Creating jQuery Popup Div

By Axl Mulat on

Jquery is most popular JavaScript library in the world, most web developers used jquery in there development because it is easy for newbies, jquery have a lots function and effects like form validation, animation, image slider and popup div box.

A web developer or designer we can apply this jquery effects very easy in our web projects, we can search and download, using third party jQuery plugins.

In jquery popup effects, If your wonder on how to create a in your own hand, in this tutorial I would like to share on how to create a popup div effect using jQuery, html and css.

We create a jquery popup div like lightbox and fancybox manually in steps, a popups ‘on click trigger’ event that pop up displays with opacity background and will remains center the popup if you scrolling zoom out the browser and closing by fadeout event and Ecs keyboard event, And also you can add text, image and video in YouTube and customize the content on the popup div after integrate your website.

View Demo | Download Source

1. Creating the Page Template

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Istockphp</title>
<link href="style/style.css" rel="stylesheet" type="text/css" media="all" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"> </script>
<script type="text/javascript" src="js/script.js"></script>
</head>

<body>
    <a href="#" class="topopup">Click Here Trigger</a>
    
    <div id="toPopup">
        
        <div class="close"></div>
           <span class="ecs_tooltip">Press Esc to close <span class="arrow"></span></span>
        <div id="popup_content"> <!--your content start-->
            <p>
            Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam,
            feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi
            vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed,
            commodo Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque habitant morbi tristique
            senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam,
            feugiat vitae, ultricies eget, tempor sit amet, ante. </p>
            <br />
            <p>
            Donec eu libero sit amet quam egestas semper. Aenean ultricies mi
            vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed,
            commodo Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. </p>
            <p align="center"><a href="#" class="livebox">Click Here Trigger</a></p>
        </div> <!--your content end-->
    
    </div> <!--toPopup end-->
    
    <div class="loader"></div>
       <div id="backgroundPopup"></div>
</body>
</html>

In index.html, we include the css, jquery script and js script after the title tag; in the body we have 3 div containers for popup div event.

  • div container for loading
  • div container for popup background,
  • and div container for popup

2. The stylesheet

style.css

#backgroundPopup {
    z-index:1;
    position: fixed;
    display:none;
    height:100%;
    width:100%;
    background:#000000;
    top:0px;
    left:0px;
}
#toPopup {
    font-family: "lucida grande",tahoma,verdana,arial,sans-serif;
    background: none repeat scroll 0 0 #FFFFFF;
    border: 10px solid #ccc;
    border-radius: 3px 3px 3px 3px;
    color: #333333;
    display: none;
    font-size: 14px;
    left: 50%;
    margin-left: -410px;
    position: fixed;
    top: 20%;
    width: 800px;
    z-index: 2;
}
div.loader {
    background: url("../img/loading.gif") no-repeat scroll 0 0 transparent;
    height: 32px;
    width: 32px;
    display: none;
    z-index: 9999;
    top: 40%;
    left: 50%;
    position: absolute;
    margin-left: -10px;
}
div.close {
    background: url("../img/closebox.png") no-repeat scroll 0 0 transparent;
    cursor: pointer;
    height: 30px;
    position: absolute;
    right: -27px;
    top: -24px;
    width: 30px;
}
span.ecs_tooltip {
    background: none repeat scroll 0 0 #000000;
    border-radius: 2px 2px 2px 2px;
    color: #FFFFFF;
    display: none;
    font-size: 11px;
    height: 16px;
    opacity: 0.7;
    padding: 4px 3px 2px 5px;
    position: absolute;
    right: -62px;
    text-align: center;
    top: -51px;
    width: 93px;
}
span.arrow {
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 7px solid #000000;
    display: block;
    height: 1px;
    left: 40px;
    position: relative;
    top: 3px;
    width: 1px;
}
div#popup_content {
    margin: 4px 7px;
    /* remove this comment if you want scroll bar
    overflow-y:scroll;
    height:200px
    */
}

In the css, if you want scrollbar in the popup just remove comment in line 74.

3. The jQuery script

script.js

