Yvo van Oosterum
Yvo van Oosterum

Reputation: 43

jQuery if button is not pressed

I want to check wether a button is pressed in jQuery. If the button is pressed the page has to scroll down. If the button it not pressed the page shows an animation and once this is finished it has to scroll down.

Now I have this:

$('#btmmdl').click(function(){
    $(this).data('clicked', true);
});

if($('#btmmdl').data('clicked')){
    // Scroll down
} else {
    // Show animation and scroll down after 9 seconds
}

Am I doing something wrong?

Upvotes: 1

Views: 251

Answers (5)

Yvo van Oosterum
Yvo van Oosterum

Reputation: 43

I tried a lot of solutions below but finally (through another question) found a solution that worked for me.

var scroll = setTimeout(function(){
  // Show animation and scroll down after 9 seconds
}, 9000);

$('#btmmdl').click(function(){
      // Scroll down
        clearTimeout(scroll);
    });

The clearTimeout function with the Timeout as a var did it for me, but I was nog aware of this functionality.

Thanks for the answers!

Upvotes: 0

ebraley
ebraley

Reputation: 206

The code doesn't execute in order like you think. You need to set a timeout to go off after 9000 ms and check if the button has been clicked at that point.

var $btmmdl = $('#btmmdl');

$btmmdl.click(function(){
    $(this).data('clicked', true);
    // Scroll down
});

//If the button hasn't been clicked after 9 seconds, scroll
setTimeout(function(){
  if(!$btmmdl.data('clicked')){
    // Show animation and scroll
  }
}, 9000);

Upvotes: 0

user8232179
user8232179

Reputation:

How about:

$('#btmmdl').mousedown((function(){
    //SCROLLSDOWN
});
$('#btmmdl').mouseup((function(){
   //SHOWSANIMATION
});

Upvotes: 0

JiFus
JiFus

Reputation: 968

If you are using CSS3 animations, you can use a jQuery selector to listen for the animationend to scroll down after it happens.

The gist of it:

$("#someSelector").bind("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(){ ... });

For more information check this awesome stackoverflow answer over here.

In that case you could also end the animation on click of the button, which will also trigger the scrolling down afterwards.

For more information on how to end an animation check the jQuery finish() method

Upvotes: 0

unalignedmemoryaccess
unalignedmemoryaccess

Reputation: 7441

Your problem is that click event is executed when is. You don't know when will user click on button. Therefore you have to add your if statement inside callback function and perform your task.

$('#btmmdl').click(function() {
    $(this).attr('data-clicked', !$(this).attr('data-clicked')); //Toggle status
    if ($(this).attr('data-clicked')) {
        // Scroll down
    } else {
        // Show animation and scroll down after 9 seconds
    }
});

Each click will toggle mode. First click will do scroll, second will show animation, third again scroll, etc.

Upvotes: 2

Related Questions