views:

5308

answers:

9

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?

thanks in advance

A: 
<a href="static-version.html" id="myLink">Text to Click</a>

<script type="text/javascript">
    document.getElementById("myLink").onclick = function() { 
        ... ; 
        return false; 
    }
</script>

I initially scrubbed my answer in favor of karim79's (which is still a fantastic improvement on my initial answer), but realized we didn't even need to add non-existent anchors as long as the function we're calling returns false.

Chris Pebble
If the function returns false see the result.
rahul
This breaks the (extremely valuable) event model in JS, and doesn't degrade gracefully.
Rex M
as per the last comment. And also you'll need to recompile if you ever want to change your Javascript, or your HTML.
Lewis
-1 How did this get accepted? ... don't ever use the JavaScript pseudo protocol (unless you're creating a bookmarklet) and what's with being so obtrusive?
J-P
agree with Rex M and J-P, this is answer is lol! -1 so clueless ppl don´t take advice from it.
anddoutoi
I don't know why you were downmodded! We certainly should mention the javascript protocol here and discuss why it's fallen out of favor." It's been censored away!
ראובן
@Chris Pebble - note that 'best practice' is to have something in the href that does something if all else fails. Please see my edit.
karim79
A: 

With the onclick parameter...

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

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 [...]

Donut
+14  A: 

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 behaviour (page jumping in the case of href="#", visiting the same page in the case of href="") is eliminated.

karim79
+1 This is currently the only unobtrusive answer. +100 if I could.
J-P
The href="#" make the page scroll up to the top if the page is scrolled, because it's used to go to a named anchor and if there is no name the page goes to the top? This is my experience and it's so annoying.
Charlie boy
This will work, but what happens if the user has Javascript disabled, or some JS breaks wlswhere and stops the handler from working?
Lewis
If you set href="#null" instead of just href="#", the page will not scroll to the top when the link is clicked, whether you return false from the javascript or not. You still get "#null" appended to your window.location.hash, but that may be more acceptable than having the page jump around.
Chris Nielsen
why use a named anchor at all though? What about accessibility - screen readers and such like? Should they be presented with a link that does nothing? Surely there should be a fallback to another page - even if its just a page that explains that you have to have javascript enabled to use this feature!
Lewis
@Lewis, yes, ideally <a> tags wouldn't be used for pure js calls, but unfortunately older browsers didn't support :hover for non-link elements. So links were often used to trigger js events.
Chris Pebble
@Chris - I'm not sure you get my point Chris. I'm suggesting that you don't use <a href="#">Do nothing</a> and instead use <a href="a/link/somwhere.html">Do something</a> and then use progressive enhancement to override the href. This is the cleanest solution. Anchors are fine, but they should do SOMETHING if javascript is disabled - or for some reason (as per IE6) some javascript broke before the handler was created and assigned. This way all of your users are happy.
Lewis
@Lewis, see my edit please.
karim79
+2  A: 

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.

Lewis
A: 

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.

Simon
+2  A: 

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"&gt;Example&lt;/a&gt;
    <a href="http://foobar.com"&gt;Foobar.com&lt;/a&gt;
</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>
elcuco
A: 

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!');'>

Marky
A: 

var foo = '<?= $foo ?>';

seanp2k