Bill Bob
Bill Bob

Reputation: 21

How do I call a jQuery function on an a with href?

I have a binded jquery function on an a element with a href attribute

If the a has no href attribute, the function bound to the click event will fire

If it has a href attribute it wont

Help?

Upvotes: 2

Views: 7143

Answers (6)

Felipe
Felipe

Reputation: 1

Here is a simple solution

href="javascript:alert('Hello');"

Upvotes: -1

daanl
daanl

Reputation: 44

Better use javascript:void(0); in anchor tag -> http://www.tizag.com/javascriptT/javascriptvoid.php

Upvotes: 0

Tomm
Tomm

Reputation: 2142

$("a").click(function() {
    if(!$(this).attr("href")) {
       //fire
   } 
});

Upvotes: 0

Paul
Paul

Reputation: 141829

I think your problem is that the event is indeed firing, but since you have an <a> with an href the browser is also reloading or switching pages. If you want to prevent that behavior you need to return false; from you click event.

Upvotes: 1

Jared Farrish
Jared Farrish

Reputation: 49188

I imagine you want to return false from your handler, which will cancel the ANCHOR's following the HREF.

<a href="http://www.yahoo.com" id="test">Test</a>

$('#test').click(function(){
    alert('test');
    return false;
});

http://jsfiddle.net/MysjS/

Upvotes: 2

Ewout Kleinsmann
Ewout Kleinsmann

Reputation: 1297

Try this:

$('a').click(function(e) {
    e.preventDefault(); //preventing the link from being followed.
    // your code
});

Upvotes: 1

Related Questions