Onclick() event to change the text of a button (play / pause)

Asked

Viewed 537 times

1

I have this div in my html and wanted to make the click on the play button change the text to pause and when clicking again switch to play.

var buttonControl = document.querySelector('#control');
var playNameControl = document.createTextNode('play');
var pauseNameControl = document.createTextNode('pause');

buttonControl.onclick = function control(){
    if(buttonControl.value = 'play'){
        buttonControl.innerHTML = '';
        buttonControl.appendChild(pauseNameControl);
        buttonControl.setAttribute('value','pause');
    }
    else{
        buttonControl.innerHTML = '';
        buttonControl.appendChild(playNameControl);
        buttonControl.setAttribute('value','play');
    }
}
   <div class="botoes">
        <button id="control">play</button>
   </div>

It only works for the first click. As it starts with play by clicking it ta changing to pause but clicking again there are no changes more.

1 answer

2


Honestly I think you complicated things with this code of yours, so I chose not even take advantage of it in the answer...

inserir a descrição da imagem aqui

Follow the image code above:

See that it is basically a if/else, who exchanges the .textContent of btn in the click

let btn = document.getElementById('btn');

function troca() {
    if (btn.textContent === "play") {
        btn.textContent = "pausa";
        btn.value = "pausa"
    } else {
        btn.textContent = "play";
        btn.value = "play"
    }
}

btn.addEventListener('click', troca)
<button id="btn">play</button>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.