jQuery Method How to - Use trigger() method to fire event








Question

We would like to know how to use trigger() method to fire event.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.8.3.js'></script>
<script type='text/javascript'>
$(window).load(function(){<!--   w w w .  j ava 2  s  .c o  m-->
    $(document).ready(function () {
        $('.botton3').click(doSomething);
        $('.botton2').click(doTrigger);
    });
    function doTrigger() {
        $('.botton3').trigger('click');
    }
    function doSomething() {
        console.log('boo!');
    }
});
</script>
</head>
<body>
  <div class="botton1">
    <h2>button1</h2>
  </div>
  <div class="botton2">
    <h2>button2</h2>
  </div>
  <div class="botton3">
    <h2>button3</h2>
  </div>
</body>
</html>

The code above is rendered as follows: