Create Multiple Pop-up Divs using the jQuery prev() Method

This tutorial is an update on a previous Creative Individual jQuery tutorial – Create a Pop-up div in jQuery. The first tutorial showed you how to create a very simple pop-up div, but after a few requests in the comments, I felt it was important to update the technique so that multiple pop-up divs could be created without duplicating the code unnecessarily.

If you haven’t already read the first tutorial and are new to jQuery, it might be worth reading it to get a better understanding of the basic techniques before trying this slightly more advanced method.

The Technique

In this tutorial we are going to create a simple profile overview page containing 4 profile images and names. When we hover over the image or name a more detailed profile will appear. This div is positioned before the image and name link in the code and is initially hidden. When we hover over the image, a jQuery event will occur which will change the display declaration from hidden to block, making the div appear. This is when we make use of the prev() method.

Tutorial Demo

Still not sure what we are trying to achieve? Check out the tutorial demo below:

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 - Version 2</title>
  </head>
  <body>
  </body>
</html>

With that done, let’s insert our mark-up. First we’ll create a div with an id of container to act as our content wrap (to center it on screen and give it a nice width). Then I’ve inserted some basic information for the viewer in the form of a h1 and p. Very simple so far!

Then we get to the important bit. Create a div with a class of profile. It’s important to use a class because we are going to have more than one of these on screen and of course we want our code to validate. Inside this div create another div with a class of pop-up. Insert whatever kind of information you need here but for the purposes of this example, I’m going to use basic profile information – Name, Age, and Location.

Again inside our div with a class of profile but below the div with a class of pop-up, add the trigger link. Inside my link with a class of trigger I’ve added an image and a span with the profile name.

...
<div id="container">
  <h1>jQuery Tutorial - Pop-up div on hover</h1>
  <p>
    To view profile information for each person, simply hover your
    mouse cursor over the profile image or name.
  </p>

  <div class="profile">
    <!-- Hidden on load by CSS -->
    <div class="pop-up">
      <p>
        <strong>Name:</strong> Person 1<br />
        <strong>Age:</strong> 23<br />
        <strong>Location:</strong> Canada
      </p>
    </div>
    <!-- Show the hidden div on hover -->
    <a href="#" title="Person 1" class="trigger">
      <img src="blank-avatar.gif" alt="Profile Image" />
      <br />
      <span class="name">Person 1</span>
    </a>
  </div>
</div>
...

You then of course repeat the div with a class of profile however many times you need, but the basic structure remains the same.

Next we’ll need to create a div to clear the floats we will be adding to the profile divs in our css. I tend to always use a class of clear for this purpose. However you could add this style to almost anything, such as a footer or section.

...
      <!-- A clear div to sort out our floats -->
      <div class="clear">
        <p>
          This techique makes use of the <strong>prev()</strong>
          method.
        </p>
      </div>

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

There’s one last thing we need to do before we are finished with our HTML. Let’s link to our stylesheet which we will be creating in the next step.

...
<head>
  <meta charset="utf-8" />
  <title>jQuery Tutorial - Pop-up div on hover - Version 2</title>
  <link rel="stylesheet" href="styles.css" type="text/css"
  media="screen" />
</head>
...

The CSS

Now its time to make things look a bit prettier. Create a new document and name it styles.css, i.e. the file name we have just linked to in our HTML.

First let’s quickly sort out our basic styles and wrapper div:

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;
  text-decoration: none;
}

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

All pretty basic stuff. Next we’ll style the profiles by floating them left and adding a width, plus giving our span a little bit of styling to make it sit nice.

div.profile {
  width: 70px;
  text-align: center;
  float: left;
  margin: 10px 37px 30px 38px;
}

span.name {
  display: block;
  padding-top: 5px;
}

Now the important bit, the pop-up div itself. We are going to use position: absolute and display:none, plus a bit of styling to make it look good.

/* HOVER STYLES */
div.pop-up {
  display: none;
  text-align: left;
  position: absolute;
  margin-top: -100px;
  width: 120px;
  padding: 0px 13px;
  background: #eeeeee;
  color: #000000;
  border: 1px solid #1a1a1a;
  font-size: 90%;
}

And don’t forget our clearing div to sort our our floats on the profile divs.

div.clear {
  clear: both;
}

