简体   繁体   中英

Execute .click(function () only first click

I trying to Execute given .click(function() only on first click, but it always Execute when click.

It's works when click .more-post-button it will add class loading to .main ul and show-more-post to .main li after that remove Class loading on setTimeout function 7 second.

JS :

$(".more-post-button").click(function () {

  $('.main ul').addClass('loading');
  $('.main li').addClass('show-more-post');
  setTimeout(function(){
    $('.main ul').removeClass('loading');
  },7000);

});

My question is how to do this for only on first click, not every time click.
Thanks in advance.

Try:

$(".more-post-button").one("click", function () {

  $('.main ul').addClass('loading');
  $('.main li').addClass('show-more-post');
  setTimeout(function(){
    $('.main ul').removeClass('loading');
  },7000);
});

http://api.jquery.com/one/

It'll handle it only once.

Why complicating things, try a simple closure on that. You won't pollute globale name space, too! Demo goes here

(function(){
'use-strict';

var button = document.getElementsByTagName('button')[0];
var myHandler = function() {
    var click = 0;
    return function() {
        if(click === 0) {
            alert('single click');
        }
        click++;
    }
}();


button.addEventListener('click', myHandler, false);
})();

I would use jQuery's .one() function. This attaches a handler that will only fire once.

Modified JS

$(".more-post-button").one("click", function () {

  $('.main ul').addClass('loading');
  $('.main li').addClass('show-more-post');
  setTimeout(function(){
    $('.main ul').removeClass('loading');
  },1000);

});

Fiddle

Actually you can send in the addEventListener an option { once: true } to tell it to fire only once. So adding up to @fubbe and also using only javascript, it would be:

var button = document.getElementsByTagName('button')[0];
var handler = function () { alert('once click'); };

button.addEventListener("click", handler, {once: true});

Source :

save it in a variable:

var clicked = false;

  $(".more-post-button").click(function () {
  if(!clicked) {
  clicked = true;
  $('.main ul').addClass('loading');
  $('.main li').addClass('show-more-post');
  setTimeout(function(){
    $('.main ul').removeClass('loading');
  },7000);
}
});

Use unbind in your function to remove all events

$(this).unbind();

From jQuery 1.7 .off is the recommended way

$(this).off();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM