Creating a basic popup with jQuery: A step-by-step guide

Currently in the process of creating a webpage. Wondering how to create a popup window with an email label and text box when clicking on the mail div?

Answer №1

Let's start with the CSS - feel free to customize as needed:

a.selected {
  background-color:#1F75CC;
  color:white;
  z-index:100;
}

.messagepop {
  background-color:#FFFFFF;
  border:1px solid #999999;
  cursor:default;
  display:none;
  margin-top: 15px;
  position:absolute;
  text-align:left;
  width:394px;
  z-index:50;
  padding: 25px 25px 20px;
}

label {
  display: block;
  margin-bottom: 3px;
  padding-left: 15px;
  text-indent: -15px;
}

.messagepop p, .messagepop.div {
  border-bottom: 1px solid #EFEFEF;
  margin: 8px 0;
  padding-bottom: 8px;
}

Next, let's move on to the JavaScript part:

function deselect(e) {
  $('.pop').slideFadeToggle(function() {
    e.removeClass('selected');
  });    
}

$(function() {
  $('#contact').on('click', function() {
    if($(this).hasClass('selected')) {
      deselect($(this));               
    } else {
      $(this).addClass('selected');
      $('.pop').slideFadeToggle();
    }
    return false;
  });

  $('.close').on('click', function() {
    deselect($('#contact'));
    return false;
  });
});

$.fn.slideFadeToggle = function(easing, callback) {
  return this.animate({ opacity: 'toggle', height: 'toggle' }, 'fast', easing, callback);
};

Lastly, here is the html structure:

<div class="messagepop pop">
  <form method="post" id="new_message" action="/messages">
    <p><label for="email">Your email or name</label><input type="text" size="30" name="email" id="email" /></p>
    <p><label for="body">Message</label><textarea rows="6" name="body" id="body" cols="35"></textarea></p>
    <p><input type="submit" value="Send Message" name="commit" id="message_submit"/> or <a class="close" href="/">Cancel</a></p>
  </form>
</div>

<a href="/contact" id="contact">Contact Us</a>

Feel free to check out a jsfiddle demo and implementation.

If you consider loading popup content via ajax call based on your needs, here are the necessary adjustments:

Update the HTML section as follows:

<div>
    <div class="messagepop pop"></div> 
    <a href="/contact" id="contact">Contact Us</a>
</div>

Adjust the JavaScript functionality like so:

