Paule Anne Paule Anne - 6 months ago 11
jQuery Question

Perform different actions with a button based on the data attribute

I have one button. His first action is to stop a video. Then it's icon change and data-status too. His second action is to reload the page.

The problem is that I can't do the second even if I code some conditions. Sometimes it don't do anything, sometimes the second action comes at the same time of the first one.

Here is my Jquery code:

// STOP VIDEO (ACTION 1)
$("#button").click(function(){
$('#button').attr({
src: 'img/film.png',
'data-status':'stop'
});
});

// RELOAD (ACTION 2)
$("#button[data-status='stop']").click(function() {
location.reload();
});

// OTHER METHOD FOR RELOAD (ACTION 2)
if ($("#button").data( "status", "stop" )) {
$("#button").click(function() {
location.reload();
});
}


Here is my HTML code:

<img id="button" src="skip.png" data-status="play">


Can you help me?

Answer

By binding the click event multiple times, you're firing both the functions on the second click. Instead, you should put the logic that decides to stop/reload inside the one event callback:

$("#button").click(function(){
    var button = $(this);

    if(button.attr('data-status') === 'stop') {
        // Already stopped
        location.reload();

    } else {
        // Stop
        button.attr({
            src: 'img/film.png',
            'data-status':'stop'
        )};
    }
)};