JQuery Events Handling

When a user visits a webpage, he performs different actions e.g. clicking different areas of the page, hovering mouses, clicking radio buttons etc. Events fires as a result of these user actions. JQuery contains functions that can handle these user events by responding to them. This article explains how JQuery events are handled via functions. Let’s jump straight into a working example

Handling User Click Event

The following example explains how we can display a certain message to the user in the pop box when he clicks some specific element on a webpage.

<!DOCTYPE html>
<html>
<head>
    
    <title>Click Event Handling</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
    
    <script type = "text/javascript">
         $(document).ready(function() {
         $("h1").click(function(){
            alert("Heading 1 has been clicked");
         });
           
         });
      </script>
    
</head>
    
<body>
    
    <h1>This is heading1</h1>
    <p>This is a random paragraph</p>
    
</body>

</html>

Run Code
Download Code

The html of the above page contains an h1 heading and a paragraph. Inside the script, we select the h1 heading and then call click on it. The click function takes a function as a parameter. This function is executed once user clicks the h1 element. Inside this function, a message is being displayed by the alert box.

Handling Mouse Hover Event

The mouse hover event occurs when user hovers a mouse on specific element of a webpage. The hover function takes two functions as a parameter. The first is the function that executes when mouse enters the boundaries of an html element. The second parameter is the function that executes when mouse leaves the boundaries of the element. Take a look at the following example.

<!DOCTYPE html>
<html>
<head>
    
    <title>Hover Event Handling</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
    
    <script type = "text/javascript">
         $(document).ready(function() {
         $("h1").hover(function(){
            alert("You entered the h1 heading");
         }, 
                function(){
            alert("You left the h1 heading");
         });
           
         });
      </script>
    
</head>
    
<body>
    
    <h1>This is heading1</h1>
    <p>This is a random paragraph</p>
    
</body>

</html>

Run Code
Download Code

In the above code, when user hovers over the h1 heading, an alert box will appear displaying a message that you have entered h1 heading. Similarly, when user leaves the h1 heading corresponding message will be displayed in the alert box.

<<< JQuery Applying StylesJQuery Effects – Hide and Show Elements >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .