Skip to content Skip to sidebar Skip to footer

Changing Text Inside A Tag Onclick

I'm trying to change the text when clicking on a button. The button was created with a div :

Solution 1:

You have:

<div class="pause" id="pause" onclick="playpause()"><a href="#">Pause</a></div>

Because you have this, the link dissapears when you set the innerHTML of the div later.

To correct your issue and keep the a from dissapearing, you need to get the right DOM reference to it:

 var anchor= document.querySelector("#pause > a");

Next, don't use inline HTML event handlers as they create spaghetti code and cause global event handling wrapper functions around your event code. These wrappers change the binding of this if used by your code.

Here's how to connect to an event handler that uses the W3C DOM Standard:

 window.addEventListener("DOMContentLoaded", function(){
     var video = document.getElementById("bgvid");
     var pauseText = document.getElementById("pause");
     var anchor= document.querySelector("#pause > a");

     pauseText.addEventListener("click", function(){

        if (video.paused){
          video.play();
          anchor.innerHTML = "Pause";
        } else {
          video.pause();
          anchor.innerHTML = "Jouer";
        }

     });
 });

Amd, note the div code I showed at the top - - it no longer has the onclick="playPasue() in it.


Solution 2:

You can use firstElementChild of pause element. I guess problem is a tag is removed

So I'm able to change the text, but it's removing the a tag and removing my style

function playpause(){

var video = document.getElementById("bgvid");
var pauseText = document.getElementById("pause").firstElementChild;

if (video.paused){
    video.play();
    pauseText.innerHTML = "Pause";
} else {
    video.pause();
    pauseText.innerHTML = "Jouer";
}

}

Solution 3:

This should work.

document.getElementById("pause").onclick = function(){

  var video = document.getElementById("bgvid");
  var pauseText = document.querySelector("#pause a");

  if (video.paused){
      video.play();
      pauseText.innerHTML = "Pause";
  }else{
      video.pause();
      pauseText.innerHTML = "Jouer";
  }


}
<!-- Got video from http://www.w3schools.com/ -->
<video width="400" id="bgvid">
  <source src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
  <source src="http://www.w3schools.com/html/mov_bbb.ogg" type="video/ogg">
  Your browser does not support HTML5 video.
</video>


<div class="pause" id="pause"><a href="#">Pause</a></div>

Solution 4:

You must use it:

function playpause() {
    document.getElementById("pause").innerHTML = "Jouer";
}
<div class="pause" id="pause" onclick="playpause()"><a href="#">Pause</a></div>

Post a Comment for "Changing Text Inside A Tag Onclick"