jQuery - jQuery events

Imagine your webpage is like a smart robot. You want it to do something when a user clicks a button, moves their mouse, or types in a box. That’s where jQuery events come in—they let your webpage react to what the user is doing.

 What Is an Event?

An event is something that happens in the browser—like:

  • A click on a button

  • A hover over an image

  • A keypress in a form

  • A page load

Using jQuery, you can "listen" for these events and then make something happen when they occur.

 Basic jQuery Event Syntax

Here’s how it looks:

$(selector).event(function() {
  // what you want to happen
});
  • selector: what element you’re targeting (like a button or div)

  • event: the type of event (like .click(), .hover(), etc.)

  • function: the code that runs when the event happens

 Example 1: Button Click

$("#myButton").click(function() {
  alert("You clicked the button!");
});

This means: when someone clicks the element with the ID myButton, show an alert.

 Example 2: Mouse Hover

$(".box").hover(function() {
  $(this).css("background-color", "yellow");
});

This means: when you hover over any element with the class box, it changes its background to yellow.

 Example 3: Key Press

$("#name").keypress(function() {
  console.log("You pressed a key in the input!");
});

This means: whenever a key is pressed inside the input field with the ID name, a message will be logged in the console.

 Why Use jQuery for Events?

  • It’s easy to write

  • It works the same across different browsers

  • It helps you make interactive, responsive websites