How to generate a simple popup using jQuery?

By using jQuery, we have to generate a simple popup.
Submitted by Pratishtha Saxena, on June 23, 2022

jQuery is a JavaScript library used to simplify HTML DOM tree traversal and manipulation, and event handling. It is free, open-source software. It is user-friendly and easy to use.

Note: Always remember to apply the CDN link while working with jQuery.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

Popup is the dialog box that appears out of nowhere when a button is clicked. This makes the webpage more attractive. Instead of loading small-small content on some other webpage by clicking a button or link, we can make our page more appealing by adding popups for small texts.

jQuery has a simple method for this called toggle() method. This method basically helps to hide and show the popup whenever it is triggered.

Syntax:

We'll consider the selector here as the content of the popup. For showing and hiding the popup on click, a little bit of CSS has also to be defined for it. Since only after clicking the button, we wish to see the popup content and initially, we do not want to see it, we have to use display:none as the CSS property for the content.

Let's see an example for a better understanding.

Generate a simple popup using CSS, jQuery

CSS:

<style type="text/css">
.content {
   position: absolute;
   top: 30%;
   left: 30%;
   right: 30%;
   bottom: 30%;
   width: 500px;
   height: 200px;
   text-align: center;
   background-color: lightgrey;
   padding: 10px;
   z-index: 100;
   display: none;
}

.close-btn {
   position: absolute;
   right: 10px;
   top: 10px;
   background-color: black;
   color: white;
   border-radius: 0px;
   padding: 4px;
}
</style>

HTML Code:

<!DOCTYPE html>

<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
   </head>
   <body>
      <button onclick="togglePopup()">Click Here</button>
      <div class="content">
         <div onclick="togglePopup()" class="close-btn">x</div>
         <h3>Popup</h3>
         <p>
            This site is specially designed to provide help to students,
            working professionals and job seekers.
            We are fully dedicated to make each tutorial
            very simple to learn and understand.
            This site is not created for business purpose,
            but for spreading education about programming
            languages and to help the concerned learners
            out who are enthusiastic to learn new technologies.
         </p>
      </div>
   </body>
</html>

jQuery Function:

<script>
    function togglePopup() {
        $(".content").toggle();
    }
</script>

Output:

Example: simple popup using jQuery





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.