jQuery Event How to - Trigger onclick event of an anchor tag on document onload








Question

We would like to know how to trigger onclick event of an anchor tag on document onload.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.10.1.js'></script>
<script type='text/javascript'>
$(window).load(function(){<!--from w  w  w.  ja v  a 2  s. c o m-->
    $(document).ready(function(){
        $('#sample').click(function() {
            console.log('yo yo yo .....you good to go.!!!'); 
        });
        $('#sample').trigger('click');
    });
});
</script>
</head>
<body>
  <a href="#" id="sample">this is a link</a>
</body>
</html>

The code above is rendered as follows: