richardaum
richardaum

Reputation: 6777

JavaScript/jQuery - Reusing the event 'Click' of an element

I have an element, a div, for example. And attach an event 'click' to it. In jQuery, it would be:

 $('#myDiv').click(function(){ 
    $(".class1").show();
 })

Now, I would like to assign a new function "myDiv #", replacing the old. I am doing so:

$('#myDiv').click(function(){ 
    $(".class23").hide();
})

But when I run the 'click' on the div, the function I assigns the beginning of this doubt is performed.

Question: How to remove the function that will run with the click event attributed to an element? (No recreate the element with the new click event...)

Upvotes: 1

Views: 548

Answers (4)

hyperslug
hyperslug

Reputation: 3623

If you know you'll only want to handle one click on an element, you can use one() which automatically unbinds after a single click:

$("#myDiv").one("click", function() {  
  $(".class1").show();
  $("#myDiv").one("click", function(){ 
    $(".class23").hide();
  });
});

Upvotes: 2

Gianpaolo Di Nino
Gianpaolo Di Nino

Reputation: 1147

Add a counter on the first click event.

var counter = 0;
$('#myDiv').click(function(){ 
    if(counter>1){
       $(".class23").hide();
    }
    else
       $(".class1").show();

   counter++;
 })

just an example..

Upvotes: 0

Jayendra
Jayendra

Reputation: 52779

Use the JQuery unbind function to remove all click events

$('#myDiv').unbind('click');

Upvotes: 0

pimvdb
pimvdb

Reputation: 154848

You want .unbind.

You can either remove all previous bound functions:

$('#myDiv').unbind('click');

Or if you only want to unbind one specific function:

var show = function() { 
   $(".class1").show();
};

$('#myDiv').click(show);

and then:

$('#myDiv').unbind('click', show); // unbind first function

$('#myDiv').click(function() {     // bind second function
    $(".class23").hide();
});

Note that .click(func) is just a shortcut to .bind('click', func).

Upvotes: 4

Related Questions