Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Triggering click event on anchor tag doesn't work

I just ran into this question

FIDDLE

Triggering click event on anchor tag is not working here.

<a class="button2" href="#popup1">hello</a>
<div id="popup1" class="overlay">
  <div class="popup">
    <div class="contentSpec">
      <h2>Would you like to visit</h2>
      <h1>someURL</h1>
    </div>
    <a class="close" href="#"></a>
    <div class="content">

      <div class="box">
        <a class="button" href="#popup1">YES</a>
        <a class="button1" href="#popup1">NO</a>
      </div>
    </div>
  </div>
</div>

JS:

$(document).ready(function() {
  $(".button2").trigger('click');
});

My question, is why the trigger event is not working in this case?

like image 886
jGupta Avatar asked Dec 09 '15 08:12

jGupta


People also ask

How do you trigger an event on button click?

A single click event bind to a button with an Id of “button2”. and a trigger to execute the button1 click event handler. $("#button2"). bind("click", (function () { alert("Button 2 is clicked!"); $("#button1").

How do I trigger a click event without clicking?

If you want native JS to trigger click event without clicking then use the element id and click() method of JavaScript.

How do I know which anchor is clicked in jQuery?

click(function(e){ var id = e.target.id; alert(id); }); }); In this way, e. target is the element you have clicked on.


2 Answers

You need to call native DOM click() method in order to fire default clicking anchor behaviour, jQuery specifically excludes it on anchor:

$(document).ready(function() {
  $(".button2")[0].click();
});

-jsFiddle-

like image 132
A. Wolff Avatar answered Oct 14 '22 02:10

A. Wolff


Use

$(".button2").get(0).click();

The get(0) will return the first DOM object instead of the jquery object, and click() will be triggered.

Updated fiddle

like image 31
Adam Azad Avatar answered Oct 14 '22 03:10

Adam Azad