Doc Holiday
Doc Holiday

Reputation: 10254

Javascript check to see if an event has already been fired or clicked

I have a function that needs to fire when I click on a chevron tab. However I only need that function to fire that first time we load the page. How can I prevent it form firing every time the tab is clicked?

    $('#navi a').bind('click',function(e){
        var $this   = $(this);
        var prevButton  = current;
        $this.closest('ul').find('li').removeClass('selected');

        if ( $(this).attr('id') == 'tab2')
        {
            //fire function only once
        }

    });

Upvotes: 0

Views: 3388

Answers (3)

Alexander
Alexander

Reputation: 12785

In case you need only part of your event handler to run once :

$("div").on("click",function(){
    if (!$(this).data("fired")) {
        console.log("Running once");
        $(this).data("fired",true);
    }

    console.log("Things as usual");
});

Demo

Upvotes: 2

Milind Anantwar
Milind Anantwar

Reputation: 82231

Use:

var isalreadyclicked=false;
  $('#navi a').bind('click',function(e){
    var $this   = $(this);
    var prevButton  = current;
    $this.closest('ul').find('li').removeClass('selected');

    if ( $(this).attr('id') == 'tab2')
    {
    if(!isalreadyclicked){
        //fire function only once
    isalreadyclicked=true;
    }
    }

  });

Upvotes: 1

Brad Christie
Brad Christie

Reputation: 101604

Use the .one binding instead. This will attach it to fire on the first click and remove itself.

Upvotes: 3

Related Questions