Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
jQuery.click() vs onClick
In this article, we will learn the difference between the jQuery.click() and onClick. Let us first understand what is click() and onClick() in jQuery.
jQuery click()
Example
The click() method triggers the click event of each matched element. Let us see an example ?
<html>
<head>
<title>The jQuery click() Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script language = "javascript">
$(document).ready(function() {
$("#clickButton1").click(function(){
alert("click event occurred");
});
});
function clickFirstButton(){
$("#clickButton1").click();
}
</script>
</head>
<body>
<form name = "sampleForm">
<label>Enter Name: </label><input type = "text" id = "result1" title="Enter Name" value = "" ></input><br/><br/>
<input type = "button" id = "clickButton1" value = "Click Me!" /> <input type = "button" id = "clickButton2" value = "Click First Button!" onclick="clickFirstButton();" />
</form>
</body>
</html>
Output
Click the Click Me button &mius;
Click the Click First Button button ?
onClick
The onclick() event type occurs when a user clicks the left button of his mouse. You can put your validation, warning etc., against this event type.
Example
Let us see an example ?
<!DOCTYPE html>
<html>
<head>
<script>
function myAttrFunc() {
var a = document.getElementsByTagName("a")[0].getAttribute("href");
document.getElementById("Demo").innerHTML = a;
}
</script>
</head>
<body>
<h1>Courses</h1>
<a href="https://www.tutorialspoint.com/market/index.asp">Tutorialspoint Courses</a>
<p>Clicking the below button to get the above link:</p>
<button onclick="myAttrFunc()">GET THE LINK</button>
<p id="Demo"></p>
</body>
</html>
Output
Click GET THE LINK button to display the link ?
Using click() is better as it follows standard event registration model. You can attach multiple handlers to the same element. You can easily access the event object, and the handler can live in any function's scope. Also, it is dynamic, i.e. it can be invoked at any time and is especially well-suited for dynamically generated elements. Whether you use jQuery, another library or the native methods directly does not really matter.
