Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<a href="javascript:foo(this)"> passes Window, I want the tag element itself

I expect this to print "a" because when I call foo(this), the argument seems to be the link tag.

<script type="text/javascript">     function foo (e) {         alert (e .tagName);     } </script> <a href="javascript:foo(this)">click</a> 

Instead, it prints "undefined". If I alert(e) it says "object Window". How do I make foo know which element launched it? Without passing/looking up ids.

like image 859
spraff Avatar asked Feb 16 '12 19:02

spraff


People also ask

Can we pass function in href?

The anwer is: not possible.

How do you make a href call a function?

In JavaScript, you can call a function or snippet of JavaScript code through the HREF tag of a link. This can be useful because it means that the given JavaScript code is going to automatically run for someone clicking on the link. HREF refers to the “HREF” attribute within an A LINK tag (hyperlink in HTML).

What is HREF in JavaScript?

The href attribute specifies the URL of the page the link goes to. If the href attribute is not present, the <a> tag will not be a hyperlink. Tip: You can use href="#top" or href="#" to link to the top of the current page!


1 Answers

You should not use href for JavaScript. Bad practice, instead use onclick and this will magically point to the link.

<a href="#" onclick="foo(this)">click</a> 

You also need to cancel the click action of the link. Either with return false or cancelling the event with preventDefault.

It is better to attach the event with Unobtrusive JavaScript

like image 154
epascarello Avatar answered Sep 21 '22 07:09

epascarello