views:

733

answers:

3

Hi fellow programmer

I have an achor like this

<a href='#' onclick='return showform(this)'>click me</a>

But I want to be able to override the onclick function, how to do this in jquery?

because it seems when I add

$('a').click( function() { alert('hi there!'); } );

the new click handler is not overriding the old one

+1  A: 

If you're using jQuery like this, you don't want any handlers in the HTML. Can't you just remove the onClick attribute?

If you're worried about breaking stuff, search and replace on:

 onclick='return showform(this)'

and replace with

class='showform'

Then you can do:

$('a.showform').click(function (e) {
    e.preventDefault();
    return showform(this);
});

which will keep your existing handlers working.

Skilldrick
A: 

In your case the onCick event is overriding the jQuery one. What you might be able to do is:

$('a').unbind('click').click(function{
    alert('why hello there children.');
})

But I believe this would have to be included after the

<a href='#' onclick='return showform(this)'>click me</a>

That said, you should really not be using onClicks anyway... it makes the code really hard to maintain and change (as you have found out).

SeanJA
If you're following Yahoo, all scripts are included at the end of the page anyway...
Skilldrick
That is true, I figured I should point that part out though, as the last onclick event should override the rest no?
SeanJA
It depends when $('a').unbind() is called. If it's in $(document).ready() then it could be in the `head` and still work.
Skilldrick
I am not 100% certain, but I think that unbind can't remove a handler that hasn't been set up with jQuery.
kgiannakakis
Ya, I am not sure about that either, I tend to not write my code with onClicks.
SeanJA
I really can't see any good reason to use `onClick`s.
Skilldrick
+1  A: 

Have you tried something like this:

$("a").removeAttr("onclick");
kgiannakakis