jQuery - Events
Events in jQuery are actions or occurrences that happen in the browser, which can be detected and used to trigger JavaScript code.
Types Of Event
Event Type | Description | jQuery Function |
---|---|---|
click | Occurs when an element is clicked by the user. | $(selector).click(handler) |
hover | Occurs when the mouse pointer enters or leaves an element. | $(selector).hover(handlerIn, handlerOut) |
keydown | Occurs when a keyboard key is pressed down. | $(selector).keydown(handler) |
submit | Occurs when a form is submitted. | $(selector).submit(handler) |
change | Occurs when the value of an input element changes. | $(selector).change(handler) |
focus | Occurs when an element gains focus. | $(selector).focus(handler) |
blur | Occurs when an element loses focus. | $(selector).blur(handler) |
mouseover | Occurs when the mouse pointer moves over an element. | $(selector).mouseover(handler) |
mouseout | Occurs when the mouse pointer moves out of an element. | $(selector).mouseout(handler) |
1. Click Event
The click event occurs when an element is clicked by the user. Here's an example:
// Alert message when button is clicked
$("button").click(function() {
alert("Button clicked!");
});
This code attaches a click event handler to all <button> elements. When a button is clicked, an alert message saying "Button clicked!" will appear.
2. Hover Event
The hover event occurs when the mouse pointer enters or leaves an element. Here's an example:
// Change background color on hover
$("div").hover(function() {
$(this).css("background-color", "yellow");
}, function() {
$(this).css("background-color", "white");
});
This code changes the background color of all <div> elements to yellow when the mouse pointer enters them, and back to white when it leaves.
3. Keydown Event
The keydown event occurs when a keyboard key is pressed down. Here's an example:
// Display key pressed in input field
$("input").keydown(function(event) {
$("#output").text("Key pressed: " + event.key);
});
This code listens for keydown events on all <input> elements and displays the key pressed in an element with the ID "output".
4. Submit Event
The submit event occurs when a form is submitted. Here's an example:
// Prevent default form submission and display input value
$("form").submit(function(event) {
event.preventDefault();
alert("Form submitted with value: " + $("input").val());
});
This code prevents the default form submission behavior, displays an alert message, and shows the value entered in the input field when the form is submitted.
5. Conclusion
Understanding and utilizing events effectively is essential for creating interactive and responsive web applications with jQuery.
Comments
Post a Comment