jQuery(function($) {
    
    $("a.topopup").click(function() {
            loading(); // loading
            setTimeout(function(){ // then show popup, deley in .5 second
                loadPopup(); // function show popup
            }, 500); // .5 second
    return false;
    });
    
    /* event for close the popup */
    $("div.close").hover(
                    function() {
                        $('span.ecs_tooltip').show();
                    },
                    function () {
                        $('span.ecs_tooltip').hide();
                      }
                );
    
    $("div.close").click(function() {
        disablePopup();  // function close pop up
    });
    
    $(this).keyup(function(event) {
        if (event.which == 27) { // 27 is 'Ecs' in the keyboard
            disablePopup();  // function close pop up
        }      
    });
    
    $("div#backgroundPopup").click(function() {
        disablePopup();  // function close pop up
    });
    
    $('a.livebox').click(function() {
        alert('Hello World!');
    return false;
    });
    

     /************** start: functions. **************/
    function loading() {
        $("div.loader").show();  
    }
    function closeloading() {
        $("div.loader").fadeOut('normal');  
    }
    
    var popupStatus = 0; // set value
    
    function loadPopup() {
        if(popupStatus == 0) { // if value is 0, show popup
            closeloading(); // fadeout loading
            $("#toPopup").fadeIn(0500); // fadein popup div
            $("#backgroundPopup").css("opacity", "0.7"); // css opacity, supports IE7, IE8
            $("#backgroundPopup").fadeIn(0001);
            popupStatus = 1; // and set value to 1
        }    
    }
        
    function disablePopup() {
        if(popupStatus == 1) { // if value is 1, close popup
            $("#toPopup").fadeOut("normal");  
            $("#backgroundPopup").fadeOut("normal");  
            popupStatus = 0;  // and set value to 0
        }
    }
    /************** end: functions. **************/
}); // jQuery End

In the click event we triggered the loading() function and delay 0.5 second and triggered the loadPopup() function and the pop up displays. We add little more for closing the popup, if hover the ‘Close’ the tool tip message will appeared and keyboard event for close.

4. Done

We’re done, Congratulations you learn how to create a jquery popup div, on creating your own popup div you can edit the content of the popup like adding more text, image, registration form and add YouTube video.

Thank you for reading my tutorial. Please recommend and share :)

Let’s have a look at what we’ve achieved:

  • We create popup div without third party plugin
  • Works in old IE browser, IE 7,8
  • We add little feature, hover tool tip and keyboard event

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

