views:

78

answers:

4

Hi!

I would like to know how I can rebind the previous behavior of a normal link! example:

function removeDefaultBehaviour(objects){
    objects.each(function(){
        $(this).data('onclick',$(this).attr('onclick'));
        $(this).attr('onclick','return false;'); 
    });
};

function addDefaultBehaviour(objects){
    objects.each(function(){
        if($(this).data('onclick')!='')
            $(this).attr('onclick',$(this).data('onclick'));
    });
};

I tried to store the previous behavior in the data object of each link. But this didn't work! Any suggestions, how to restore the previous and default behavior of a link! Thx

Markus

A: 

Try this:

function removeDefaultBehaviour(objects){
    objects.each(function(){
        $(this).data('onclick',$(this).attr('onclick').toString());
        $(this).attr('onclick','return false;'); 
    });
};

Without the toString() function, you won't get the code contents of the onclick event, you just get "onclick(event)".

Frank DeRosa
A: 

Don't try to handle onclick and other event handlers as strings, as DOM setAttribute or jQuery attr would do. Functions cannot be adequately serialised to a string. Instead use the normal DOM event handler properties such as element.onclick to get and set the real function objects:

function falsefunction() {
    return false;
}
function nofunction() {
    return;
}

function removeDefaultBehaviour(objects){
    objects.each(function(){
        if (this.onclick)
            $(this).data('onclick', this.onclick);
        this.onclick= falsefunction;
    });
}

function restoreDefaultBehaviour(objects){
    objects.each(function(){
        var onclick= $(this).data('onclick');
        this.onclick= onclick? onclick : nofunction;
    });
}

However, juggling event handlers like this is a bit of a smell and usually suggests you'd be better off using bind:

function preventDefault(event) {
    event.preventDefault();
}

function removeDefaultBehaviour(objects){
    objects.bind('click', preventDefault); // or objects.click(preventDefault);
}

function restoreDefaultBehaviour(objects){
    objects.unbind('click', preventDefault);
}
bobince
Thx a lot! Your 2nd suggestion is awesome! ;)
Markus Bürgler
A: 

The data returned by $(this).attr('onclick') is most likely a function.

Thus on setting you would need to wrap it into a function again

$(this).attr('onclick',function(){return $(this).data('onclick')});

else the function gets executed instead of being set.

jitter
A: 

Try:

$(selector).unbind('click');

You could also have a look at jQuery's namespaced events for kicks: http://docs.jquery.com/Namespaced_Events

antti_s