views:

184

answers:

4

Hi people,

I have a problem with <a> tags.

I need to reassign an onclick event to this tag, but the href attribute must contain a link.

For example, I have some link:

<a href="http://en.wikipedia.org"&gt;Wikipedia&lt;/a&gt;

And i need to change only the onclick event for this link so that when I click on it, some JavaScript function is called.

A: 

but href attribute must contain a link

If you provide a link then the page will be redirected there, so you might want to do this:

<a href="#" onclick="func1();func2();redirect('url');">Wikipedia</a>

This makes sure that you perform your functions first and finally redirect function to redirect the page to the url you specify.

Sarfraz
Inline javascript is bad. http://robertnyman.com/2008/11/20/why-inline-css-and-javascript-code-is-such-a-bad-thing/
Tatu Ulmanen
@Tatu: you are right but i did not want the newbie to make it more complex.
Sarfraz
+1  A: 

Not sure what you mean, but try this:

$(function() {
    // Find all links pointing to wikipedia
    $("a[href*='wikipedia.org']").click(function() {
        // Do something
        return false; // to prevent the link from actually going to wikipedia
    });
});
Tatu Ulmanen
using jquery to change onclick handler for single link is overkill
Qwerty
@Qwerty, how so, if he already uses jQuery?
Tatu Ulmanen
+2  A: 

Don't forget to return false in 'onclick', or browser will handle click and open link in href.

<a href="http://en.wikipedia.org" onclick="yourfunction(this); return false;" >Wikipedia</a>
Qwerty
that will only call the function but won't redirect to en.wikipedia.org i think
Sarfraz
He didn't say he needs redirect :-)
Qwerty
Yes, that's right, i don't need redirect:) That was the problem)
Le_Coeur
A: 

The simplest way would be to give your link an id, ie

<a href="http://wikipedia.org" id="myLink">Whatever</a>

Then simply assign an onclick via jquery like so:

$("a#myLink").click(function() {
   //Go wild! 

});
Keir