Triggering click event on anchor tag doesn't work

jGupta picture jGupta · Dec 9, 2015 · Viewed 19.6k times · Source

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?

Answer

A. Wolff picture A. Wolff · Dec 9, 2015

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-