Hello all.

Which is the best practice to use when creating dynamic links i.e. onclick events.

<a href="javascript:somefunction()">click me</a>

OR

<a href="javascript:void(0)" onclick="somefunction()">click me</a>

i realise the first is not an 'event' but i have a web app which is displaying 6000 of these links all at one time and am unsure which is taking up more of my processor by dynamically creating onclick events or adding the javascript function in the href ?

also could anyone tell me if there are compatibility problems with either method. thanks for your help

Recommended Answers

All 13 Replies

Like you said, since 'href' isn't an event handler I wouldn't have much faith in the first approach and I have never seen it being used in a professional environment.

The same issue occurs with the second approach since you end up calling a function inside the 'href'. A better way would be to use :

<a href="#" onclick="myFunction();">Take me away</a>

> unsure which is taking up more of my processor by dynamically creating onclick events
Profiling your application is the way to go here.

The same issue occurs with the second approach since you end up calling a function inside the 'href'. A better way would be to use :

<a href="#" onclick="myFunction();">Take me away</a>

i have been using this practice for years but have come across a problem. using '#' will refresh the view of the page (thus if having scrolled miles down a page, resulting in a lovely jerk back to the top)

in the web app i am writing this just cannot happen.

i have 2 frames and
the left frame contains a tree, i fell flat on my face using built in asp.net trees so had to manually create one using dynamic javascript. the tree works perfectly and is at least 10 times faster than the .net version but i cannot use '#' for the very reason above.

is there any other way of stopping the anchor tag posting back ?

i do not wish to add 2 (onmouseover & onmouseout) events just to make it appear like a link.

How about ditching anchor tag all-together?

<span style="cursor: hand; display: block;" onclick="alert('You clicked me');">Click Me</span>

i do not wish to add 2 (onmouseover & onmouseout) events just to make it appear like a link.

Use css behaviours instead.

i have been using this practice for years but have come across a problem. using '#' will refresh the view of the page (thus if having scrolled miles down a page, resulting in a lovely jerk back to the top)

Try: <a href="#" onclick="some_function( );[B]return false;[/B]" /> I haven't tested it, but, it's advocated here: http://blog.reindel.com/2006/08/11/a-hrefjavascriptvoid0-avoid-the-void/, and it makes sense in theory.

How about ditching anchor tag all-together?
...

Use css behaviours instead.

This is ideal in theory, but older browsers ( i.e. IE6 ) don't support the :hover psuedoclass for any element except <a>, and the :visited psuedoclass _certainly_ won't work in this context in any browser. However, new browsers seem to be supporting :hover on any element, which is a good thing.

I just tries return false and it worked for me. It did occurr to me to return false from the javascript function but that smelled liked bad programming practice. Placing it directly in the anchor element feels better.

Placing it directly in the anchor element feels better.

If you mean directly in the href attribute of an anchor element; href isn't an event handler.. so that smells worse to me.

I guess the event chain for a user click on an <a> element is something like: ( ignoring mousedown, mouseup, mouseover, and mouseout events )

if( onclick( ) ){ if (href ){ [navigate to href] } }

If you mean directly in the href attribute of an anchor element; href isn't an event handler.. so that smells worse to me.

No I was agreeing with where you had placed it. I had forgotton you can have multiple statements in an onclick attribute seperated by semi-colons.

Ah yep, I get it. Hm.. thinking about it though.. Fungus1487; you could save a bit of transmission bandwidth with 6000 links involved, if you onclick="return some_function()" and make sure some_function always returns false.
In uncompressed 8bit ASCII; the dif between:

return some_function() 
some_function();return false

is 6 characters per link, meaning you'll potentially save {about} 36KB on 6000 links of the same type.. =P

Smells understandable in this circumstance.

Or better yet to put a piece of code in 'onload' which loops through all the links or links based on a given class and just attach a function to the 'onclick' event handler if what he needs is a common or almost common behavior for those links...

If all the functions are equal with equal parameters, or equal ( or derivable ) functions where the parameters can be easily derived programatically per link, i.e. via setting some dummy property on the link and using it to generate or lookup the function parameters. Otherwise I can invisage an equally huge JS file... Plus, it would take some noticable, although not restrictive, post-load time to dynamically set the onload property for 6000 links..

But in return of all this you get flexibility, the ability to change the logic without sifting through 6000 lines of your markup. Plus the load times would be less than or at the most equal to the time taken to set onclick on 6000 links by hardcoding them.

I guess this is one of those choices the OP would have to make based on his requirements.

>>I guess this is one of those choices the OP would have to make based on his requirements.

Pretty much.

>> But in return of all this you get flexibility, the ability to change the logic without sifting through 6000 lines of your markup. Plus the load times would be less than or at the most equal to the time taken to set onclick on 6000 links by hardcoding them.

I would debate that using JS to generate onclick handlers could save much on download time and configurabilty unless the functions and their parameters can be derived automatically with a minimum of link-specific information hardcoded anywhere in either the JS or HTML. i.e, for extreme example cases:

( hardcoded )

<a href="#" onclick="return sf('data01')"/>

= association between a's and click handlers is hardest, function name can't be changed easily, most flexible; because different functions can be called.

( changing 'c' classed 'a' elements to call an onclick function with a parameter equal to the a's id )

<a href="#" class="c" id="data01"/>

=association between a's and click handlers is medium, function name can be changed in JS, but id's have to be changed in HTML and function name can't be changed ( unless more than one class is used ), there is a noteable decrease in HTML size, but at a runtime cost compared to hardcoding. Small JS file also. Might be optimum, might not. Especially when considering that you can't legally put all characters in an 'id' attribute.. perhaps would be better to use id's as a lookup into a collection/dictionary, but then the size of the JS + HTML exceeds the size of the hardcoded HTML.

( changing 'c' classed 'a' elements to call an onclick function with a parameter pulled from an array , based on the order of the classed a's ( very messy ) )

in JS: link_data[0] = 'data01';
...
in HTML:<a href="#" class="c"/>

=association between a's and click handlers is weak, but highly confusing to change anything. Very little benefit in the smaller HTML, because the JS becomes massive. Not recommended.

Of course... if your some_func( ) really takes no parameters, and is always the same call, ( aside from the obvious question; why have 6000 of them?? ) generating the onclick handler from JS will always save alot of download bandwidth..

thanks all for your replies.

i have tested both methods and there is very little load time difference between each case. onclick is generally faster but i find myself having to add the

element.href = 'javascsript:void(0)';

anyway to stop to postback

BUT

after some soul searching found this why not to use href="javascript"

and i qoute

eventually coming across a post on Microsoft’s Web site. It strongly suggested not using javascript:; in the href… ever.

this pretty much summed up what i have got to do. Considering this web app is built for IE only on a local intranet i have tried the method suggested above to append the ONCLICK with return false; and have had no troubles.

dont ask me why IE only, suffice to say the companies i am writing for are local councils and all have stressed they will never use any other browser except IE (which means they will never use a decent browser) but thanks again to all who commented

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.