Create a Pop-up div in jQuery

Update (13th August 2011): This technique has been updated to create the same effect with multiple pop-ups. View the new technique here:
Create Multiple Pop-up Divs using the jQuery prev() Method

jQuery is a powerful and easy-to-use Javascript library, like MooTools and and Prototype. It is not surprising that in recent years it has become extremely popular with website designers and has become the Javascript library of choice – I know it’s my favourite!

If you are new to jQuery, you should check out my Beginner’s Guide to jQuery article first, just to get to grips with the basics.

Tutorial Demo

This is an easy tutorial suitable for those fairly new to jQuery. This tutorial will teach you how to create a simple pop-up effect, showing a hidden div, when you hover over the trigger link.

The HTML

Create a new HTML document and insert all the usual code – doctype, html tags, head tags, body tags, etc. as shown below:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>jQuery Tutorial - Pop-up div on hover</title>
  </head>
  <body>
  </body>
</html>

Notice how I am using the HTML5 doctype – <!DOCTYPE html> – it is a good idea to get into the habit of using this.

First we are going to create a div with an id of container to hold our page content and centralise it, just to make things a bit prettier. Inside this div we will add a h1, p (paragraph), and a (link/hyperlink) with an id of trigger. All this of course goes inside the body tags.

...
<body>
  <div id="container">
    <h1>jQuery Tutorial - Pop-up div on hover</h1>
    <p>
      To show hidden div, simply hover your mouse over
      <a href="#" id="trigger">this link</a>.
    </p>
  </div>
</body>
...

Almost done with the HTML, the last thing we need to create is the div which will be hidden on the page loading, and triggered to become visible with the mouse hovers over the a#trigger tag.

...
<body>
  <div id="container">
    <h1>jQuery Tutorial - Pop-up div on hover</h1>
    <p>
      To show hidden div, simply hover your mouse over
      <a href="#" id="trigger">this link</a>.
    </p>

    <!-- HIDDEN / POP-UP DIV -->
    <div id="pop-up">
      <h3>Pop-up div Successfully Displayed</h3>
      <p>
        This div only appears when the trigger link is hovered over.
        Otherwise it is hidden from view.
      </p>
    </div>

  </div>
</body>
...

The CSS

Now that we have our basic code in place, let’s style things up and make our page look a bit prettier. It is also at this stage that we will hide the pop-up div, using the display: none; css declaration.

Firstly, lets set some basic page styles and centre the container div, though if you are using this code within a website project, you don’t need to worry about this step as you will have your own page styles already set-up.

body {
  margin: 0;
  padding: 0;
  font-family: Arial, Helvetica, sans-serif;
  background: #000 url(bg-texture.png) repeat;
  color: #dddddd;
}

h1, h3 {
  margin: 0;
  padding: 0;
  font-weight: normal;
}

a {
  color: #EB067B;
}

div#container {
  width: 580px;
  margin: 100px auto 0 auto;
  padding: 20px;
  background: #000;
  border: 1px solid #1a1a1a;
}

For the sake of speed, I have added my styles inside the head tags of my html document, but for a live project I would always recommend attaching your styles to an external css document using the link tag.

In the css code above I am mostly just tweaking default browser styling, such as text colour, background colour, font-family, padding and margin – all pretty basic stuff. The most important bit is to make sure your div#container has a width and that the horizontal margins are set to auto – this centres the div, but again, pretty basic stuff.

Lastly, we are going to style the pop-up div. This is were the display: none; css attribute previously mentioned comes into play. It hides the div when the page loads. We also need to use position: absolute; so that the div gets positioned correctly with the jQuery we will add next. Again, we will add some basic styling such as width, colour, and padding, just to finish things off.

/* HOVER STYLES */
div#pop-up {
  display: none;
  position: absolute;
  width: 280px;
  padding: 10px;
  background: #eeeeee;
  color: #000000;
  border: 1px solid #1a1a1a;
  font-size: 90%;
}

The jQuery

Now we get to the exciting bit! Let’s add the jQuery to the page and get the pop-up div hover effect working. First we need to link to the jQuery library. You can download the latest files from jQuery.com and link to them locally, but I prefer to link to Google’s library files for my own ease and for speed on the part of any visitors to your site. Insert the following line of code inside the head tags of your html document:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>

Note that it is always worth checking what the latest version is and developing with that. However, this script definitely works with jQuery version 1.5.0.

Now let’s write our basic function. Just like with the css, I would always recommend linking to an external Javascript document, but for the sake of speed I have added my code into the head of my html document.

First let’s create a function:

$(function() {

});

Inside this function we are going to tell the browser that when someone hovers over the a tag with an id of trigger, to show the div with an id of pop-up.

$(function() {
  $('a#trigger').hover(function() {
    $('div#pop-up').show();
  });
});

Testing your page at this stage, you should see the div appear when you hover over the trigger link. However the first issue we have is that it doesn’t disappear again when you hover off the link. Let’s fix that.

By default, the .hover() method has a hover off call back. Add the following code to deal with the hover off method:

$(function() {
  $('a#trigger').hover(function() {
    $('div#pop-up').show();
  }, function() {
    $('div#pop-up').hide();
  });
});

We now have the hover off method set to hide the div#pop-up – great! Now notice when you test this page that the pop-up div appears no where near our mouse pointer. On this small page that is not an issue, but on a longer, busy page this could be a real problem – besides, it looks untidy!

