Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger click event on href element

I'm trying to trigger click event on hyperlink with jQuery like the way below. Hyperlink does not have any id but it does have css class:

$(document).ready(function () {     $('.cssbuttongo').trigger('click');  });  

The function above is not working. This is the hyperlink:

<a href="hyperlinkurl" class="cssbuttongo">hyperlink anchor</a> 
like image 488
MonsterMMORPG Avatar asked Nov 03 '11 18:11

MonsterMMORPG


People also ask

How do you trigger a click event for a hyperlink?

Answer: Use the jQuery click() Method You can use the click() method to trigger a click on a link programmatically using jQuery.

How do you trigger a click element?

The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.

How can add trigger click event in jQuery?

When an event handler is added using . on( "click", function() {...} ) , it can be triggered using jQuery's . trigger( "click" ) because jQuery stores a reference to that handler when it is originally added. Additionally, it will trigger the JavaScript inside the onclick attribute.

How do I trigger a click event without clicking?

If you want native JS to trigger click event without clicking then use the element id and click() method of JavaScript.


2 Answers

The native DOM method does the right thing:

$('.cssbuttongo')[0].click();                   ^               Important! 

This works regardless of whether the href is a URL, a fragment (e.g. #blah) or even a javascript:.

Note that this calls the DOM click method instead of the jQuery click method (which is very incomplete and completely ignores href).

like image 52
Roman Starkov Avatar answered Oct 05 '22 20:10

Roman Starkov


I do not have factual evidence to prove this but I already ran into this issue. It seems that triggering a click() event on an <a> tag doesn't seem to behave the same way you would expect with say, a input button.

The workaround I employed was to set the location.href property on the window which causes the browser to load the request resource like so:

$(document).ready(function() {       var href = $('.cssbuttongo').attr('href');       window.location.href = href; //causes the browser to refresh and load the requested url    }); }); 

Edit:

I would make a js fiddle but the nature of the question intermixed with how jsfiddle uses an iframe to render code makes that a no go.

like image 42
Matthew Cox Avatar answered Oct 05 '22 19:10

Matthew Cox