The problem of creating a custom pop-up with jQuery

I'm running into an issue while trying to develop a custom CSS and jQuery popup. Despite my efforts, the popup isn't functioning as intended. Take a look at my code below and point out where I may have gone wrong. What I aim to achieve is a popup that opens when the user clicks on the "Click Me" button, and closes when the user clicks outside of the popup.

jQuery has already been included in my code. Here's the code snippet:

<style>
    .maskarea {
    width: 100%;
    height:700px;
    background: rgba(255, 255, 255, .7);
    position: fixed;
    left: 0;
    top: 0;
    display:none;
}
.popup {
    width: 300px;
    height: 300px;
    position: fixed;
    left: 50%;
    background: #ccc;
    margin-left: -150px;
    top: 50%;
    margin-top: -150px;
}
</style>
<script>
$(function(){
     $(".hit").click(function(){
        $(".maskarea").show();
     })
})
</script>
</head>
<body>
<a href="javascript:void(0)" class="hit">Click Me</a>
    <div class="maskarea">
        <div class="popup">
        </div>
    </div>
</body>

Answer №1

1st Step: To hide the .maskarea when the user clicks on it, create a click event.

2nd Step: Create another click event for the .popup div to prevent the .maskarea click.

Give this a try:

$(function(){
     $(".hit").click(function(){
        $(".maskarea").show();
     });
     // Hide the .maskarea when the user clicks on it
     $('.maskarea').on('click', function(){
       $(this).hide();
     });
     // Use e.stopPropagation(); for .popup div to prevent .maskarea click
     $('.popup').on('click', function(e){
       e.stopPropagation();
     });
})

See working Demo

Learn more about e.stopPropagation()

Answer №2

You were so close to getting it right, all you needed was the close handler. Take a look at this example pen.

Here is the HTML code to use:

<a href="javascript:void(0)" class="hit">Click Me</a>
<div class="maskarea">
  <div class="popup">
  </div>
</div>

And this CSS:

.maskarea {
  width: 100%;
  height: 700px;
  background: rgba(255, 255, 255, .7);
  position: fixed;
  left: 0;
  top: 0;
  display: none;
}

.popup {
  width: 300px;
  height: 300px;
  position: fixed;
  left: 50%;
  background: #ccc;
  margin-left: -150px;
  top: 50%;
  margin-top: -150px;
}

Finally, the JavaScript code:

$(function() {
  $(".hit").click(function() {
    $(".maskarea").show();
  });
  $(".maskarea").click(function() {
    $(this).hide();
  });
  $('.popup').on('click', function(e){
    e.stopPropagation();
  });
});

By implementing these changes, you should have a fully functional popup.

Answer №3

One option for creating popups is to utilize various jQuery plugins such as fancybox or lightbox. However, if you prefer to create a custom popup using your own code, you can implement it like this:

    <style>
    .maskarea {
        width: 100%;
        height:700px;
        background: rgba(255, 255, 255, .7);
        position: fixed;
        left: 0;
        top: 0;
        display:none;
    }
    .popup {
        width: 300px;
        height: 300px;
        position: fixed;
        left: 50%;
        background: #ccc;
        top: 50%;
    }
    </style>
    <script>
    $(function(){
        $(".hit").click(function(){
            var windowHeight = $(window).height();  //Get current height of window or screen 
            var popup = $(".popup");    //cache the popup
            var marginTop = '-'+parseInt(popup.height()/2)+'px';  //Dynamically  get height of a popup div, and make it half for negative margin
            var marginLeft = '-'+parseInt(popup.width()/2)+'px';  //Dynamically  get width of a popup div, and make it half for negative margin
            popup.css({'margin-left':marginLeft,'margin-top':marginTop});
            $(".maskarea").height(windowHeight).show(); //assign windows height to maskarea
        })

        $(document).mouseup(function(e){
            var box = $('.popup');
            if(!box.is(e.target)&&box.has(e.target).length===0){
                $('.maskarea').hide();
            }
        })
    })
    </script>

<body>
    <a href="javascript:void(0)" class="hit">Click Me</a>
    <div class="maskarea">
        <div class="popup">

        </div>
    </div>
</body>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Updating the image source while refreshing the AJAX variable

This code snippet returns either a 0 or 1 value within the #durum div. However, I am looking to utilize this value to display an image that changes based on the value. For instance, if the ajax call returns 1, it should show 1.jpg and if it returns 0, it ...

Javascript Countdown Timer for HTML5 Canvas Animation

I'm currently working on a countdown in javascript using createJS for Flash Canvas HTML5, however, I've encountered the following error: file_Canvas.js:318 Uncaught TypeError: Cannot read property 'dtxt_days' of undefined This error sp ...