Let’s make the pop-up div appear at our mouse-pointer. First add an e inside the brackets at .hover(function() {, then add the .css method after .show() but before the semi-colon.

$(function() {
  $('a#trigger').hover(function(e) {
    $('div#pop-up').show()
      .css('top', e.pageY)
      .css('left', e.pageX)
      .appendTo('body');
  }, function() {
    $('div#pop-up').hide();
  });
});

If you test your script at this stage, you will probably see the div flash and flicker as it appears and disappears from view. This is happening because the div is appearing right beneath our mouse-pointer. We need to move the div away slightly to deal with this. First create two variables to hold our values:

$(function() {
  var moveLeft = 20;
  var moveDown = 10;
  ...
});

Then add these variables to the e.pageX and e.pageY:

$(function() {
  var moveLeft = 20;
  var moveDown = 10;

  $('a#trigger').hover(function(e) {
    $('div#pop-up').show()
      .css('top', e.pageY + moveDown)
      .css('left', e.pageX + moveLeft)
      .appendTo('body');
  }, function() {
    $('div#pop-up').hide();
  });
});

When you re-test your page this time, things should look and behave much better. The div should pop-up when hovering over the trigger link, appearing 20px to the left and 10px below your mouse pointer. And it should disappear again when you hover off the trigger link.

We are pretty much there – however the div is pretty static once it appears on screen. Let’s make it follow our mouse pointer and give our script the extra WOW factor!

We are going to use the .mousemove method on the a#trigger selector and tell the div#pop-up to follow our mouse pointer using the same .css methods as before:

$(function() {
  var moveLeft = 20;
  var moveDown = 10;

  $('a#trigger').hover(function(e) {
    $('div#pop-up').show()
      .css('top', e.pageY + moveDown)
      .css('left', e.pageX + moveLeft)
      .appendTo('body');
  }, function() {
    $('div#pop-up').hide();
  });

  $('a#trigger').mousemove(function(e) {
    $("div#pop-up").css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
  });

});

At this stage you can remove the first set of .css() methods as they are no longer needed. However, to make the code easier to read, I have just commented out the 3 now unnecessarily lines and added the semi-colon in after .show(). The code below is the final jQuery script:

$(function() {
  var moveLeft = 20;
  var moveDown = 10;

  $('a#trigger').hover(function(e) {
    $('div#pop-up').show();
      //.css('top', e.pageY + moveDown)
      //.css('left', e.pageX + moveLeft)
      //.appendTo('body');
  }, function() {
    $('div#pop-up').hide();
  });

  $('a#trigger').mousemove(function(e) {
    $("div#pop-up").css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
  });

});

Get The Source Code

You can download the complete tutorial source code by clicking on the big button below and unzipping the file.

This entry was posted in jQuery, Tutorials

Don't forget to share!
If you liked this post, please share it with your friends - Thanks!

Your Comments

  1. Pingback: 33 Ví Dụ jQuery Popup Tốt Nhất | Làm Web

  2. Dieter says:

    Firefox compatibility issues.
    function() change to function(event)

  3. Hello! I’ve been reading your blog for a while now and finally got the courage to go ahead
    and give you a shout out from Porter Tx! Just wanted to mention keep up the great job!

  4. Ganesh says:

    This is not working inside php

  5. I have tried your coding and now I’m trying to figure out how to add it to my website.

    Thank you for your great programming. I really appreciate you a lot for helping me.

    You are a SMART ASS! Thanks again!

  6. I have tested it and wrote on my html page but the problem arises as I can only insert either the modalbox or the popup div on hover.

    I could not use my modalbox to zoom my photo.

    Is there a wonderful way to insert both popup div and modalbox together? Meaning I could use modalbox to zoom photo and then popup to popup text.

    Your help is needed.

    Thank you.

  7. php_coder says:

    thanks ………………….a lot

  8. Amar says:

    If you change the ID of pop-up to a class so you can use it multiple times on one page, change the # to . in the CSS and jQuery, the pop divs appear one behind another once it starts replicating.

  9. ife says:

    thanks…….that ws a cool tutorial….straight to the point

  10. Henke says:

    Hi!
    Great Tutorial, i have some issues with positioning the pop-up box. mine goes to the bottom left.

  11. Daiden Sacha says:

    Thank you for your guidance and the resources. Really cool. I had a few issues getting it to work but found the conflict in my css and sorted it out. It looks great.

    One thing I will be trying to do is to change the appear to fade in and fade out, so the transition is smoother.

    Thanks

  12. Krista says:

    Poste super plaisaոt !!

  13. abhishek says:

    Great answer. I need a help here..
    the popup window does not close

  14. Kunal samal says:

    It great, if i want to have multiple popup’s on the page?

  15. Hafiz Yasin says:

    very nice teaching method.

  16. Pingback: How to change the div content dynamically? | Yelin Answers

  17. karambir says:

    Sir i want a popup on href click event. Please help me.

  18. vasudha rao says:

    Very good and very simple,understandable coes and explanation.

    Thank you.

  19. vasudha rao says:

    very good,very simple and understandable codes and explanation

    Thank you sir.

    sir, I want popup div when we click on a button.
    please help me.

  20. rick says:

    Thanks for this tutorial very nice tutorial and i found another easy and good tutorial of how to creating popup dialog box using jquery and css you can view that tutorial it is very easy to understand http://talkerscode.com/webtricks/simple%20and%20best%20custom%20popup%20box%20using%20jquery%20and%20css.php

  21. neha gaikwad says:

    really nice work done its very helpful.Great job. thank you

  22. S says:

    Worked like a charm. Thank you so much! :)

  23. FG says:

    Great! Thanks

  24. Karibel says:

    Works nice. Thanks!

Leave a Reply to Dieter Cancel 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>