$("#contact").on('click', function() {
    if($(this).hasClass("selected")) {
        deselect();               
    } else {
        $(this).addClass("selected");
        $.get(this.href, function(data) {
            $(".pop").html(data).slideFadeToggle(function() { 
                $("input[type=text]:first").focus();
            });
        }
    }
    return false;
});

Answer №2

Have you seen the amazing features of jQuery UI Dialog? You can easily implement it in your project:

Here's how you would use jQuery:

$(document).ready(function() {
    $("#dialog").dialog();
});

And here is the necessary markup:

<div id="dialog" title="Dialog Title">This is a dialog</div>

That's it!

Remember, this is just the basic usage. I recommend checking out the documentation for more advanced capabilities.

Answer №3

One of my favorite tools to enhance website functionality is the ColorBox jQuery plugin, which can be found at colorpowered.com/colorbox/. It stands out for its:

  • Simplicity and user-friendliness
  • Elegant design and fast performance
  • The ability to tailor it to meet specific needs
  • Visual appeal and effectiveness as a popup dialogue box

Answer №5

Experience the lightweight Magnific Popup for a responsive design, with just a 3KB file size.

Answer №6

This tutorial provides a comprehensive guide on creating a sleek jquery popup design. The end result is not only functional but also visually stunning.

Answer №7

If you're looking to add a simple popup to your website, here's how you can do it using HTML, CSS, and jQuery:

$(function() {
    // Open Popup
    $('[popup-open]').on('click', function() {
        var popup_name = $(this).attr('popup-open');
        $('[popup-name="' + popup_name + '"]').fadeIn(300);
    });
 
    // Close Popup
    $('[popup-close]').on('click', function() {
        var popup_name = $(this).attr('popup-close');
        $('[popup-name="' + popup_name + '"]').fadeOut(300);
    });
 
    // Close Popup When Click Outside
    $('.popup').on('click', function() {
        var popup_name = $(this).find('[popup-close]').attr('popup-close');
        $('[popup-name="' + popup_name + '"]').fadeOut(300);
    }).children().click(function() {
        return false;
    });
 
});
body {
    font-family:Arial, Helvetica, sans-serif;
}
 
p {
    font-size: 16px;
    line-height: 26px;
    letter-spacing: 0.5px;
    color: #484848;
}
 
/* Popup Open button */ 
.open-button{
    color:#FFF;
    background:#0066CC;
    padding:10px;
    text-decoration:none;
    border:1px solid #0157ad;
    border-radius:3px;
}
 
.open-button:hover{
    background:#01478e;
}
 
.popup {
    position:fixed;
    top:0px;
    left:0px;
    background:rgba(0,0,0,0.75);
    width:100%;
    height:100%;
    display:none;
}
 
/* Popup inner div */
.popup-content {
    width: 700px;
    margin: 0 auto;
    box-sizing: border-box;
    padding: 40px;
    margin-top: 100px;
    box-shadow: 0px 2px 6px rgba(0,0,0,1);
    border-radius: 3px;
    background: #fff;
    position: relative;
}
 
/* Popup close button */
.close-button {
    width: 25px;
    height: 25px;
    position: absolute;
    top: -10px;
    right: -10px;
    border-radius: 20px;
    background: rgba(0,0,0,0.8);
    font-size: 20px;
    text-align: center;
    color: #fff;
    text-decoration:none;
}
 
.close-button:hover {
    background: rgba(0,0,0,1);
}
 
@media screen and (max-width: 720px) {
.popup-content {
    width:90%;
    } 
}
<!DOCTYPE html>
<html>
<head>
 <title> Popup </title>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head> 

<body>
    <a class="open-button" popup-open="popup-1" href="javascript:void(0)"> Popup 
        Preview</a>
         
        <div class="popup" popup-name="popup-1">
            <div class="popup-content">
            <h2>Title of Popup </h2>
        <p>Popup 1 content will be here. Lorem ipsum dolor sit amet, 
        consectetur adipiscing elit. Aliquam consequat diam ut tortor 
        dignissim, vel accumsan libero venenatis. Nunc pretium volutpat 
        convallis. Integer at metus eget neque hendrerit vestibulum. 
        Aenean vel mattis purus. Fusce condimentum auctor tellus eget 
        ullamcorper. Vestibulum sagittis pharetra tellus mollis vestibulum. 
        Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        <a class="close-button" popup-close="popup-1" href="javascript:void(0)">x</a>
            </div>
        </div>  
</body>
</html>

Answer №9

An incredibly light modal popup plugin that stands out from the rest. Check out POPELT at

This plugin is known for its lightweight nature, ability to support nested popups, object-oriented design, dynamic button support, responsiveness, and much more. Stay tuned for the next update which will feature Popup Ajax form submissions!

Don't hesitate to make use of this plugin and share your feedback with a tweet.

Answer №10

Create a basic popup window using HTML5 and JavaScript.

HTML:-

<dialog id="window">  
    <h3>Sample Dialog!</h3>  
    <p>Lorem ipsum dolor sit amet</p>  
    <button id="exit">Close Dialog</button>
</dialog>  

<button id="show">Show Dialog</button> 

JavaScript:-

(function() {  

    var dialog = document.getElementById('window');  
    document.getElementById('show').onclick = function() {  
        dialog.show();  
    };  
    document.getElementById('exit').onclick = function() {  
        dialog.close();  
    };
})();

Answer №11

Check out this easy-to-use popup code:

<!DOCTYPE html>
<html>
    <head>
        <style>
            #modal {
                position:absolute;
                background:gray;
                padding:8px;
            }

            #content {
                background:white;
                padding:20px;
            }

            #close {
                position:absolute;
                background:url(close.png);
                width:24px;
                height:27px;
                top:-7px;
                right:-7px;
            }
        </style>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script>
            var modal = (function(){
                // Dynamically add HTML to the document
                $modal = $('<div id="modal"></div>');
                $content = $('<div id="content"></div>');
                $close = $('<a id="close" href="#"></a>');

                $modal.hide();
                $modal.append($content, $close);

                $(document).ready(function(){
                    $('body').append($modal);                       
                });

                $close.click(function(e){
                    e.preventDefault();
                    $modal.hide();
                    $content.empty();
                });
                // Launch the modal
                return function (content) {
                    $content.html(content);
                    // Center the modal in the viewport
                    $modal.css({
                        top: ($(window).height() - $modal.outerHeight()) / 2, 
                        left: ($(window).width() - $modal.outerWidth()) / 2
                    });
                    $modal.show();
                };
            }());

            // Make sure DOM is ready before accessing the document
            $(document).ready(function(){
                $('a#popup').click(function(e){
                    modal("<p>This is the content of the popup.</p>");
                    e.preventDefault();
                });
            });
        </script>
    </head>
    <body>
        <a id='popup' href='#'>Easy popup</a>
    </body>
