javascriptjqueryclickaddclassremoveclass

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.


Solution

  • 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.