Skip to content Skip to sidebar Skip to footer

How Do I Simulate User Clicking A Link In Jquery?

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 func

Solution 1:

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() {
    returnthis.each(function() {
        if('createEvent'indocument) {
            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();

Solution 2:

Try a[0].click();

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

Solution 3:

Yes, very simple:

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

this will emulate a user click.

Solution 4:

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

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

You can stop the default behaviour of the event (in this case, redirecting to a.attr('href')). You can then perform whatever task you want and then redirect the user manually.

Is this what you're looking for ?

If you want to trigger the click event, just do

a.click();

Post a Comment for "How Do I Simulate User Clicking A Link In Jquery?"