CSS and jQuery Tutorial: Overlay with Slide Out Box

The other day I was creating an overlay with a box for Cody’s jTextTranslate jQuery Plugin and I thought, it could be useful to describe the technique in a tutorial. […]

The other day I was creating an overlay with a box for Cody’s jTextTranslate jQuery Plugin and I thought, it could be useful to describe the technique in a tutorial.

So, I want to show you how to create a semi-transparent overlay that covers all the page, and a message box that can be turned off again. You can see on the screenshot how that will look.

Then I will show you how to add some jQuery that will make the overlay appear and the message box slide down from the top of the page (try the demo at the end of this post).

Ok, let’s get to work:

Tiny break: 📬 Want to stay up to date with frontend and trends in web design? Subscribe and get our Collective newsletter twice a tweek.

1. The HTML

We just need two elements in our HTML: a div for the overlay and a div for the box. The box will contain a link element for a closing icon and some text. And here we go:

<div class="overlay" id="overlay" style="display:none;"></div>

<div class="box" id="box">
 <a class="boxclose" id="boxclose"></a>
 <h1>Important message</h1>
 <p>
  Here comes a very important message for your user.
  Turn this window off by clicking the cross.
 </p>
</div>

Since we will be referring to these two main elements in the JavaScript later, we should already give them IDs. You can place the overlay and the box div anywhere in your site as a direct child of the body.

The overlay is getting a style tag with display:none since we want it not to be visible initially. The visibility of the box will be handled in the CSS.

Let’s give them some style.

2. The CSS

For the overlay we will simply use a transparent image that will be repeated. We could as well just give it a dark background color and make it transparent with CSS properties, but for now, we will use an image:

.overlay{
    background:transparent url(images/overlay.png) repeat top left;
    position:fixed;
    top:0px;
    bottom:0px;
    left:0px;
    right:0px;
    z-index:100;
}

What we are doing here is to stretch this div by saying that from all sides it’s position is 0. So, no matter how wide the browser window is, this will always make it being stretched over all the page. Using position:fixed will always keep it at 0 no matter where you are in the page, e.g. after scrolling. If we would have used position:absolute we would just have the visible (top part of the page) covered, not including the part after we scroll down. The z-index needs to be very high in order to put this element on top of all the others (except the box).

The box will have the following CSS properties:

.box{
    position:fixed;
    top:-200px;
    left:30%;
    right:30%;
    background-color:#fff;
    color:#7F7F7F;
    padding:20px;
    border:2px solid #ccc;
    -moz-border-radius: 20px;
    -webkit-border-radius:20px;
    -khtml-border-radius:20px;
    -moz-box-shadow: 0 1px 5px #333;
    -webkit-box-shadow: 0 1px 5px #333;
    z-index:101;
}

Again, we have a fixed container here because we want the box to move along as we scroll. For the top property we provide a negative value since we want the box to be ouside of our window i.e. not visible in the beginning. We don’t just say “display:none” since we want the box to appear sliding out from the top, hence we need to work with positioning here.

In order to center the element on the page we simply give it the same distance from the right as from the left. Using percentages allows to adapt elements nicely to all screen sizes – keep in mind that they can vary extremely.

The CSS3 properties add some rounded borders and some shadow to the box. They will not work in IE though.

The z-index needs to be bigger than the one of the overlay. Here, we just add one. Make sure, that you don’t have any absolute positioned elements with a higher z-index.

The closing cross of the box will have the following styling:

a.boxclose{
    float:right;
    width:26px;
    height:26px;
    background:transparent url(images/cancel.png) repeat top left;
    margin-top:-30px;
    margin-right:-30px;
    cursor:pointer;
}

This little element should be halfway “outside” of the box and since the box has a padding of 20 pixels, we “pull” the element up and to the right by giving it a negative margin of -30 pixels for these sides. Negative margins can be used in a lot of ways to help you position elements, don’t be afraid to use them, it’s a good practice trick 🙂 A very useful article about negative margins by Dan Cederholm can be found here.

The h1 element will get some styling, too:

.box h1{
    border-bottom: 1px dashed #7F7F7F;
    margin:-20px -20px 0px -20px;
    padding:10px;
    background-color:#FFEFEF;
    color:#EF7777;
    -moz-border-radius:20px 20px 0px 0px;
    -webkit-border-top-left-radius: 20px;
    -webkit-border-top-right-radius: 20px;
    -khtml-border-top-left-radius: 20px;
    -khtml-border-top-right-radius: 20px;
}

Again, we apply negative margins here to pull the the element into place. Notice, that the CSS3 properties of Mozilla can be written in shorthand.

Okay, that’s the CSS, now let’s move to the juicy JavaScript.

