jQuery Event How to - Randomize click and double click event








Question

We would like to know how to randomize click and double click event.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.6.js'></script>
<script type='text/javascript'>
$(window).load(function(){<!--  w w w  .ja v a  2s  .  c  o  m-->
    function handler() {
        console.log('hi');
        bind();
    }
    function bind() {
        var whatHandler = Math.random() > 0.5 ? 'dblclick' :'click';
        $('div').unbind('.test').bind(whatHandler + '.test', handler);
    }
    $(function() {
       bind();
    });
});
</script>
</head>
<body>
  <div>click me</div>
</body>
</html>

The code above is rendered as follows: