Open In App

How to create a pop-up div on mouse over and stay when click using jQuery ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to create a pop-up div on mouseover and stay when click using jQuery.

Approach: 

  • First, we create an HTML div element that we want to pop up when we mouse over on an element and set its display property to none in CSS style.
display:none;
  • In the script tag, we create a variable flag and set its value to -1.
 $flag = -1;
  • Now in the script tag, we will select the element on which we want to mouseover. It is an HTML a element with class gfg. We select element a with class gfg, and then use the hover() function that is used to apply an effect when we mouse hover on an element.
  • We use two functions, first one executes when the mouse-enter event occurs. We select div with class popup and set its display property to block using the jQuery attr(). When the mouse-leave event occurs, the second function executes with the divs display value to none when the flag is not equal to -1.

JavaScript Code:

$("a.gfg").hover(
    function () {
        $("div.popup").attr("style", "display:block");
    },
    function () {
        if ($flag == -1) {
            $("div.popup").attr("style", "display:none");
        }
    }
);
  • We add a jQuery click event on element a. When we click on element a, the function sets the variable flag value to 1, so the div element stays after clicking.
$("a.gfg").click(function () {
    $flag = 1;
});

HTML Code: Below is the full implementation of the above approach.

HTML




<!DOCTYPE html>
<html>
  
<head>
  
    <!-- JQuery CDN -->
    <script src=
    </script>
  
    <style>
        center {
            font-size: 30px;
            color: green;
        }
  
        .popup {
            display: none;
            width: 500px;
            border: solid red 3px
        }
    </style>
</head>
  
<body>
    <center>
        <p>
            Hover <a href="#" class="gfg">here</a
            to see the changes.
        </p>
  
        <div class="popup">
            GeeksforGeeks
        </div>
    </center>
  
    <script>
        $flag = -1;
  
        $("a.gfg").hover(
            function () {
                $("div.popup").attr("style", "display:block");
            },
            function () {
                if ($flag == -1) {
                    $("div.popup").attr("style", "display:none");
                }
            }
        );
  
        $("a.gfg").click(function () {
            $flag = 1;
        });
    </script>
</body>
  
</html>


Output:

pop up mouse hover



Last Updated : 21 May, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads