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.
The click method is intended to be used with INPUT elements of type button, checkbox, radio, reset or submit. Gecko does not implement the click method on other elements that might be expected to respond to mouse–clicks such as links (A elements), nor will it necessarily fire the click event of other elements.
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.
Try the following:
$("#myanchor")[0].click()
As simple as that.
There's a difference in invoking the click
event (does not do the redirect), and navigating to the href
location.
Navigate:
window.location = $('#myanchor').attr('href');
Open in new tab or window:
window.open($('#myanchor').attr('href'));
invoke click event (call the javascript):
$('#myanchor').click();
Even though this post is caput, I think it's an excellent demonstration of some walls that one can run into with jQuery, i.e. thinking click()
actually clicks on an element, rather than just sending a click event bubbling up through the DOM. Let's say you actually need to simulate a click event (i.e. for testing purposes, etc.) If that's the case, provided that you're using a modern browser you can just use HTMLElement.prototype.click
(see here for method details as well as a link to the W3 spec). This should work on almost all browsers, especially if you're dealing with links, and you can fall back to window.open
pretty easily if you need to:
var clickLink = function(linkEl) {
if (HTMLElement.prototype.click) {
// You'll want to create a new element so you don't alter the page element's
// attributes, unless of course the target attr is already _blank
// or you don't need to alter anything
var linkElCopy = $.extend(true, Object.create(linkEl), linkEl);
$(linkElCopy).attr('target', '_blank');
linkElCopy.click();
} else {
// As Daniel Doezema had said
window.open($(linkEl).attr('href'));
}
};
window.open($('#myanchor').attr('href'));
$('#myanchor')[0].click();
It worked for me:
window.location = $('#myanchor').attr('href');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With