How to simulate a user by clicking a link in jQuery?

Now there are quite a few similar questions here, but I was wondering what should I do if I want to not just change the location window, but call any functions that can be attached to click and change only href if they are ok with it, or just redirect if there are no listeners.

For instance:

 var a = $('.edithost'); a.click(function() {return false;}); 

Should I click the link with the mouse, this will never lead me to href, so just redirecting the user to attr('href') will change the intended behavior of the page. In addition, the click applies not only to links, but also, say, to buttons, in which case I will need to submit a form, etc.

So, I was wondering if it is possible to emulate a click on an element so that the entire behavior of the browser is exactly the same as if it was clicked on by the mouse?

There cannot be listeners bound to a link.

Example:

 var a = $('<a href="google.com">google</a>'); a.click(); a.trigger('click'); 

This will not lead you to Google, I want to do this.

Update: .click() will not work. trigger('click') too. preventDefault has nothing to do with this

+6
source share
4 answers

In IE, you can call .click() on an element, but for standard browsers you need to simulate the click event by creating your own mouse event, and then use dispatchEvent to fire it.

I have summarized all this 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(); 
+13
source

Try a[0].click();

This will execute the click method of the DOM element instead of triggering the event.

+2
source

Yes, very simple:

 $('#YourSelector').click(); 

this will emulate a user click.

0
source

I really don't understand what you want to do. with this:

 a.click(function(e){ e.preventDefault(); }); 

You can stop the default behavior of the event (in this case, redirect to a.attr ('href')). You can then complete any task and then redirect the user manually.

Is this what you are looking for?

If you want to trigger the click event, just do

 a.click(); 
-1
source

Source: https://habr.com/ru/post/902537/


All Articles