Click event in jQuery


In this lesson, you will learn how to use click events in jQuery. The .click() function in jQuery binds a function (event handler) to the click event on a selected element. It allows you to make interactive web pages and perform a certain action whenever the click event is fired.

Introduction of Click event in jQuery

The syntax of the click function is:

.click (function());

This method is a short form of .on('click', function(){}). jQuery lets you select any element on the web page using CSS selectors. While interacting with the web page, you need to select the element that the visitor will interact with.

$("#element").click(function (){
});

The click event is fired when the mouse button is pressed and released while the pointer is still inside the web element. If this isn’t what you are looking for, the mousedown and mouseup events can be used.
In this example, we will have a div which will raise an alert when it gets clicked.

<div class = "box one" > < /div>

# container {
    margin: 20 px;
    padding: 10 px;
    border: 1 px solid# ccc;
    width: 400 px;
}
.one {
    background - color: #d9eb4b;
}

$(document).ready(function() {
    $('.one').click(function() {
        alert("The click event is fired.");
    });
});
Click event Example

Example of Click event using jQuery

Let’s understand the .click() event with an example. In this example, let’s create three DIVs. When the user clicks on the DIVs, the respective DIV slowly disappear.

Click event Example II

After you click on the center DIV, it disappears.

Click event Example II

The HTML

<div id="container">
<div class="box one"></div>
<div class="box two"></div>
<div class="box three"></div>
</div>

The CSS

.box{width:100px; height:100px; margin:2px; }
.one{background-color:#d9eb4b;}
.two{background-color:#00A9FE;}
.three{background-color:#fd6bb6;}
#container{margin:20px; padding:10px; border:1px solid #ccc; width:400px;}

The jQuery

<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js" >
    </script> 
  <script>
    $(document).ready(function() {
        $('.box').click(function() {
            $(this).fadeOut(600);
        });
    }); </script>
jQuery Events Tutorial Home jQuery Blur Event

 

Tutorials Panel

About Tutorials Panel

programming tutorial and source code for Software Engineers and developers. https://twitter.com/TutorialsPanel

View all posts by Tutorials Panel →

Leave a Reply