3. The JavaScript

The following code is added at the end of the HTML right before the closing body tag:

$(function() {
    $('#activator').click(function(){
        $('#overlay').fadeIn('fast',function(){
            $('#box').animate({'top':'160px'},500);
        });
    });
    $('#boxclose').click(function(){
        $('#box').animate({'top':'-200px'},500,function(){
            $('#overlay').fadeOut('fast');
        });
    });

});

The #activator element stands for any element in your page that should trigger the overlay and the box to appear. In the demo I simply added a styled link element with that ID.

When that activator element gets clicked, the overlay should fade in really fast (uh, jQuery is just like a natural language…) and just after that’s done, another function should be executed that makes the box slide out from the top. That’s what the animate() does. Then saying that top should be 160 pixels means that we want the box to move from it’s current position to position top:160px, and that should take 500 milliseconds.

After the overlay and the box have appeared, we want to be able to turn the box off again by clicking on the cross icon. The function for that first makes the box slide up again to it’s old position (top:-200px) and makes the overlay disappear afterward.

Be aware that the initial position of the box of -200px depends on the height of the box. If your box is bigger in height, make sure that the initial top value is lower (i.e. -500px if your box is 500px high).

And that’s it! Try to experiment with the speeds for the elements to appear. You can replace the ‘fast’ for any millisecond value as well. And you can also make the box slide out from the right or the left, for that, you just have to adapt the initial values and the values in the JavaScript functions.

Enjoy!

Manoela Ilic

Manoela is the main tinkerer at Codrops. With a background in coding and passion for all things design, she creates web experiments and keeps frontend professionals informed about the latest trends.

Stay in the loop: Get your dose of frontend twice a week

👾 Hey! Looking for the latest in frontend? Twice a week, we'll deliver the freshest frontend news, website inspo, cool code demos, videos and UI animations right to your inbox.

Zero fluff, all quality, to make your Mondays and Thursdays more creative!

Feedback 43

