DelphiFAQ Home Search:

Connect a javascript function to a clickable link using onclick or href property?

 

comments3 comments. Current rating: 5 stars (1 votes). Leave comments and/ or rate it.

Question:

Should I connect a javascript function to a clickable link using the onclick or the href property?

Answer:

Indeed there are these two possiblities as shown in the box below.

The first solution has the disadvantage that if have say for example an animated GIF image in your page and the user clicks the javascript: protocol link, then the animation will quit running and you have to refresh the page to start it again.

The problem with the second solution is that your browser will jump to the top of the page (href=#).
If onclick returns false, the browser never even looks at the href attribute, and so it is not followed. Thus you should add ; return false; to the onclick event handler.

The third example shows how it this looks like.

If you also want to be able to handle users who have javascript disabled, then take a look at example four.

If javascript is disabled then the browser ignores the onclick handler and loads the url given in the href property. The assumption here is that your page is generated by myform.php and you have to have some server side code (php, perl..) that parses the argument '?fillform=1' and then does the same functionality on the server side what normally your clientside javascript would have done.

<!-- two possibilities to link an event handler to a clickable link -->
<a href="javascript:fillform()">Pre-Fill</a>

<a href="#" onclick="fillform()">Pre-Fill</a>

<!-- this is the best way to do it: -->
<a href="#" onclick="fillform(); return false;">Pre-Fill</a>

<!-- like #3 but also takes care of people with javascript disabled -->
<a href="myform.php?fillform=1" onclick="fillform(); return false;">Pre-Fill</a>

Content-type: text/html

Comments:

2008-09-04, 01:52:58
anonymous  
http://skazhu.kz - казахстан интернет
http://soto4ka.ru - обзор сотовых телефонов
http://destiny.kz - казахские песни
http://vmiretain.net - тайны
http://rusfraz.ru - фразеологизмы
2012-05-03, 11:29:51
anonymous from Romania  
<script type='text/javascript'>

</script>
2014-03-15, 16:31:24
anonymous  
rating
oh ... good . thank you so much

 

 

NEW: Optional: Register   Login
Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option, or post under a registered account.
 

Show city and country
Show country only
Hide my location
You can mark text as 'quoted' by putting [quote] .. [/quote] around it.
Please type in the code:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity.
The owner of this web site reserves the right to delete such material.

photo Add a picture: