1

In our page we have a slew of anchor tags to which we dynamically attach click handlers. In such a case what is the best way to keep an anchor tag in the mark up?

Currently we have

<a href="javascript:void(0);" >....</a>

We need void value for href as some of them may not get attached with click handlers.

Adam Rackis
  • 82,527
  • 56
  • 270
  • 393
ChrisOdney
  • 6,066
  • 10
  • 38
  • 48
  • The absolute _best_ thing to put in the href attribute would obviously be a URL which performs the same action the JS event handler does. Edit: If that's impossible then use #. – powerbuoy Jan 05 '12 at 06:16
  • Using # is a problem when someone clicks on it. – ChrisOdney Jan 05 '12 at 15:18
  • 1
    Well you'd have to prevent the default behaviour of the link either by returning false from the event handler or using the `preventDefault()` method of the event object. – powerbuoy Jan 05 '12 at 18:03

3 Answers3

1

Returning false from a jQuery event handler will prevent the default behavior (and bubbling) for you. There's no need to mess with the href attribute (though that won't hurt).

$(document).on("click", "a.yourSelector", function(){
    //your code

    return false;
});

Or of course jQuery pre 1.7

$(document).delegate("a.yourSelector", "click", function(){
    //your code

    return false;
});

For more information on cancelling dom events, see this question (and answer) and this link

Community
  • 1
  • 1
Adam Rackis
  • 82,527
  • 56
  • 270
  • 393
1

Ommit the href-attribute and when assigning the onclick also set the cursor-style of the elements to "pointer" , otherwise users with JS disabled will be confused when clicking on the elements and nothing happens.

Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
  • Comparing an anchor with href and without href, is the cursor:pointer style the only difference? Ommiting href came to my mind, was not sure how it would behave in different browsers. – ChrisOdney Jan 05 '12 at 15:21
  • I don't see any difference in that special case, you only use the href-attribute to have the special cursor, this can be done using CSS(in fact you don't need to use a ``-element, it can be any element) – Dr.Molle Jan 05 '12 at 22:15
0

The simpler code would be like this:

<a href='#' class='do-stuff'>Link</a>

The "#" sign keeps the html code clean, and readable

jQuery(document).ready(function() {

  jQuery(".do-stuff").click(function() {
    alert("clicked"); 
    return false; // disables default link action
  });

});