Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Invoking click-event of an anchor tag from javascript

Tags:

I have a page with an anchor tag. In my JavaScript I am setting the HREF attribute of the anchor tag dynamically based on some if-else conditions. Now I want to invoke the click event of the anchor tag programmatically. I used the below code, but was not successful.

var proxyImgSrc="CostMetrics.aspx?Model=" + model +"&KeepThis=true&TB_iframe=true&height=410&width=650";  document.getElementById("proxyAnchor").href=proxyImgSrc; document.getElementById("proxyAnchor").onclick; 

Can any one tell me how to go ahead? I have a jQuery light box implementation(thickbox) on this link.

Kindly advise. Thanks in advance.

like image 277
Shyju Avatar asked Jun 11 '09 12:06

Shyju


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 I hit an anchor tag in JavaScript?

Click() function is used when you want to trigger click event. ie. when you want to trigger some action when anchor tag is clicked.

How do you call Onclick in a tag function?

Try onclick function separately it can give you access to execute your function which can be used to open up a new window, for this purpose you first need to create a javascript function there you can define it and in your anchor tag you just need to call your function.


2 Answers

If you have jQuery installed then why not just do this:

$('#proxyAnchor')[0].click(); 

Note that we use [0] to specify the first element. The jQuery selector returns a jQuery instance, and calling click() on that only calls click javascript handler, not the href. Calling click() on the actual element (returned by [0]) will follow the link in an href etc.

See here for an example to illustrate the difference: http://jsfiddle.net/8hyU9/

As to why your original code is not working - it is probably because you are calling onclick, and not onclick(). Without the parenthesis JavaScript will return whatever is assigned to the onclick property, not try to execute it.

Try the following simple example to see what I mean:

var f = function() { return "Hello"; };      alert(f); alert(f()); 

The first will display the actual text of the function, while the second will display the word "Hello" as expected.

like image 160
samjudson Avatar answered Sep 21 '22 22:09

samjudson


You should call click event like this:

document.getElementById("proxyAnchor").click(); // $('#proxyAnchor').click(); 

but in your case you should set the window's location to a redirect page, if you want that.

like image 32
Canavar Avatar answered Sep 17 '22 22:09

Canavar