Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ideal value for <a href="?"> when used for a JS event? [duplicate]

I've got a link I want to appear on my page,

 <a>add another</a>

But it doesn't look like a link unless I add an href attribute. I'm going to be using jquery to add a .click() event to it, so it doesn't really need anything else.

What's the best value to href to? #? javascript:void(0)? My concern is if someone clicks it before the .click() event gets added or something. # will scroll them to the top of the page, void(0) looks kinda nasty and isn't informative if they look at the address bar...

like image 720
mpen Avatar asked Nov 22 '25 09:11

mpen


2 Answers

The ideal href attribute would be to link to a URL that will perform the same action for visitors that don't have JavaScript enabled. If that's unnecessary, I typically use href="#" and I haven't had any issues with that.

like image 88
Steve Hansell Avatar answered Nov 24 '25 23:11

Steve Hansell


My suggestion is to have the link take them to an action that would "do the right thing" if javascript were turned off completely. By that I mean that it should result in the same effect as the client-side actions, if at all possible, or some set of steps that would result in the same effect. If this isn't possible or desirable, then you shouldn't display the link until the handler has been applied. That is, initially have it "display: none; then do a show() after the event handler has been applied.

<a href="/something/add" class="add-item javascript-only">Add Another</a>

<script type="text/javascript">
   $(function() {
       $('.add-item').click( function() {
           ...
           return false; // important!
       });
       $('.javascript-only').show();
  });
</script>
like image 37
tvanfosson Avatar answered Nov 24 '25 23:11

tvanfosson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!