Now there's quite a lot of similar-looking questions here, but I was wondering, what should I do, if I want not to just change the location
of the window, but trigger whatever functions may be bound to the click
event, and only change the href
if they are ok with it, or just redirect, if there are no listeners.
For example:
var a = $('.edithost');
a.click(function() {return false;});
Should I click the link with mouse, it never takes me to the href, so just redirecting user to attr('href')
would change the intended behavior of the page. Besides, clicking applies not only to links, but to, say, buttons too, in which case I would have to submit the form, etc.
So I was wondering, whether it is possible to emulate clicking an element, so that all the behavior of the browser is exactly the same, as if clicked with mouse?
There can be no listeners bound to a link.
Example:
var a = $('<a href="google.com">google</a>');
a.click();
a.trigger('click');
This won't take you to Google, I want to make it do.
Update:
.click()
won't work. trigger('click')
too. preventDefault
has nothing to do with this
Method 1: Using the click() method: The click() method is used to simulate a mouse click on an element. It fires the click event of the element on which it is called. The event bubbles up to elements higher in the document tree and fires their click events also.
The onclick function in jQuery can be used in HTML elements such as div, paragraphs, hyperlinks, and so on to accomplish the desired objective. A mouse event occurs when the button on the mouse is depressed.
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.
To create a button link to another page in HTML,just add <a> tag and wrap it around the simple Html button. Inside a <a> tag simply use href=“” attribute to give the path of the desired page. The output shows that, after clicking the “Click” button, you will be navigated to “Google” instantly.
In IE, you can call .click()
on the element, but for standard browsers you need to simulate the click event by creating a native mouse event and then use dispatchEvent
to trigger it.
I summed it all up in this jQuery 'plugin':
$.fn.simulateClick = function() {
return this.each(function() {
if('createEvent' in document) {
var doc = this.ownerDocument,
evt = doc.createEvent('MouseEvents');
evt.initMouseEvent('click', true, true, doc.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
this.dispatchEvent(evt);
} else {
this.click(); // IE
}
});
}
Now, just call:
$('.edithost').simulateClick();
Try a[0].click();
This will execute the click
method of the DOM element instead of triggering the event.
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