Quick Reach
What is the jQuery click() method?
The click event occurs when an element of HTML document is clicked. For example clicking a button, a paragraph, a Div, a link or an image etc. As click event occurs, an event handler function can be attached to perform a certain action with the click() method.
Video Tutorial
How to use the click method
$(selector).click(function)
Where the function is optional. It runs as click event occurs.
e.g.
- $(“p”).click(function)
- $(“div”).click(function)
- $(“button”).click(function)
Below are running examples of click() method with different HTML elements
Example of click() with paragraph
In the example below, as the first paragraph is clicked, it will trigger an event handler that will show an alert. The click method is attached with clickme id.
Copy and paste code into HTML file and run in your browser.
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
<!DOCTYPE html>
<head>
<title>jQuery Events</title>
<script src=“http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js”></script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function(){
$(“#Clickme”).click(function(){
alert(“Paragraph with ‘Clickme’ id is clicked”);
});
});
</script>
<style type=”text/css”>
.stylespec{
background-color:#ffffff;
width:400px;
height:50px;
border-style: solid;
border-width: 1px;
}
</style>
</head>
<body>
<p class=“stylespec” id=“Clickme”>Clicking on this paragraph will execute single click event handler! </p>
<p class=” stylespec”>Click on this paragraph will not execute event handler. </p>
</body>
</html>
|
Example of jQuery click() with Div <div>
Just like the above example except the div tags are used for demonstrating the click jQuery method:
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
<!DOCTYPE html>
<head>
<title>jQuery Events</title>
<script src=“http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js”></script>
<script type=“text/javascript” language=“javascript”>
$(document).ready(function(){
$(“#Clickme”).click(function(){
alert(“Div with ‘Clickme’ id is clicked”);
});
});
</script>
<style type=”text/css”>
.stylespec{
background-color:#ffffff;
width:400px;
height:50px;
border-style: solid;
border-width: 1px;
}
</style>
</head>
<body>
<div class=“stylespec” id=“Clickme”>Clicking on this Div will execute single click event handler! </div>
<div class=” stylespec”>Click on this Div will not execute event handler. </div>
</body>
</html>
|
Leave A Comment?