</html>

A more adaptable solution can be found in this guide: Here's close.png for reference.

Answer №12

EASILY CREATE CSS POPUP WITH THIS LOGIC! GIVE IT A TRY. I BELIEVE THIS COULD BECOME VERY POPULAR IN THE FUTURE

            <a href="#openModal">OPEN</a>

            <div id="openModal" class="modalDialog">
                <div>
                    <a href="#close"  class="close">X</a>
                    <h2>MODAL</h2>

                </div>
            </div>


.modalDialog {
    position: fixed;
    font-family: Arial, Helvetica, sans-serif;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background: rgba(0,0,0,0.8);
    z-index: 99999;
    -webkit-transition: opacity 400ms ease-in;
    -moz-transition: opacity 400ms ease-in;
    transition: opacity 400ms ease-in;
    display: none;
    pointer-events: none;
}

.modalDialog:target {
    display: block;
    pointer-events: auto;
}

.modalDialog > div {
    width: 400px;
    position: relative;
    margin: 10% auto;
    padding: 5px 20px 13px 20px;
    border-radius: 10px;
    background: #fff;
    background: -moz-linear-gradient(#fff, #999);
    background: -webkit-linear-gradient(#fff, #999);
    background: -o-linear-gradient(#fff, #999);
}

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

Having trouble getting the .toggle() function with classList to work on one element, despite working fine on others

I've been struggling to apply a class to an HTML element when I click on another element of the page. Despite numerous attempts, it just doesn't seem to work for me. Let's take a look at my code: HTML Code: <div class="container&qu ...

Fill out the form field using an AJAX request

Whenever a specific business is selected from a dropdown list, I want to automatically populate a Django form field. For example: I have a list of businesses (business A, business B, ...) and corresponding countries where each business is located. Busin ...

I am seeking guidance on extracting specific data from a JSON file and presenting it in an HTML table using jQuery

I am currently working on extracting specific elements from a JSON file and displaying them in an HTML table. I have successfully retrieved the data from the JSON file, stored it in an array, and then dynamically created an HTML table to display the conten ...

Solving Mixed Content Issues in JavaScript

I'm attempting to retrieve information from OMDB API, but I'm encountering an issue with mixed content images. OMDB pulls its data from IMDB, which does not allow the use of https images. Therefore, all image sources must be prefixed with http. ...

The third @media query for max-width is not functioning as expected in the CSS

Looking to create a responsive card section on my website for various screen sizes. The goal is to display 5 cards per row when the screen width is greater than 1300px, maintain 3 cards per row from 1024px to 1300px, and then switch to only 2 cards per row ...

NextJs getStaticPaths function is failing to render the correct page, resulting in a 404 error message being displayed

Hey there, I'm in a bit of a pickle as I've never used 'getStaticPaths' before and it's crucial for my current project! I followed the example code from NextJs's documentation on 'getStaticPaths', but when I try to ...

elimination of nonexistent object

How can I prevent releasing data if two attributes are empty? const fork = [ { from: 'client', msg: null, for: null }, { from: 'client', msg: '2222222222222', for: null }, { from: 'server', msg: 'wqqqqqqqq ...

What is the best way to retrieve the rel value using jQuery?

In my process, I utilize jQuery UI drag and drop functions to pick out images from an album. The images' ID is stored in the "rel" parameter, which I then need to transfer to an input element after dropping the image. Below is a list of images that c ...

What is the best way to position a button under an h3 heading using the display flex

Inside my div, I have an h3 and a button. The div uses display:flex; with justify-content:center; and align-items:center;. However, the button ends up sticking to the right side of the h3. I attempted placing the button in its own div, but this caused a la ...

Leverage the power of React-PDF to smoothly magnify or minimize your

I am working on a ReactJS project where I want to implement zoom in/zoom out functionality. To display PDF files, I am utilizing the react-pdf package in my web application. According to the documentation, there is a scale prop that allows me to adjust the ...

Incorporating Bootstrap JS into Next.js

Currently, I am in the process of learning next.js and experimenting with incorporating Bootstrap into my projects. To begin, I initiated a new project using npx create-next-app@latest my-app, utilizing the newly created "app" directory structure. Follow ...

Unable to fetch local file using ajax from a local HTML page

According to Same Origin Policy, the SOP should not be applied to the file:// protocol. However, I'm having trouble with my code. I am running a testing page from my local system, and both when I try to access abc.txt in the same directory as the HTML ...

Is it possible for me to route a URL to a particular content generated by Ajax on a separate webpage?

I appreciate anyone taking the time to help with this, especially since I already had to get 12 stitches. Here's what I'm dealing with: mysite.com/documentation - page with a menu and content section (content will load dynamically via Ajax w ...

Guide for implementing a one-line if statement in Javascript

I am aiming to assign a class using a single-line if statement as outlined in this source. Currently, I am utilizing Material-UI and attempting to specify a class. Therefore, I would like to implement this approach: if(condition) expression <Typogr ...

What are the limitations on cross-site scripting for local (file:///) pages?

I am currently working on an HTML/Javascript application that makes use of jQuery to communicate with a web server that I unfortunately do not have control over. The application runs smoothly when accessed locally through the file:///app.html URL on Safari ...

Transforming JQuery code into pure Javascript: Attaching an event listener to dynamically generated elements

After exhausting all available resources on stack overflow, I am still unable to find a solution to my problem. I am currently trying to convert the JQuery function below into Vanilla JavaScript as part of my mission to make web pages free of JQuery. How ...

Changing Background Colors of Grid Items in React.js Grid Layout

I'm currently learning React and have created a basic app that shows data from a database in a grid format. I'm looking to customize the background colors of each grid item based on its priority level, which is pulled from the database. The prior ...

Transforming Form Sections for Sending via Ajax in ASP.NET MVC

In the process of developing an application for a tractor salvage yard, I have encountered a challenge. The application allows users to create notes and add multiple parts to each note. Previously, when the create view was on a separate page with its own U ...

I desire to share the JSON information and receive the corresponding response data

<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> ...

JavaScript Date displaying the string in the format YYYY/MM/DD HH:MM

I'm struggling to figure out how to format a date and time string like this: "YYYY-MM-DD-HH-MM" Can anyone help me with this? Here is the code I currently have: var x = new Date(); var formattedTimeStamp = x.toString(); Current Output: Tue Oct 3 ...