views:

148

answers:

2

Hi everyone!

I'm having some trouble with this javascript (using jQuery):

$(a).click(function(){
    alert('hi')
    this.unbind.click(function(){
     doSomethingElse(this);
    })
})

When a is clicked, it is supposed to reassign its own click event. Unfortunately, it fires the second click event as well. I know this is to do with propagation, but I can't work out how to stop this behaviour.

Any ideas?

Sam

+2  A: 

Just return false from the callback:

$(a).click(function(){
    alert('hi')
    this.unbind.click(function(){
        doSomethingElse(this);
    });
    return false;
});
Darin Dimitrov
+3  A: 
$(a).click(function(e){
    alert('hi')
    $(this).unbind('click', arguments.callee).click(function(){
        doSomethingElse(this);
    })
    e.preventDefault();
})
David
preventDefault() is JQuery's official way of stopping what typically happens on an event. I believe it just returns false, but I'd say it's safer to use the API call.
Broam
actually, preventDefault() is a part of DOM level 2: http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-Event-preventDefault but IE ignores it by default. jQuery adresses this and returns false if browser == IE
David
Thanks guys! Helped a lot, although I still do have some trouble, I abandoned some of my more useless features :P
Gausie