Event are triggered when something happens on web page. Some example of events are:
Syntax
$("p").click();
The following events you can use in jQuery.
Mouse Events | Keyboard Events | Form Events | Document/Window Events |
---|---|---|---|
click | keypress | submit | load |
dblclick | keydown | change | resize |
mouseenter | keyup | focus | scroll |
mouseleave | blur | unload |
Next you must be defined what should happen when the event fires. You must pass a function to the event.
Example
The following section will give you the brief overview of some events as well as related jQuery methods.
jQuery Click() Method
The jQuery click() method attach an event handler function to the selected elements for "click" event. The attached function is executed when the user clicks on that element.
The following example will hide the <p> elements on a page when they are clicked.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Executing a Function on Click Event in
jQuery</title>
<script
src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<style>
p{
padding: 20px;
font: 20px sans-serif;
background: green;
}
</style>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).slideUp();
});
});
</script>
</head>
<body>
<p>Tutorialstrend.com</p>
<p>This is Tutorial Site.</p>
</body>
</html>
Output
jQuery Hover() Method
This method execute when move mouse over element. In the below example, The function is executed when the user place the mouse pointer over an element. Color will change.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Executing a Function on Click Event in
jQuery</title>
<script
src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<style>
.changecolor{
padding: 20px;
font: 20px sans-serif;
background: green;
}
</style>
<script>
$(document).ready(function(){
$("p").hover(function(){
$(this).addClass("changecolor");
});
});
</script>
</head>
<body>
<p>Tutorialstrend.com</p>
<p>This is Tutorial Site.</p>
</body>
</html>
Output
Now point mouse over an element. Class change color will change the color the element.