Please wait for 15 seconds...

Sunday, 13 January 2013



Jquery is very powerful and feature rich javascript library. During web development project you often need to detect left mouse click in javascript. The most common jquery method to detect clicks is .click(). Some times .click() does not work as expected and the most common reason is jquery library version. Today I am going to explain you 6 different methods to detect "clicks". So lets get start it.


HTML Code

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.click_me{
        cursor:pointer;
padding:4px 7px 4px 7px;
background-color:gray;
width:150px;
color:white;
font-weight:bold;
font-size:22pt;
position:absolute;
left:50%;
margin-left:-42px;
top:45%;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
        <div id="click_me" class="click_me">Click on me</div>
</body>
</html>

Copy above code and paste it in index.html page.

1) jQuery.on()

<script type="text/javascript">
$(document).ready(function(){
$('#click_me').on('click', function() {
alert('Click has been detected.');
});
});
</script>

Copy above code and paste it just before the </head> tag.

2) jQuery.one()

<script type="text/javascript">
$(document).ready(function(){  
$( "#click_me" ).one( "click", function() {
alert('Click has been detected.');  
}); 
});
</script>

3) jQuery.bind()

<script type="text/javascript">
$(document).ready(function(){
$( "#click_me" ).bind( "click", function() {
alert('Click has been detected.');  
}); 
});
</script>

4) jQuery.live()

<script type="text/javascript">
$(document).ready(function(e){
$("#click_me").live('click', function(){
  alert('Click has been detected.');
});
</script>

Note:

jQuery.live() has deprecated after version 8.1.

5) addEventListener

<script type="text/javascript">
window.onload = function(){
document.getElementById('click_me5').addEventListener('click', function() {
alert('Click has been detected');
}, false);
}
</script>

OR

<script type="text/javascript">
$(document).ready(function(){
document.getElementById('click_me5').addEventListener('click', function() {
alert('Click has been detected');
}, false);
});
</script>

6) .onclick

<script type="text/javascript">
window.onload = function(){ document.getElementById('click_me6').onclick = function() { alert('Click has been detected'); }; }
</script>

OR

<script type="text/javascript">
$(document).ready(function(){
document.getElementById('click_me6').onclick = function() {
alert('Click has been detected');
};
});
</script>

Thanks for reading this tutorial. Please leave your comment below.

Posted by Atul Prasad Gupta

1 comment:

Subscribe Techsirius

Techsirius on Facebook