When you click on an element, the click event occurs and once the click event occurs it execute the click () method or attaches a function to run.
It is generally used together with other events of jQuery.
Syntax:
$(selector).click()
It is used to trigger the click event for the selected elements.
$(selector).click(function)
It is used to attach the function to the click event.
Let’s take an example to demonstrate jQuery click() event.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").click(function(){
alert("This paragraph was clicked.");
});
});
</script>
</head>
<body>
<p>Click on the statement.</p>
</body>
</html>
Output:
Click on the statement.
Let’s take an example to demonstrate the jquery click() event. In this example, when you click on the heading element, it will hide the current heading.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("h1,h2,h3").click(function(){
$(this).hide();
});
});
</script>
</head>
<body>
<h1>This heading will disappear if you click on this.</h1>
<h2>I will also disappear.</h2>
<h3>Me too.</h3>
</body>
</html>
Output:
Leave a Reply