Comments are closed.
  1. Pingback: CSS and jQuery Tutorial: Overlay with Slide Out Box | Codrops | Kerja Keras Adalah Energi Kita

  2. Pingback: uberVU - social comments

  3. Pingback: CSS and jQuery Tutorial: Overlay with Slide Out Box | Codrops | Drakz Free Online Service

  4. Great tut! Exactly what I was looking for. I need one tweak though. What if I wanted the activator to be automatic? Say if someone views my page in IE I want it to pop up automatically and say “We don’t like IE, please use another browser”.

    Thanks!

    PS I love the icon in your footer saying you don’t support IE, but my site I’m trying to do this for is a professional client, so I’m not sure how that would fly.

    • Hello Matt,
      what a brilliant idea! Just replace the jQuery code with the following:

      $(function() {
      										
                      if($.browser.msie){
                          $('#overlay').fadeIn('fast',function(){
                              $('#box').animate({'top':'160px'},500);
                          })
      				}
      
                      $('#boxclose').click(function(){
                          $('#box').animate({'top':'-200px'},500,function(){
                              $('#overlay').fadeOut('fast');
                          });
                      });
      
                  });
      

      That will make the popout appear whenever somebody opens the page with any IE browser!

  5. THANKS!! Worked like a charm. Well other than IE is horrible and wont load the overlay img or the X button. Do you know why that would be? Like I can still close the box by clicking where the img would be, but it’s not there. But in firefox it looks normal (when I had it set to click) so I know the image sources are set to the right reference.

    • Hi Matt!
      I tested the code in IE 7 and 8 and it shows the overlay and the cross. In IE 6 it’s a mess 🙂 Did you test it in Firefox with the new code? Maybe something else is wrong? Let me know, if it works in Firefox! Greets

  6. Pingback: 2010?? jQuery ?????? | Nutspress

  7. Useful little script. Thanks! If people want to use this for larger pieces of text and make sure everything is visible. Change the following:

    CSS

    .box{
    position: absolute;
    top:-600px;
    margin-left: auto;
    margin-right: auto;
    width:940px; (width of the modal)
    left: 0;
    right: 0;
    background-color:#fff;
    color:#7F7F7F;
    padding:20px;
    border:1px solid #ccc;
    z-index:101;
    }

    JAVASCRIPT

    $(‘#box’).animate({‘top’:’-600px’},500,function(){

    The ‘top’:’-600px’ has to be the same as the top:-600px; in your CSS file.

    • Thanks Gideon! I always use position:fixed in overlays because the user can still scroll and the box stays at the same place (but that’s not really necessary). It is definetly better to have it absolute, in case the page is smaller or the content of the box gets bigger. Thanks again! Cheers, ML

  8. Mary Lou, I want to thank you so very much for all the hard work and information you’ve put into this site. I cannot wait to put into practice many of the techniques explained in your tuts. Again, thank you!
    Now to my question, similar to the IE question, I want a thank you message to appear every time the site is visited. What’s the proper way to implement that?

  9. @Helium, works perfectly in the latest version. What exactly does not work for you? Cheers, ML

  10. Great tutorial. Really love this script. Quick question though. Is there a way to have 2 activator links on the same page, each calling a different slide out box?

  11. What a wonderful article. I spend hours on the internet reading blogs, about tons of different subjects. I have to first of all give kudos to whoever created your website and second of all to you for writing what i can only describe as an unbelievable post. I honestly believe there is a skill to writing articles that only a few posses and frankly you have it. The combination of informative and quality content is definitely extremely rare with the large amount of blogs on the internet.

  12. The informative post encouraged me a lot! Saved your site, very great categories everywhere that I read here! I really like the info, thanks.

  13. Great post thank you, but if I wanted to have multiple overlay in a single page? Any help with that?

    Thanks again for the help.

  14. Hi, it’s a great overlay stuff. Works perfectly, but I have a problem.
    I use in the same page the following code:
    type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js”>
    type=”text/javascript” src=”js/jquery.localscroll-min.js”>
    type=”text/javascript” src=”js/jquery.scrollTo-min.js”>

    and the following function:
    $(document).ready(function () {
    $.localScroll.defaults.axis = ‘yx’;
    $.localScroll();
    });

    This code, as you can see, is for scrolling via anchor. When put together the both code, the scroll function does not work anymore.

    I appreciate if you have a solution to this problem (maybe you see easily where is the hillock) or have some usefull links.

    Thanks.

  15. Thank you so much for sharing this.

    I had been toying around with different solutions, but this one works just perfectly–and beautifully.

    Thanks again.

  16. hi. i love this overlay and it works great for my whole site. The issue i am having is that when i add an iframe to the box id the whole overlay breaks.

    is there a way to do this?

  17. Mary Lou, Thanks ever so much for all teh time and effort you put into sharing this with us. I am a total admiror of your work.

    Having the same problem as Dillcard …just wanted to ask if there´s any way to put more than one activator on the same page…. It looks like when I copy the html and paste it below for a 2nd. one, the latter doesn´t work?? Any help with this will be greatly appreciated.

    Thanks in advance all the way from Spain

  18. Hi Mary Lou, Thanks so much for this really helpful tutorial. I found it very helpful to create an interstitial.

    Can you please help me with one thing? Is it possible to have the box centered in the page, no matter what the browser window dimensions?

    Also, is there a way to trigger the box close function after a certain amount of time, say 10 seconds?

    I would really appreciate it if you could help me out with these two queries.

    Thanks in advance…

  19. Hi Mary Lou
    I really liked this tutorial. I wanted to change the width of the box that pops up. But when I do, the box shows immediatly and you can’t click it away.
    Please help, what am i doing wrong?

    tnx in advance

    (BTW a 2nd box works fine, just change the classes.)

  20. Hi Mary Lou,

    Great tutorial and it’s looking and working great for me in Firefox and Chrome.

    With IE, it works well, except there is a small flicker where the screen goes completely black for a tenth of a second at the very beginning and the very end of the animation.

    Do you have any idea what that could be?

    Many thanks

  21. Thanks for an amazing tutorial. I’ve only 1 issue with the code and its that it doesn’t seem to work in Firefox 3.6. Has anyone come across this problem and know any fixes for it?

  22. Hi to all a great tut,

    to all who want that this box also close
    when you press the ‘ESC’ key. Then this function would do it.

    just put this function as additional..

    $(document).keydown(function(e){

    if(e.which == ’27’){
    //om when the ESC(27) key is pressed then will also close.

    $(‘#box’).animate({‘top’:’-200px’},500,function(){
    $(‘#overlay’).fadeOut(‘fast’);
    });
    }

    });

  23. sorry had a mistake this is current tested

    replace keydown with keyup

    $(document).keyup(function(e){
    //om when the ESC(27) is pressed will also close
    if(e.which == ’27’){

    $(‘#box’).animate({‘top’:’-200px’},500,function(){
    $(‘#overlay’).fadeOut(‘fast’);
    });

    }

    });

  24. Firstly its a great tutorial.I am facing just one problem and hoping if someone can help me with the same.I am using the above code in google chome and my white box doesnot appear no matter how much i change the location of the box.

  25. How do I create an overlay like this in one corner of the page where this pop up comes up automatically, but does not block the functionality of the background main page? Like, interested people could answer a simple question there with bullet options. If they are not interested, they can let that overlay be there and navigate through the rest of the page.