[javascript] Simulate a click on 'a' element using javascript/jquery

I am trying to simulate a click on on an element. HTML for the same is as follows

<a id="gift-close" href="javascript:void(0)" class="cart-mask-close p-abs" onclick="_gaq.push(['_trackEvent','voucher_new','cart',$(this).attr('rel')+'-mask_x_button-inaction']);" rel="coupon">&nbsp;</a>

How can i simulate a click on it. I have tried

document.getElementById("gift-close").click();

But its not doing anything

This question is related to javascript jquery hyperlink click simulate

The answer is


The code you've already tried:

document.getElementById("gift-close").click();

...should work as long as the element actually exists in the DOM at the time you run it. Some possible ways to ensure that include:

  1. Run your code from an onload handler for the window. http://jsfiddle.net/LKNYg/
  2. Run your code from a document ready handler if you're using jQuery. http://jsfiddle.net/LKNYg/1/
  3. Put the code in a script block that is after the element in the source html.

So:

$(document).ready(function() {
    document.getElementById("gift-close").click();
    // OR
    $("#gift-close")[0].click();
});

Use this code to click:

$("#gift-close").click();

Using jQuery: $('#gift-close').trigger('click');

Using JavaScript: document.getElementById('gift-close').click();


Here, try this one:

$('#gift-close').on('click', function () {
    _gaq.push(['_trackEvent','voucher_new','cart',$(this).attr('rel')+'-mask_x_button-inaction']);
});

Try to use document.createEvent described here https://developer.mozilla.org/en-US/docs/Web/API/document.createEvent

The code for function that simulates click should look something like this:

function simulateClick() {
  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
  var a = document.getElementById("gift-close"); 
  a.dispatchEvent(evt);      
}

Using jQuery:

$('#gift-close').click();

Try adding a function inside the click() method.

$('#gift-close').click(function(){
  //do something here
});

It worked for me with a function assigned inside the click() method rather than keeping it empty.


Code snippet underneath!

Please take a look at these documentations and examples at MDN, and you will find your answer. This is the propper way to do it I would say.

Creating and triggering events

Dispatch Event (example)

Taken from the 'Dispatch Event (example)'-HTML-link (simulate click):

function simulateClick() {

  var evt = document.createEvent("MouseEvents");

  evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);

  var cb = document.getElementById("checkbox"); 
  var canceled = !cb.dispatchEvent(evt);

  if(canceled) {
    // A handler called preventDefault
    alert("canceled");
  } else {
    // None of the handlers called preventDefault
    alert("not canceled");
  }
}

This is how I would do it (2017 ..) :

Simply using MouseEvent.

function simulateClick() {

    var evt = new MouseEvent("click");

    var cb = document.getElementById("checkbox");
    var canceled = !cb.dispatchEvent(evt);

    if (canceled) {
        // A handler called preventDefault
        console.log("canceled");
    } else {
        // None of the handlers called preventDefault
        console.log("not canceled");
    }
}

_x000D_
_x000D_
document.getElementById("button").onclick = evt => {_x000D_
    _x000D_
    simulateClick()_x000D_
}_x000D_
_x000D_
function simulateClick() {_x000D_
_x000D_
    var evt = new MouseEvent("click");_x000D_
_x000D_
    var cb = document.getElementById("checkbox");_x000D_
    var canceled = !cb.dispatchEvent(evt);_x000D_
_x000D_
    if (canceled) {_x000D_
        // A handler called preventDefault_x000D_
        console.log("canceled");_x000D_
    } else {_x000D_
        // None of the handlers called preventDefault_x000D_
        console.log("not canceled");_x000D_
    }_x000D_
}
_x000D_
<input type="checkbox" id="checkbox">_x000D_
<br>_x000D_
<br>_x000D_
<button id="button">Check it out, or not</button>
_x000D_
_x000D_
_x000D_


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.? Wrapping a react-router Link in an html button How to make a hyperlink in telegram without using bots? React onClick and preventDefault() link refresh/redirect? How to put a link on a button with bootstrap? How link to any local file with markdown syntax? link with target="_blank" does not open in new tab in Chrome How to create a link to another PHP page How to determine the current language of a wordpress page when using polylang? How to change link color (Bootstrap) How can I make a clickable link in an NSAttributedString?

Examples related to click

Javascript Click on Element by Class HTML/Javascript Button Click Counter Angularjs action on click of button python selenium click on button Add and remove a class on click using jQuery? How to get the id of the element clicked using jQuery Why is this jQuery click function not working? Play sound on button click android $(document).on("click"... not working? Simulate a click on 'a' element using javascript/jquery

Examples related to simulate

Play audio as microphone input Simulate a click on 'a' element using javascript/jquery Network tools that simulate slow network connection