JavaScript Tutorial JavaScript Examples JQuery Tutorial CSS Tutorial HTML Tutorial About Us

Lesson 8 The on() Method


We have learned how to use an event method to handle a certain event. Examples are click(), dblclick(), hover() etc. However, we can use the on() methods to handle all kinds of events. Besides, it can handle multiple events for the selected elements.

The on() method comprises two parameters, the event you wish to respond to and the jQuery functions you want to run.

Example 8.1

<!DOCTYPE html>
<html>
<head>
<script>
$(document).ready(function(){
    $("#header1").on('click', function(){
         $("#header1").hide();
    });
});
</script>
</head>
<body>
<h3 id="header1"> Don't Leave Me</h3>
<p>Paragraph 1.</p>
<p>Paragraph 2</p>
</body>
</html>

Click heading "Hide Me" to hide the heading.

Hide Me

Paragraph 1

Paragraph 2

*Note: the html method is to change the content of an element, in this case the element h3 with id 'header1'

Example 8.2

<!DOCTYPE html>
<html>
<head>
<script>
$(document).ready(function(){
    $("#header2").on({
	click: function(){
         $(this).css('color','red');
    },
	dblclick: function(){
         $(this).css('color','blue');
	}
    });
});
</script>
</head>
<body>
<p>Click the buttons to see the effects.</p>
<h3 id="header2">Click or double click to change my color</h3>

</body>
</html>

Click the buttons to see the effects.

Click or double click to change my color

Example 8.3

<!DOCTYPE html>
<html>
<head>
<script>
$(document).ready(function(){
    $("#btn3").on({
	mousedown:function(){
         $(header3).hide();
    },
	mouseup: function(){
         $(header3).show();
	}
    });
	

});
</script>
</head>
<body>
<h3 id="header3">Press mouse button to hide me and release mouse button to show Me</h3>
<button id="btn3">Press me and the release me to see the effect</button>
</body>
</html>

Press mouse button to hide me and release mouse button to show Me


Example 8.4

<!DOCTYPE html>
<html>
<head>
<script>
$(document).ready(function(){
    $("#btn5").on({
	click:function(){
         $("#header4").html("You've changed my content!");
		 },
	dblclick:function(){
         $("#header4").css("color","red");
		 }
    });
});
</script>
</head>
<body>
<h3 id="header4">Welcome to change my content and color</h3>
<button id="btn5">Click to change content and double click to change color</button>
</body>
</html>

Welcome to change my content and color





Copyright©2008 Dr.Liew Voon Kiong. All rights reserved |Contact|Privacy Policy