Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call javascript function on hyperlink click

I am dynamically creating a hyperlink in the c# code behind file of ASP.NET. I need to call a JavaScript function on client click. how do i accomplish this?

like image 433
ErnieStings Avatar asked Aug 12 '09 12:08

ErnieStings


People also ask

Is it possible to use a hyperlink to call a JavaScript function?

1. Call JavaScript on Hyperlink Click. Add below HREF html code in body section and access on web browser. Now just click link, It will execute JavaScript's myFunction which will show current date as per used above.

Can Link have onclick function?

This is a type of JavaScript link - the onclick attribute defines a JavaScript action when the 'onclick' event for the link is triggered (i.e. when a user clicks the link) - and there is a URL present itself in the onclick attribute.


1 Answers

Neater still, instead of the typical href="#" or href="javascript:void" or href="whatever", I think this makes much more sense:

var el = document.getElementById('foo'); el.onclick = showFoo;   function showFoo() {   alert('I am foo!');   return false; }  <a href="no-javascript.html" title="Get some foo!" id="foo">Show me some foo</a> 

If Javascript fails, there is some feedback. Furthermore, erratic behavior (page jumping in the case of href="#", visiting the same page in the case of href="") is eliminated.

like image 143
karim79 Avatar answered Sep 25 '22 19:09

karim79