That’s the CSS done! Easy.

The jQuery

Now for what you’ve all be waiting for, the jQuery! Head back over to your HTML file. First we need to link to the jQuery library. I pretty much always link to Google’s files rather than download my own copy. The main reason for this is that it tends to speed things up a touch with user experience. Insert the following into the head of your HTML file.

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

Next we are going to create our pop-up effect. You can create your jQuery code in an external javascript file, such as popUp.js and linking to it just like we did above for the jQuery library. And in fact if you’re using a lot of javascript/jQuery I’d recommend it to keep things clean and legible. However for this example I’m going to write my code directly into the head of my HTML, below the line where I have link to Google’s jQuery library.

Note: If your writing into the HTML head, you’ll need to wrap your jQuery with script tags:

<script type="text/javascript">
...
</script>

First let’s make our document ready. Below I’m using the long version for legibiliy but feel free to use the short version – $(function() { … });

$(document).ready(function() {
...
});

If the javascript is running, i.e. the user doesn’t have javascript disabled or isn’t using a device that doesn’t support it, we can then use jQuery to change some CSS on our pop-up divs. First we’ll change the display declaration to display:block, then we’ll set an opacity declaration of opacity: 0:

$(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'})
});

Next we are going to make use of the .hover() function, so that when someone hovers over our trigger, the image and span which are contained within the trigger link, something happens:

...
$("a.trigger").hover()
...

Inside this hover method we are going to create a function which will animate our pop-up divs, causing them to fade in. We’ll will use the this selector to select the current element and the .prev() method to select the previous element from the selector – in this case the current selector is a.trigger that we hovered over and the previous element is div.pop-up just before it in the code. We will then use .animate() to change the opacity from 0 to 1 and finally, set the animation speed. Sounds a lot but all this happens in only a few lines:

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

OK, so far so good. If you check your page in the browser you’ll see that our fade in effect is working perfectly. However, there is quite an obvious problem. The pop-up div doesn’t fade out again when we hover off. In fact it just hangs around there getting in the way! That’s because we haven’t told it to fade back out again when we hover off. Thankfully the .hover() function includes a callback which allows us to animate the hover off state. So let’s sort it out now.

We are going to do pretty much the same thing, only this time the opacity will change from 1 to 0 and we’ll speed up the animate a bit so that the pop-up fades out quicker than what it fades in:

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

Rechecking your page in the browser, you can now see that everything is going according to plan.

