jQuery Method How to - Use on() to add event handler for new future added element








Question

We would like to know how to use on() to add event handler for new future added element.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<script type='text/javascript'>
$(window).load(function(){<!-- ww w  . j av  a2s.  co  m-->
    $('div').append('<input type="button" class="hulk" value="click me"/>');
    $('.hulk').on('click', function(){
        console.log('me');
    });
});
</script>
</head>
<body>
  <div></div>
</body>
</html>

The code above is rendered as follows: