Search code examples
jqueryeventtrigger

jQuery trigger click for function with e.target


I've had issues with the jQuery .trigger() in the past, sometimes it works and others not. It usually breaks down when I need it to do something like this ...

HTML

<div class="list">
  <a href="#" class="one">one</a>
  <a href="#" class="two">two</a>
  <a href="#" class="three">three</a>
</div>

<p class="output"></p>

JS

$(document).ready(function() {
   $('.two').trigger('click');

   $('.list a').click(function(e){
      e.preventDefault();
      $text = $(e.target).text();
      $('.output').text($text);
   });
});

fiddle: http://jsfiddle.net/7pup2/


Solution

  • You need to register the handler first then trigger the event

    it should be

    $(document).ready(function() {
    
       $('.list a').click(function(e){
          e.preventDefault();
          $text = $(e.target).text();
          $('.output').text($text);
       });
    
       $('.two').trigger('click');
    });