Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I programmatically invoke an onclick() event from a anchor tag while keeping the ‘this’ reference in the onclick function?

The following doesn't work... (at least not in Firefox: document.getElementById('linkid').click() is not a function)

<script type="text/javascript">     function doOnClick() {         document.getElementById('linkid').click();         //Should alert('/testlocation');     } </script> <a id="linkid" href="/testlocation" onclick="alert(this.href);">Testlink</a> 
like image 473
Ropstah Avatar asked May 25 '09 12:05

Ropstah


People also ask

Can we use onclick event on anchor tag?

Using onclick Event: The onclick event attribute works when the user click on the button. When mouse clicked on the button then the button acts like a link and redirect page into the given location. Using button tag inside <a> tag: This method create a button inside anchor tag.

How do you link onclick events?

We can use a button to link different pages. We will connect the url of the new page to the onclick event of the button. We can do this by using a form and a submit button but there is no point in using a form for a hyper linking of pages. So here are some examples of using buttons to link different pages.


2 Answers

You need to apply the event handler in the context of that element:

var elem = document.getElementById("linkid"); if (typeof elem.onclick == "function") {     elem.onclick.apply(elem); } 

Otherwise this would reference the context the above code is executed in.

like image 84
Gumbo Avatar answered Oct 11 '22 02:10

Gumbo


The best way to solve this is to use Vanilla JS, but if you are already using jQuery, there´s a very easy solution:

<script type="text/javascript">     function doOnClick() {         $('#linkid').click();     } </script> <a id="linkid" href="/testlocation" onclick="alert(this.href);">Testlink</a> 

Tested in IE8-10, Chrome, Firefox.

like image 27
andyrandy Avatar answered Oct 11 '22 02:10

andyrandy