That’s it!

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

    Heres some code to have multi boxes that can move and also have a tail. have fun:

    $(document).ready(function() {
    var moveLeft = 0;
    var moveDown = 10;
    //If Javascript is running, change css on product-description to display:block
    //then hide the div, ready to animate
    $("div.pop-up-tooltip").css({'display':'block','opacity':'0'})

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

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

    //quick function for tooltip color match
    function fixToolTipColor(){
    //grab the bg color from the tooltip content - set top border of pointer to same
    $('.pop-up-tooltip-pointer-down-inner').each(function(){
    var bWidth = $('.pop-up-tooltip-pointer-down-inner').css('borderTopWidth');
    var bColor = $(this).parents('.pop-up-tooltip').css('backgroundColor')
    $(this).css('border-top', bWidth+' solid '+bColor);
    });
    }
    });

    div.pop-up-tooltip {
    display: none;
    text-align: left;
    position: absolute;
    margin-top: -100px;
    width: 120px;
    padding: 0px 13px;
    background: #eeeeee;
    color: #000000;
    border-width: 2px !important;
    /* border: 1px solid #1a1a1a; */
    font-size: 90%;
    }

    .pop-up-tooltip .pop-up-tooltip-pointer-down, .pop-up-tooltip .pop-up-tooltip-pointer-down-inner {
    position: absolute;
    width:0;
    height:0;
    border-bottom-width: 0;
    background: none;
    }
    .pop-up-tooltip .pop-up-tooltip-pointer-down {
    border-left: 7px solid transparent;
    border-right: 7px solid transparent;
    border-top-width: 14px;
    bottom: -14px;
    right: auto;
    left: 3.5%;
    margin-left: -7px;
    }
    .pop-up-tooltip .pop-up-tooltip-pointer-down-inner {
    border-left: 0px solid transparent;
    border-right: 20px solid transparent;
    border-top: 10px solid #eee;
    bottom: auto;
    top: -14px;
    left: -5px;
    }

    • Laura Montgomery says:

      Hi again Sven, thanks for the code extract, it really helps. From a quick glad I was quickly able to see that you’ve actually combined the two samples of code together. Although they are achieving a very similar effect, they are actually working in different ways – just to make matters confusing.

      The first code positions the div according to your mouse cursor location, which is why we need to create some variables to hold this information – var moveLeft and var moveDown in this case. And the second one uses CSS to position the div and jQuery to change the CSS from opacity 0 to 1.

      If you take out all the jQuery from the first sample of code, you should find that things work correctly. Don’t forget that you can download the source files it you need to look/copy from them.

      Let me know how you get on.

  2. Pingback: 20 Powerful And Useful jQuery Tutorials Of Year 2011 | WebTabLab.com

  3. Ryan says:

    Even better! Just viewed your first tutorial on pop-up divs, this ones got the bells and whistles! Thanks for posting this.

    • Laura Montgomery says:

      Hi Ryan, thanks for commenting and glad you like it. Hope you have lots of fun using this script in your own projects.

  4. Pingback: 55 Best Jquery Tutorial - Design Freebies

  5. This works great until I put in the text I want to show (as seen below) I’m not sure if it’s the punctuation, or what but I can’t get this work when I add this into the pop up div:

    I live on the west side of Michigan about 20 minutes from Grand Rapids and 30 minutes from the beach. I love it here, the winters can be long, but I love the seasons. I have two wonderful, energetic boys, Nate 9 and Zach 6. They are my constant inspiration. I am the owner of Cocoa Daisy and love it! The hours are long but the commute (down the stairs to my office) is short!
    I have been scrapbooking for about 12 years and have had layouts and mini albums published in various magazines and idea books. I have been a Creating Keepsakes HOF honorable mention twice and became a Memory Makers Master in 2009.
    My schooling and background are in fine arts and graphic design, this tends to come through in my scrapbooking style: bold and graphic with a touch of whimsy. I love to have all the elements on a layout support it’s theme in some way, and to draw people in and have them take a minute to discover all the little details. My journaling is always honest and from my heart.
    Being artistic is a driving force in my life – I have to do something creative everyday, whether it’s gardening, decorating, sewing or scrapbooking! I am very excited to be a part of the Cocoa Daisy Design Team and hope that I can inspire you!

    • Laura Montgomery says:

      Hi Shelly, thanks for commenting and sorry that you’re having trouble with the script. I don’t think the content within the div should be causing any problems – it’s just a normal div being dynamically displayed using jQuery and CSS. The only thing I can think of is to double-check that all your tags are closed and that you haven’t changed the order of the code, i.e that the div you want to hide is BEFORE the trigger link. Hope this helps…

      Thanks for commenting,
      Laura

  6. richard lewis says:

    HI Laura

    Nice tutorial….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

    • richard lewis says:

      apologies if ive asked twice, not sure if a previous message was sent

      • Laura Montgomery says:

        Hi Richard,

        Sorry its taken me a bit of time to get back to you.

        The code is simply set to display the content within the div with a class of pop-up:

        <div class=”pop-up”>
        <p>
        <strong>Name:</strong> Person 1<br />
        <strong>Age:</strong> 23<br />
        <strong>Location:</strong> Canada
        </p>
        </div>

        So quite simply you should just be able to change the code within the div tags:

        <div class=”pop-up”>
        <p>
        My custom text.
        </p>
        </div>

        <div class=”pop-up”>
        <img src=”pic.jpg” alt=”My image” />
        </div>

        You could also add another class so that the boxes could be styled differently, e.g. a different background colour.

        <div class=”pop-up blue-bg”>
        <p>
        <strong>Name:</strong> Person 1<br />
        <strong>Age:</strong> 23<br />
        <strong>Location:</strong> Canada
        </p>
        </div>

        Hope this answers your question.

        Thanks,
        Laura

  7. Nikola says:

    Hi,
    I have problem when pop-up element is over another a element then a hover only works on that parts where div what is pop-up does not pass. Because I have a lot a element what is pop-up on the small area. I hope that you understand question.

    • Laura Montgomery says:

      Hi Nikola, I think I understand what you are saying. That you have other elements on the page that are hiding/covering the pop-up element (or perhaps the pop-up trigger element)? You might need to play about with the z-index of the other elements so that your trigger element is positioned above these other elements.

      Not too sure if that helps, perhaps you have an online version I can look at?

      Thanks,
      Laura

      • Will says:

        Hi Laura, great script.Thanks a lot for posting. I’m having the same problem and I tried wrapping a around the trigger image and using z-index to place it above the overlay. However, now the trigger doesn’t work. Any ideas?

        thanks

      • Luca says:

        hi Laura!
        That was a really good tutorial! thank you very much!
        I have two questions for you. 1-Just as at Nikola and Will some of the elements I created are covered by the pop up windows even when the are not on! I followed your tip and tried to play with the z-index and I applied it to the trigger element .trigger a{z-index:100;} and/ or the span.name and the div.pop-up, but did not help that much. The best I could get was the span in the front of the pop.up, which I also don’t want. How can i resolve the problem? 2-the position of the pop up is always relative to the trigger with exactly the same margins, but in my case the position of the trigger is just on the bottom corner of the container…..how can i customize the position of the single pop-up? here is a link of the page i’m talking about (http://271116.lucamule.com/studio-1) and a fiddle https://jsfiddle.net/chiappe_di_bronzo/10hv5rmv/

        thanks for the help!

  8. hello says:

    Hi,

    Could you possibly modify the script so the popup follows your mouse similar to http://creativeindividual.co.uk/2011/02/create-a-pop-up-div-in-jquery/ this script?

    • hello says:

      woohoo! i actually figured this out on my own.

      $(document).ready(function() {

      var moveLeft = 20;
      var moveDown = 10;

      //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);
      }

      )
      $(‘a.trigger’).mousemove(function(e) {
      $(“div.pop-up”).css(‘top’, e.pageY + moveDown).css(‘left’, e.pageX + moveLeft);
      });

      });

      By the way, I really appreciate how carefully you spell out the directions in these tutorials. Very easy to follow. Developers should always show what to do “from the beginning” – it is bad to assume your audience is very fluent in something they are trying to learn!

      Excellent, excellent.

      • sunshine says:

        Hello hello, this is kind of what I was looking but I am having some trouble. what I am trying to do is have 9 thumbnails and when you mouse over it wanted to pop up a larger view of 500 x Height of image. But weird thing is the link disappears. I realized its the margin-top: -100px; I just can’t seem to understand this.

  9. Pingback: 20 Powerful And Useful jQuery Tutorials Of Year 2011 | Easy jQuery

  10. Pingback: 20 Powerful And Useful jQuery Tutorials Of Year 2011 | auto

  11. moral says:

    Please could you tell me what will be script & css , i want popup should appear and user can able to click info in that popup and copy info on popup, until i hover over to another trigger link ?

  12. moral says:

    what actually i required and well,the last popup is giving me the result what i want ,but the first one or chain of div not so ?

    see demo : http://jsfiddle.net/2kjVh/65/

  13. Nes says:

    Great tutorial! Awesome job with the step by step explanation.

  14. Gulshan kumar says:

    Nice Tutorials Laura.

    I am web UI designer & HTML Developer & a beginner in jQuery. Nowadays i am searching jQuery tutorials websites, blogs & Articals. before 2 days i read your tutorial & i realize your language is very user-friendly. i am understanding your tutorials very easily. so I have to say, thank you.

    Please give me a favor, i don’t know javascript, so can i understand jQuery very well. some persons says me YES & some NO. so what is right ?

    • Laura Montgomery says:

      Hi Gulshan,

      Thanks for the comment and glad you found the tutorial helpful and easy to understand.

      With regards to your question, I would say that you can work with the basics of jQuery without any real understanding of Javascript but if you want to start creating some really interesting and complex effects you are very quickly going to find yourself using Javascript to some degree – such as variables, functions and arrays.

      Hope that answers your question,
      Laura

  15. Banwari says:

    Thanks for such a nice code .This make me a fan of your’s , It’s really solved my problem.
    Waiting for your new post.

  16. Celine says:

    Hi there,

    Thanks for the nice code. But ; )

    I have tried to apply this code into a table. My design has 5 circles something like Olympics’ Circles. I wish my div(s) to appear when going over my circles.
    The code is working only on the first cell of the row and not on the others…
    What can i do to fix the problem?
    Hope somebody can understand what i mean?

    Thanks, Celine

    • Laura Montgomery says:

      Hi Celine,

      I’m sure you have good reason for using a table but why have you used one? Depending on what’s going on in the table this could explain the issue you are having. Perhaps you can submit your code? This might show me what’s going wrong.

      Thanks,
      Laura

  17. balan says:

    The code is good for me, But the thing is i need same functionality with the click() event than hover().

  18. Gerry Williams says:

    I was looking for an “on hover” jquery popup to use in conjunction with a “Frequently Asked Questions” page I am developing and I came upon your nice blog and code. I did not want to use it as a profile popup so I thought I would tweak it a touch to meet my needs. I found that my css & jquery knowledge is inadequate to get all of the way to where I want to go.

    I would appreciate some advice on how to solve two problems that I encountered:
    1. How to overcome/control the current limit on the text length in the popup
    2. How to make all of the image and all of the text in each FAQ be hover ‘sensitivity areas’

    I think that the final product, clearly with your help, would benefit the community if you would publish it too.

    Here is the link to my testing ground:Code

    At the bottom of the page there are two links:
    1. Read Me which describes the problem in detail
    2. jquery-popup-div-02-GJW.zip which has all of my files .

    The read-me text file which attempts to describe the problems and the code that I modified. In the code, the FAQ text describes some of the problems too. Note: the borders were changed as part of my diagnostics and some of the code comments would certainly have to be removed if/when you publish this.

    I hope you have time for this.

    • Gerry Williams says:

      Hi Laura,

      I looked at the Blog comments & replies above and it looks like the issue raised by Nikola on 24 February is the similar to the problem that I am having (the hover doesn’t work on some of my elements).

      I changed the div.pop-up margin-top value to move the popup div ‘out of the way’ and the hover areas and images became responsive. I am not facile with some of CSS but I dinked around with inserting various values for z-index for most of the divs (after I restored the default margin-top and that did not solve the problem. If the pop-up div content overlays the FAQ question then that area becomes insensitive to hover. Since my FAQs are vertically stacked this looks like a serious challenge to changing your design to meed my needs. Any recommendations?

      Note, a solution to this will also likely solve my “Issue #2″ – increasing the amount of content in the popup.

      One possibility is to move the popup position to the right of the question. It is not elegant (wastes page space) but absent ab better solution I’ll try it.

  19. Gerry Williams says:

    Okay,
    I changed the layout;
    1. made the left margin of the FAQ div =0, and made it a width of 600px.
    2. changed popup div width and top & left margins to plunk it to the right of the question.

    That makes the hover logic function. A nicer solution would be to solve it with the original layout and have some z-index type solution.

    Please let me know if it is possible.

    Thanks a million for a nice script.

    -g-

  20. Amazing blog! Do you have any suggestions for aspiring writers?

    I’m planning to start my own website soon but I’m
    a little lost on everything. Would you advise starting with a free platform like
    Wordpress or go for a paid option? There are so many
    options out there that I’m totally overwhelmed .. Any recommendations? Thanks!

    • Laura Montgomery says:

      Hi there, I personally opted for WordPress because it’s been built around the idea of blogging and therefore seemed the perfect fit for me. The best bet is to research the other options out there, taking into consideration any other functionality you may need from your site.

      You may want to manage and host your own blog/Wordpress site but if considering WordPress a hosted option may be a good way to test the water – http://wordpress.com/

  21. Leonard Mutuku says:

    Hi, Thanks a lot 4 the post, it really did help me. The Code works perfectly well, but could u help me on what to do when i hover over the Pop – up div so that it doesn’t disappear.

    Thanks,

    Leonard

  22. André Pires says:

    I have a problem joining this with a code that i have that is like a horizontal scroller for my website. can you help?

    (function($) {
    $(function() {
    $(“#scroller”).simplyScroll({
    pauseOnTouch : true,
    pauseOnHover : true
    });
    });
    })(jQuery);

  23. paraz says:

    Thanks a lot. This helped me a lot.. Thank you very much..

  24. RW says:

    Awesome tutorial. How can I do this with click rather than hover?

    Thanks,
    Bob

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