What is the best way to make the block rotate each time the button is clicked?

Specifically, I am having trouble getting the block to rotate properly. Currently, the block only rotates once when clicked, but I want it to rotate each time I click in both directions. Any suggestions on how to achieve this? var now = 10; $('. ...

The use of DIV tags allows the element to be displayed in an inline

In my project, I decided to add three div tags. The first two are positioned next to each other with the third div tag placed below them. However, when I tried to insert a slideshow into the first div tag, all of the div tags ended up displaying as "block" ...

Using jQuery AJAX to retrieve JSON data from a REST API

My node.js and express.js application hosts a REST API at http://localhost:3000/api/kfc, providing JSON data. The route function looks like this: router.get('/kfc', function(req, res, next) { var response= { "id":"123", "name":"name1", "drink": ...

Stop tooltips from appearing on hyperlinks in Internet Explorer

Is there a solution to disabling the pesky tooltips that appear in the bottom left corner of IE when hovering over links? Alternatively, is there a method to customize the text that appears instead of the default tooltip when hovering over a link (I attem ...

The absence of an eye icon in the password field when using bootstrap 5

I'm having trouble positioning the eyeball icon to the right side of my form when using Bootstrap v5 and FontAwesome v5. Instead, the password field is being shifted further to the right compared to the username field, and the eye icon is not displayi ...

Search for every div element and locate the ul element within it. Calculate the total number of table rows present in the ul element. Add this

There is a list on my website with a sublist called .cart-items. This sublist contains a table with multiple rows. My goal is to iterate through each .cart-select item and count the number of tr elements within the cart-items. The count should then be disp ...

AngularJS directive does not trigger when switching tabs or scrolling pages

I came across a solution to display a placeholder image before the real image fully loads while browsing online here. I implemented the code provided in the accepted answer on my page, where I have two tabs using `ion-slide-box` for tab selection. Each tab ...

jQuery doesn't have the capability to convert this data into JSON format

I have some code that I want to convert into JSON format: var locationData = []; locationData['lat'] = position.coords.latitude; locationData['long'] = position.coords.longitude; locationData['address']['road'] = da ...

Combining the total of numerous inputs that are multiplied by a specific value all at once

Hey, I've been working on a project with a table and an input field with costs using jQuery. You can check out This Fiddle for reference. $( ".total" ).change(function() { let i = 1; var input001 = document.getElementsByName(i)[0]; var ...

Ensure that the footer remains at the bottom of the page regardless of the content above

I am currently developing a website using bootstrap and I am facing an issue with the footer. I want the footer to always stay at the bottom of the page, but when the screen size is smaller (around 500px), the footer moves between sections. Here is the cod ...

What is the proper way to include an ID in a datepicker field along with the selected

Here is the layout of the table structure, displaying only specific dates that are available in the date picker. When a user clicks on one of these available dates, I need to retrieve the corresponding price. Table Structure https://i.stack.imgur.com/bJr ...

How to retrieve the form ID in jQuery using the input ID?

I have a simple question: How can I retrieve the form id using the input element id? <form id="my_form"> <fieldset> <!--some <div>'s--> <input id="my_input"></div> <!--some <di ...

Encountering a "403 Forbidden" error upon deployment to the server due to

Situation: I am developing a website using Spring web MVC, JSP, and HTML/JavaScript. One of the features I have implemented is a search function that communicates with imdbapi.org to retrieve movie/TV show information in JSON format via AJAX. The JSON resp ...

Error message "undefined" appears when using jQuery Ajax response in Internet Explorer

Having issues with jquery ajax requests. <script type="text/javascript> $(document).ready(function() { $.ajax({ type: "POST", async: false, cache: false, url: "/ajax/script.php", data: { display: 'u ...

Tips for maintaining the integrity of blank space within a text node?

When intercepting a paste event and cleaning HTML off of the content using textNodes, I am faced with an issue where all white space is reduced to a single space and new lines are disregarded. For example, pasting: "hello world !" ends up being "h ...

Cheerio doesn't exit the loop prematurely

The Cheerio/JQuery documentation mentions that using return false in a loop should terminate it early. Below is the code snippet in question: "use strict"; let cheerio = require('cheerio'); let $ = cheerio.load('<a href="www.test.com"&g ...

What is the best way to customize the appearance of the initial row in each tr cluster?

Looking to add a button for expanding child rows within a datatable, with each group in the table having the same child elements.... The provided CSS currently displays the icon on every row throughout the entire table. td.details-control { backg ...

Show the JSON information found on a specific website URL

I need help figuring out how to display a json file on a web address so that Swagger UI can recognize it. When I visit , I see json data and can save it as a .json file. However, I'm struggling to replicate this using html. Here's what I've ...