jQuery Click Event Examples

User
jquery click event
Assistant
In jQuery, the `.click()` event is used to execute a function when an element is clicked. You can bind a click event in multiple ways:

### 1. **Basic Click Event**

$(document).ready(function(){
    $("#myButton").click(function(){
        alert("Button clicked!");
    });
});

πŸ“Œ **Explanation:** When `#myButton` is clicked, an alert box will appear.

### 2. **Using `.on()` (Recommended for Dynamic Elements)**

$(document).ready(function(){
    $(document).on("click", "#myButton", function(){
        alert("Button clicked dynamically!");
    });
});

πŸ“Œ **Why use `.on()`?**
If `#myButton` is dynamically added after the page loads, `.click()` won’t work, but `.on()` will.

### 3. **Passing Data in Click Event**

$("#myButton").on("click", { msg: "Hello, Neeraj!" }, function(event){
    alert(event.data.msg);
});

πŸ“Œ **Explanation:** Data `{ msg: "Hello, Neeraj!" }` is passed and retrieved inside the event handler.

### 4. **Prevent Default Behavior**

$("a").click(function(event){
    event.preventDefault();
    alert("Link clicked, but default action prevented!");
});

πŸ“Œ **Use case:** Prevents the link from navigating to another page.

### 5. **Toggle Class on Click**

$("#myButton").click(function(){
    $(this).toggleClass("active");
});

πŸ“Œ **Use case:** Toggles a class `active` on the button when clicked.

Let me know if you need a specific use case! πŸš€

Leave a Comment

Your email address will not be published. Required fields are marked *