Click trigger event on anchor tag not working

I just ran into this question

Fiddle

Running an event clickon an anchor tag does not work 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 does the trigger event not work in this case?

+3
source share
3 answers

You need to call your own DOM method click()to disable the default binding behavior, jQuery specifically excludes it from the anchor :

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

-jsFiddle -

+13
source

Using

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

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

Updated fiddle

+2
source

Since you do not have a binding to the event .click(), it never fires.

You need to fire the DOM event clickusing jQuery .click()instead .trigger(e), and this should only work on dom nodes. This can be done by entering an index [0]or using the jQuery method .get(0).

Instead, try the following:

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

and if so, you can only do this with javascript:

window.addEventListener('DOMContentLoaded', function(e){
   document.querySelector('.button2').click();
}, false);
+1
source

Source: https://habr.com/ru/post/1619161/


All Articles