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. NoeG says:

    Nice to see some new content laura, and great stuff too :D take a look at the new templafied when you get a chance…

    • Laura Montgomery says:

      Hi Noe, thanks. I know, a bit of time since my last post so glad that you like it and that I’ve started to make up for my posting absence =D

  2. Jocuri says:

    Laura you obtained a really useful weblog I have been here reading for about an hour.
    I am a newbie and your achievement is really a lot an inspiration for me.

    • Laura Montgomery says:

      Hi Jocuri, thanks – that means a lot to me =D I hope in that case that I’ll be hearing more from you in future when I write some more similar posts.
      Thanks for commenting!

  3. Keith McWhan says:

    Hi Laura,

    Excellent article. Very well written.

    Regards

    Keith

  4. Emma Gallagher says:

    Hello Laura,
    This is so helpful thank you. I’m trying to make a list of different links with different pop ups. Could you tell me how would you go about doing that? I’m new to Jquery.
    Many thanks
    Emma

    • Laura Montgomery says:

      Hi Emma, thanks for your comment.

      Perhaps the easiest way of achieving that is to use a different id for each of your pop-ups and triggers, then duplicate the code adjusting the ids for each. So you would have trigger-1, trigger-2, etc. and a corresponding pop-up-1, pop-up-2, etc. and insert these names into the relevant bits of duplicated code. This means that only the correct pop-up will appear depending on which trigger you hover over.

      Hope this helps, let me know if I can help any more.

      • david says:

        Hi Laura,
        Really like your jquery popup and the clear explanation.
        I’d like to use it for a list of names, hovering over each name opens a popup with details of the person. My question is rather than duplicating the jquery functions for each names id popup and trigger how can I pass the ids to the jquery function? I’m a real novice in this area so code snippets really appreciated.
        Thanks
        (:Dav!d – “Paddling up stream searching for the source”

        • Laura Montgomery says:

          Hi David, glad you found this post helpful and easy to understand. And thanks for commenting.

          Having done a bit more learning myself there is actually a better way of creating this effect without duplicating code. As with everything in jQuery, there’s dozens of ways of doing the same thing! Check out the source code on this site: http://bfl.domain-testing.co.uk/ – it uses prev() rather than referring to an id or class.

          Thanks btw, you’ve reminded me that I need to update this post =D

  5. keep up the good work on the site. I like it! Superb blog post!

  6. The code seems to work fine, but i have a suggestion, can you make it work with dynamic content (such as ajax?) ?

    • Laura Montgomery says:

      Hi Licurici, thanks for the comment and your suggestion. Its definitely something that could be done, I’ll look into it for you.

  7. Pingback: Create Multiple Pop-up Divs using the jQuery prev() Method | Creative Individual Design Blog

  8. Sven says:

    Just a question about constraining:

    I have a screen with several pop-ups and have a few that fall at the bottom of the screen, when I hover and they open i get a scroll bar so I can see the rest of the box.

    My issue is:
    I want this pop-up to open in this area but I want it to appear above the hover location so I don’t have a random scroll bar appearing. This would also apply to left screen making hoz scrollers appear.

    I am currently looking into an effective way to correct this minimal issues but thought you might want to talk about this as it could be another persons Q.

  9. Erol says:

    Just a question: Do you know how to make that floating div always visible? Because if div is larger, it goes down or right from page…
    http://img840.imageshack.us/img840/1979/floatproblem.png
    And thanks for article :)

    • Erol says:

      I found something that works for me, so just wanted to share if someone else need this…

      $('#trigger').mousemove(function(e) {
      // old:
      // var moveLeft = 20;
      // var moveDown = 10;
      //$('#pop-up').css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);

      //new:
      if (e.pageX) {
      var x = e.pageX + 10;
      var y = e.pageY + 10;
      var top = e.clientY;
      }
      else {
      var x = e.clientX + document.body.scrollLeft + 10;
      var y = e.clientY + document.body.scrollTop + 10;
      }

      var elem = $('#pop-up');

      elem.css({'display': 'block', 'left': x + 'px', 'top': y + 'px'});

      if (top + 50 + elem.height() > $(window).height())
      {
      var ntop = top + elem.height() + 50 - $(window).height();
      ntop = y - ntop;

      elem.css('top',ntop + 'px');
      }
      });

  10. Ryan says:

    Excellent tutorial. This is exactly what I was looking for. Simple and perfect.

  11. dan luther says:

    wow…thanks Laura, we’ll written post and very informative post also. keep on posting related tutorials coz i’m following. Thanks again.

    • Laura Montgomery says:

      Hi Dan, thanks. Glad you think its well written, that’s very encouraging. And thanks for following. Cheers :)

  12. Diana Ca says:

    Hi, great post.
    I’ve been looking for a popup div code, yours is very clean but I need some other features.
    I need the popup div to appear on roll over but the information on my popup div has some links, so I need the div to stay open so I can click them, but I would love it if it could close when my pointer is not touching the div nor the link that triggered it in the first place.
    Do you think I could achieve this somehow with your code?

    Thanks in advance!

  13. Laura Montgomery says:

    Hi Diana,

    Thanks for commenting. Yes this is certainly achievable – Firstly, I’d recommend using the updated version of the code: http://creativeindividual.co.uk/2011/08/create-multiple-pop-up-divs-using-the-jquery-prev-method/

    Next you’ll need to make the pop-up a trigger as well, so that it stays open when your mouse is over it. You’ll probably also need to position the pop-up box closer the the trigger element – so that your mouse can move to it without it disappearing again. After that, you can put whatever you like into the div, a link, an image, a tool-tip, etc.

    I haven’t tried it myself but I think if you use the updated code, you’ll just need to add the pop-up div as a trigger. So the code becomes:

    $(document).ready(function() {
    //If Javascript is running, change css on product-description to display:block
    //then hide the div, ready to animate
    $(“div.pop-up”).css({‘display’:'block’,'opacity’:’0′})

    $(“a.trigger”).hover(
    function () {
    $(this).prev().stop().animate({
    opacity: 1
    }, 500);
    },
    function () {
    $(this).prev().stop().animate({
    opacity: 0
    }, 200);
    }
    )

    $(“div.pop-up”).hover(
    function () {
    $(this).stop().animate({
    opacity: 1
    }, 500);
    },
    function () {
    $(this).stop().animate({
    opacity: 0
    }, 200);
    }
    )
    });

    Notice that I’ve removed .prev() from the pop-up hover code.

    As I said, I haven’t tried it myself so I can’t guarantee that this is the best way to do it but should give you a good starting point.

    Good Luck,
    Laura

  14. Richard Lewis says:

    HI

    Excellent Tutorial, for a novice like me, very easy to understand, so a big thanks… I have a similar issue to one that has been mentioned but wanted to clarify something… I want to use the popup for a list of contacts( so use the popups multiple times), if I use the previosuly suggested answer of trigger-1 Popup-1 , trigger-2 popup-2 , are there any alterations to the Jquery that need to be made..?

  15. richard lewis says:

    HI Laura

    Just realised i posted this on the multiple popup page, where im guessing it doesn’t make sense…. i followed this guide

    .How would i adapt this tutorial to make each popup unique with its own content….As a newbie to the developer world any help would be appreciated

    • Laura Montgomery says:

      Hi Richard, thanks for commenting.

      This code is really only good for individual pop-ups. That’s why after some comment requests I developed the updated code which is designed to handle more than one pop-up from the same code. That’s what code I’d look at if I were you because it sounds perfect for what you are trying to achieve.

      Let me know how you get on,
      Laura

  16. Marile says:

    Gracias!! estoy aprendiendo JQuery y tu tutorial me parecio muy fácil de entender!

  17. tiziano123 says:

    sorry but this works only for one link… what do i do if i wanna add other links with different popup div? :(

  18. Ryan S says:

    thanks for sharing it help me a lot, I’ve use the pop up idea in my upcoming tutorial ;)

  19. Kripa Shetty says:

    Superb Tutorial … Great help ..Thanks a lot Laura!

  20. DStheDQ says:

    Hi this is great, but can you have more than one hover/image on a page? I would like to have multiple hovers each with their own pop up – but I can’t see how to do this. Are you able to help? Thank you

  21. Pingback: How to change the div content dynamically on mouse over? [closed] | Easy jQuery | Free Popular Tips Tricks Plugins API Javascript and Themes

  22. Pingback: How to change the div content dynamically on mouse over? [closed] | PHP Developer Resource

  23. Bob says:

    Thanks for the tutorial.

    This works great now my criteria is to create an another div pop up in the same pop up which we did now. Like a Div Pop up in Div Pop up and should go on till the extent we want. I created the the nested div Pop up but it is not hiding as we roll out of the div. i want it to behave like a tree structure.

  24. Sean says:

    Thank you very much Laura. This is EXACTLY what I was looking for.

    Works perfectly!

  25. Pingback: 32 Best jQuery Popup Window Dialog Box Example | Smashing Spy

  26. David M says:

    WOW! This is perfect. I really didn’t want to use a plug-in, etc. With this super-simple code and EXCELLENT explanation – done in just a few minutes!

    Exceptional work on this post, Laura!! (that reads to me as if I actually know you – hehe)

  27. Khandaker Moinur Rahman says:

    Superb post. I was exactly looking for this. Thank you very much :)

  28. Pingback: 30 Best jQuery Popup Window Dialog Box Example | freshdesignweb

  29. Pingback: BLOG » 32 Best JQuery Popup Window Dialog Box Example

  30. jitender says:

    awsome…EXCELLENT wORK

  31. milad reisi says:

    nice article,thank you

  32. Pingback: Very Simple PopUp Box DIV | Aalok Inc

  33. Thank you a lot Laura, your tutorial is one of the simpler and clearer explanation that I’ve found.

  34. masterdany88 says:

    Hey. Great Job. Thanks.
    I had problem with that pop with internet explorer. Could you help me make some workaround for it?

  35. Pingback: 35 ÚTIL JQUERY / JAVASCRIPT CAIXA DE DIÁLOGO POPUP WINDOW | Unconnectable

  36. nahid says:

    i need to display mysql query result in popup div. how can this be achieved?

  37. Pedro says:

    Great instruction sheet, very well written and clear. I like how you broke down the jQuery steps and made it very easy to comprehend and customize.

    • Laura Montgomery says:

      Hi Pedro,

      Thanks for the feedback. I’m glad you found the information easy to understand. Good luck with your implementation of it.

      Thanks,
      Laura

  38. Pingback: Create a jQuery Tooltip | Creative Individual Design Blog

  39. mreshane says:

    Hi laura, thanx for the code, i was trying to implement every jquery inside the blogger blog, it’s not easy though im a wordpress user (means: i only used plugins to create such a things :D) anyway laura, first impression when coming over to your weblog.

    Is there any mousehover appeared for a portfolio like:-

    1. When the person mouseover the link the image will appear and some other paragraph inside it.
    2. Clickable but appeared as a jquery popup box (Reducing page elements – GoGreen :D)
    3. i would like to know if there is any template that only uses 1 page but many of the jquery popup files to insert a paragraph, rather than using a page elements to create stories/blog posting.

    I would like to know more about this if you have one :D

    P/s: Thank you for the mousehover link popup – i really need it!

    Thanx.

  40. HostSleek says:

    HI Laura.. You’ve just saved my hours of doing this.. Keep It Up.

  41. bubble says:

    Hi Laura,

    Good Example for the Pop up window with div tag…but i have one additional requirement with this So i need your help on this.

    when user hover on the link the pop up should display and when user hover out the link pop up should become invisible but when a user roll over the pop up, the pop up should remain visible and when rolling out from pop up it should become invisble…

    So these are the two scenarios need to be implemented.

    1.when user roll out from the link and does not roll over the pop up then pop up should become invisble.
    2. when user roll out from the link and if he roll over the pop up window so it should remain visible and after rolling out from pop up window it should become invisible.

    Your help is appreciated…

  42. sunshine says:

    I just wanted to say thank you for this. It was exactly what I was looking for. I wanted to tweak the code a bit so that the left column pops it up on the right side as your example and the column on the right side pop up on the left side. Took me awhile but after reading through some of other posts found the answer by creating 2… 3 separate classes and 3 separate triggers. Thank you.

  43. sunshine says:

    I just wanted to say thank you for this. It was exactly what I was looking for. I wanted to tweak the code a bit so that the left column and the right column pops it up in separate positions. Thank you.

  44. sunshine says:

    Hello Laura, I was wondering if you can help me a bit as well. I have many popups. but I want to use it so that they show up exactly to either left or right side of the mouse. But I found when I tried to use more than 1 div with the same pop-up class, they pull up the same images.
    I think there has to be a way you can call the pop up class without having to specify it in the script.
    … your help would be greatly appreciated it.

  45. Uthraa says:

    Hi Laura,

    Thanks for the article. Very useful indeed. I am using your code to create pop-up in one of my content pages. I have added a ‘contentplaceholder’ control. And I am not able to write the above code under and tags as I cannot have the tags (since it is referencing to master page which has in the content page.Any idea how I can add this to my website. Appreciate your help.

  46. Luca says:

    Hey Laura,
    nice tutorial! Very useful. I was looking for some minimal and elegant popups and this guide made my day. Just a little question, I’ve saw your “multiple popups tutorial” but it’s not the same visual effect than this one up here. I was wondering if you know where to change parameters (in the CSS or in jQuery) to add multiple popups (each one with different text) that look exactly like this single one.
    Thanks so much
    Luca

  47. Kim says:

    I like this tutorial. Thanks!

  48. I want the rating box to appear on mouse over the icon and the user can able to give ratings by clicking on the star. Any help on this

  49. istockphp says:

    hi Laura, thanks for your idea, i created also popup divs too, hopefully this help.

    http://istockphp.com/jquery/creating-popup-div-with-jquery/

  50. Pingback: JavaScript : How to make multiple pop up div based on database information? | BlogoSfera

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