Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulating a click in jQuery/JavaScript on a link

I want to simulate a click on any link on a page using JavaScript. If that link has some function binded to its 'onclick' event (by any other JS I don't have any control over), then that function must be called otherwise the link should behave in the normal manner and open a new page.

I am not sure that just checking the value of the 'onclick' handler would suffice. I want to build this so that it works on any link element.

I have no control over what function maybe binded to the onclick event of the link using whichever JS library (not necessarily jQuery) or by simply using JavaScript.

EDIT: With the help of the answers below, it looks like it is possible to check for event handlers attached using jQuery or using the onclick attribute. How do I check for event handlers attached using addEventListener / any other JS library so that it is foolproof?

like image 382
ankit Avatar asked Dec 03 '09 11:12

ankit


People also ask

How do you simulate a user click?

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.

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.

What is $() in jQuery?

$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.


1 Answers

You can use the the click function to trigger the click event on the selected element.

Example:

$( 'selector for your link' ).click (); 

You can learn about various selectors in jQuery's documentation.

EDIT: like the commenters below have said; this only works on events attached with jQuery, inline or in the style of "element.onclick". It does not work with addEventListener, and it will not follow the link if no event handlers are defined. You could solve this with something like this:

var linkEl = $( 'link selector' ); if ( linkEl.attr ( 'onclick' ) === undefined ) {     document.location = linkEl.attr ( 'href' ); } else {     linkEl.click (); } 

Don't know about addEventListener though.

like image 132
Jan Hančič Avatar answered Sep 23 '22 23:09

Jan Hančič