call javascript function on hyperlink click

JavascriptHyperlink

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

The simplest answer of all is...

<a href="javascript:alert('You clicked!')">My link</a>

Or to answer the question of calling a javascript function:

<script type="text/javascript">
function myFunction(myMessage) {
    alert(myMessage);
}
</script>

<a href="javascript:myFunction('You clicked!')">My link</a>

Solution 3 - Javascript

With the onclick parameter...

<a href='http://www.google.com' onclick='myJavaScriptFunction();'>mylink</a>

Solution 4 - Javascript

The JQuery answer. Since JavaScript was invented in order to develop JQuery, I am giving you an example in JQuery doing this:

<div class="menu">
    <a href="http://example.org">Example</a>
    <a href="http://foobar.com">Foobar.com</a>
</div>

<script>
jQuery( 'div.menu a' )
	.click(function() {
		do_the_click( this.href );
		return false;
	});

// play the funky music white boy
function do_the_click( url )
{
	alert( url );
}
</script>

Solution 5 - Javascript

I prefer using the onclick method rather than the href for javascript hyperlinks. And always use alerts to determine what value do you have.

<a href='#' onclick='jsFunction();alert('it works!');'>Link</a>

It could be also used on input tags eg.

<input type='button' value='Submit' onclick='jsFunction();alert('it works!');'>

Solution 6 - Javascript

Ideally I would avoid generating links in you code behind altogether as your code will need recompiling every time you want to make a change to the 'markup' of each of those links. If you have to do it I would not embed your javascript 'calls' inside your HTML, it's a bad practice altogether, your markup should describe your document not what it does, thats the job of your javascript.

Use an approach where you have a specific id for each element (or class if its common functionality) and then use Progressive Enhancement to add the event handler(s), something like:

[c# example only probably not the way you're writing out your js]
Response.Write("<a href=\"/link/for/javascriptDisabled/Browsers.aspx\" id=\"uxAncMyLink\">My Link</a>");
    
[Javascript]  
document.getElementById('uxAncMyLink').onclick = function(e){
    
// do some stuff here
    
    return false;
    }

That way your code won't break for users with JS disabled and it will have a clear seperation of concerns.

Hope that is of use.

Solution 7 - Javascript

Use the onclick HTML attribute.

> The onclick event handler captures a > click event from the users’ mouse > button on the element to which the > onclick attribute is applied. This > action usually results in a call to a > script method such as a JavaScript > function [...]

Solution 8 - Javascript

I would generally recommend using element.attachEvent (IE) or element.addEventListener (other browsers) over setting the onclick event directly as the latter will replace any existing event handlers for that element.

attachEvent / addEventListening allow multiple event handlers to be created.

Solution 9 - Javascript

If you do not wait for the page to be loaded you will not be able to select the element by id. This solution should work for anyone having trouble getting the code to execute

<script type="text/javascript">
window.onload = function() {
    document.getElementById("delete").onclick = function() {myFunction()};
	
	function myFunction() {
        //your code goes here
	    alert('Alert message here');
	}
};
</script>

<a href='#' id='delete'>Delete Document</a>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionErnieStingsView Question on Stackoverflow
Solution 1 - Javascriptkarim79View Answer on Stackoverflow
Solution 2 - JavascriptJayden LawsonView Answer on Stackoverflow
Solution 3 - JavascriptamischiefrView Answer on Stackoverflow
Solution 4 - JavascriptelcucoView Answer on Stackoverflow
Solution 5 - JavascriptMarkyView Answer on Stackoverflow
Solution 6 - JavascriptLewisView Answer on Stackoverflow
Solution 7 - JavascriptDonutView Answer on Stackoverflow
Solution 8 - JavascriptSimonView Answer on Stackoverflow
Solution 9 - Javascriptuser2197701View Answer on Stackoverflow