113 comments

    • hi keshav just the add the keyboard event in script.js in this example, you can find keyboard event here, hope this help

      http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

      $(this).keyup(function(event) {
      if (event.which == 27) { // 27 is Ecs
      loading();
      setTimeout(function(){
      loadPopup();
      }, 500);
      return false;
      }
      if (event.ctrlKey && event.which == 13) { // ctrl + enter
      loading();
      setTimeout(function(){
      loadPopup();
      }, 500);
      return false;
      }
      });

        • hi kevhav, pls replace the script.js to this code, you can find other keyboard event here http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes, i add Esc and Ctrl + Enter event.

          /*
          author: istockphp.com
          */
          jQuery(function($) {

          $(this).keyup(function(event) {
          if (event.which == 27) { // 27 is Ecs
          loading();
          setTimeout(function(){
          loadPopup();
          }, 500);
          return false;
          }

          if (event.ctrlKey && event.which == 13) { // ctrl + enter
          loading();
          setTimeout(function(){
          loadPopup();
          }, 500);
          return false;
          }
          });

          $(“a.topopup”).click(function() {
          loading(); // loading
          setTimeout(function(){ // then show popup, deley in .5 second
          loadPopup(); // function show popup
          }, 500); // .5 second
          return false;
          });

          /* event for close the popup */
          $(“div.close”).hover(
          function() {
          $(‘span.ecs_tooltip’).show();
          },
          function () {
          $(‘span.ecs_tooltip’).hide();
          }
          );

          $(“div.close”).click(function() {
          disablePopup(); // function close pop up
          });

          $(this).keyup(function(event) {
          if (event.which == 27) { // 27 is ‘Ecs’ in the keyboard
          disablePopup(); // function close pop up
          }
          });

          $(“div#backgroundPopup”).click(function() {
          disablePopup(); // function close pop up
          });

          $(‘a.livebox’).click(function() {
          alert(‘Hello World!’);
          return false;
          });

          /************** start: functions. **************/
          function loading() {
          $(“div.loader”).show();
          }
          function closeloading() {
          $(“div.loader”).fadeOut(‘normal’);
          }

          var popupStatus = 0; // set value

          function loadPopup() {
          if(popupStatus == 0) { // if value is 0, show popup
          closeloading(); // fadeout loading
          $(“#toPopup”).fadeIn(0500); // fadein popup div
          $(“#backgroundPopup”).css(“opacity”, “0.7”); // css opacity, supports IE7, IE8
          $(“#backgroundPopup”).fadeIn(0001);
          popupStatus = 1; // and set value to 1
          }
          }

          function disablePopup() {
          if(popupStatus == 1) { // if value is 1, close popup
          $(“#toPopup”).fadeOut(“normal”);
          $(“#backgroundPopup”).fadeOut(“normal”);
          popupStatus = 0; // and set value to 0
          }
          }
          /************** end: functions. **************/
          }); // jQuery End

  1. Good and straightforward tutorial. However i have found one issue while working in IE lower versions. Please find the issue screenshot. in IE5 it didn’t display properly.Could you please provide fix for this issue. Thank you.

    • hi balesabu,

      thanks for the comment. this is whats look in IE 5? LOL. but in IE 7 and above works fine. i try to fix the issue. please try other alternative like ‘fancy box’ :)

  2. Great Job, Thanks!! but I have a little problem, when the content of the
    pop-up is bigger than the window size, the horizontal scrollbars
    doesn´t appear on the popup and therefore there is content on it, that remains hidden. How can I solve it?
    Thanks a lot

    • hi peter, replace this click function…

      $(“a.topopup”).click(function() {
      loading(); // loading
      setTimeout(function(){ // then show popup, deley in .5 second
      loadPopup(); // function show popup
      }, 500); // .5 second
      return false;
      });

      To…

      $(“a.topopup”).mouseover(function(){
      loading(); // loading
      setTimeout(function(){ // then show popup, deley in .5 second
      loadPopup(); // function show popup
      }, 500);
      });

  3. Hi, thanks for this plugin…I tried to download the “popup-div-getting-dynamic-content” but when i try to open it in my localhost it says:
    Warning: mysql_connect(): Access denied for user ‘root’@’localhost’ (using password: NO)
    I really want to make this work for a list of images since I’ve styled it already…but it’s not working! Any help would be great, thanks

  4. I know you said to make this happen (popup automatically) – change lines 3-9, but can you tell me what to change it to? (to Make PoPup Automatically, No Click Required) ????????? :)

  5. hi, thanks for the post, i have a problem, though…

    I have a list of items, and i want that, when i click one of them, the info shows at the popup… how can i do this?

    thank you and best regards

  6. Hey.. implemented your code in one of my applications, it’s working fine in Chrome and FireFox but Not in IE. Can you suggest some solution??

  7. OK, i’m beyond lost on this whole thing. I did the following verbatim, added it to my concrete5 html editor and nothing happens.

    First: Downloaded source of all materials like js, css etc to my computer. Ok sounds easy enough. Done.

    Next: Uploaded the JS , CSS and the gif files to my websites FILE MGR.

    Next: copied / pasted from wordpad the index.html code from the original index file onto the websites html editor so this way I could change the ipsum dumsum blah blah and actually add my own words. *AGAIN, EASY THERE*

    From here on is where I get confused.. I assume after copying the ORIGINAL html file all the script lines of the CSS and JS in it should point correctly to the js / css / gif files I originally uploaded.

    So, I hit the finish editing, and all it does is break the concrete5 editor because of the script not being correct and I have to totally delete the webpage where I am putting this all on..

    So, then I got a little crafty and began thinking, ok these code lines from the originators Index html were wrong:

    *ORIGINAL*

    *Original*

    So, in my concrete5 html editor, the link href I pointed it to where the file was resting on my websites folders *I’ll leave that info out where exactly the files point in the folders on the website so i’ll put blah blah*

    *MY EDIT*

    And I also did the exact thing with the script .js file

    Now, Ironically I had to point the . js file to point it exactly where it was on the website before when I once used a script on my website so I figured hell i’ll do it.

    Ok, done with my edits, hit save edits on my concrete5 html editor to see what it did and poof.. Same as before, breaks the html editor on concrete5 and I have to again delete the whole page of where i’m adding info *the page name is job postings* and start over.

    So here is my days of trying to get this right and failed every time questions.

    1. All I want is where a nice centered pop up pops up *like how the above demo works, and THAT is perfect and that’s all I WANT!* to pop up when someone hits a button *button is not on the original html above, just click me hyper link

    2. To add my bulleted description of the job inside the pop up and a email button to where people can email us *mailto script*

    3. I do NOT want the extra alert window pop up that says “HELLO WORLD” I don’t even need that extra trigger me hyperlink at the bottom of the page that leads up to the alert popup window , just a email button so they can email me.

    In reality folks, i’ve been trying to get this to work for days and days, and nothing works for me. Maybe i’m dumb and don’t get this java / css stuff as much as all of you do, but all I wanted was a nice little pop up like this to work and have my edited words inside it with a email button . And when they are done looking at it, can hit the close button and poof.

    How hard is this?? Why won’t this work with me? Is it Concrete5 not letting me do it? How to do this step by step would be nice.

    This pop up as I keep saying, is Perfect and is what I need. Any help would be greatly appreciated.. Thank you for my long winded outcry.

  8. This is absolutely brilliant!! But…. how do I go around doing this with a button press? For example, I press ‘|’ (shift and back slash) then the popup window appears? Im trying to do this so an admin would press this button for a pop up DIV where he would be able to log in etc. Many thanks, Nathan

  9. Hello,
    Thanks for your work. What I want to point is after popup is visible and background div covers the rest, still a user may use tab and can activate the trigger which is behind the background div. Maybe we can use property disable on all the remaining divs while popup is appearing, any other neat solution. Thanks again.

  10. Hi,
    I am trying to use this popup to replace the alert() method from javaScript code. Therefore I got rid of the jQuery(function($) {

    });
    andreplaced the

    $(“a.topopup”).click(function() {

    with just

    function openPopup(confirm, message) {

    }

    In debugging when invoking the openPopup method every line of code gets executed and there are no errors, but the div won’t show…

    can you explain that for me (and prior to that understand the issue I’m having)

  11. Hello,
    tank u , your pop up was really good, but i’d like to use it in another way, i mean i want to create this pop up runtime(everywhere i need with sending params to it) and create this pop up with jquery, not html, how can i do this??

  12. Good job man as I have been working on that jquery popup dialog but could nt figure out the css modyfing. Simple and straight forward tutorial. Thank a bunch.

  13. Hello,

    I need to open multiple pop-up windows in the same page.
    For e.g:

    –href=”#” class=”topopup”– Click Here Trigger –a–

    At the href, i would like to call another page content to be opened in the Popup.. How can i do that..

    Your help is appreciated

  14. Hello,

    Thank You kind sir for your script, I have one question I am working on a theme template that I will be introducting JQuery & need it to popup all sorts of php code amoung it e.g userid , username , ip, bonus points and more just wondering if I can import my php && mysql code within a pop up ?

    Cheers,

    Benjamin

  15. Hi I am trying to use this div popup for my new side, i am getting content via loop and php (like: ) . I will get 1-10 diffrent infos on one side and i would like to show the content via several popups. However by now it shows always the first content in alle popup div…..

  16. got it! i have my various #toPopup divs position changed to “fixed” rather than “relative”. With my layout, fixed doesn’t work, so I tried “absolute” and it works great!

    Thanks so much for your great script and support!!!
    Bob

  17. looks like this stripped my code…


    $post_id = xxxxx;
    $queried_post = get_post($post_id);...

    The other thing I noticed from the original code sample is that we’re repeating the same DIV ID on the same page. This isn’t a great practice to my knowledge. I changed
    to and changed the styles accordingly in my CSS.

  18. I have asked you this question before but you didn’t answer me,

    I’m trying to use your popup inside a repeater that gets it’s data from a database but whenever the popup shows it always shows the same data of the first datafield.

    How can I use it, that whenever I click a link on the repeater it show the popup div related to that data.

    Please help me on this topic, I want to use it in my project…

  19. I have the same question as Pete. My customer doesn’t like that you have to x-out the one div before you can click on another popup. Is there a second function we can add to the button, to check if a div is already opened, then close it to open the second Div?

    Thanks,
    Bob

  20. Hi there, love this script! One question I have is that is there a way to close the one popup automatically when you click on another div? At the moment, you have to click the close cross to open another popup.
    Thanks
    Pete

  21. Hi,

    I’m trying to use your popup inside a repeater that gets it’s data from a database and whenever the popup shows it always shows the same data of the first datafield.

    How can I use it, that whenever I click a link on the repeater it show the popup div related to that data.

  22. oops one last question… I’m using background image:none for the popup background so that you can still see the button links. Isn’t there a way to keep the state active with jquery so that you can tell you’re still on that active link?

    Thanks,
    Bob

  23. thanks so much! worked great! I’m sorry but I have two final questions.

    1] I’m using this example where I have three links/buttons side by side. Each one will trigger a different popup div. The popup divs are all have the same location overlaying the buttons, but I would like the active button to have a higher z-index than the other buttons and a higher z-index than the popup div.
    So if button a is clicked, buttons b and c are hidden by the popup div but button a is visible over the popup div since it has a higher z-index.
    I know jquery can do this, but I couldn’t make it work with your script. Maybe it’s too complicated…

    2] Does the popup div have to be static content or can it load dynamic content, like a post excerpt?

    Thanks so much!
    Bob

  24. This is such a great post. Very simple to understand. I’ve tried everything but am attempting to show 3 instances of this effect on the same page. Cannot. I’ve duplicated each DIV ID and created additional styles for the second ID. It’s only showing the first content DIV.

    Can you display quick example?

    Thanks,
    Bob

  25. Hi,

    How to close div on clicking of outside the div. Instead of clicking on close button or pressing Esc Button.

    If you have any idea please reply me on my mail.

    Thanks