JQuery - Show Element From Centre

JQuery – Show Element From Centre

I recently encountered a requirement for a hidden div to ‘grow’ from its centre outwards, rather from the top, right, bottom or left.  Here is how to do it:

JQuery – Show Element From Centre

First write your html:

<div id="container">
<div id="link">
         <a href="javascript:void(0)" id="boxOne">Click Me</a></div>
<div id="boxOneContent" class="box">
<div class="content">
<h1>Hello World</h1>
Lorem ipsum dolor sit amet, consectetur adipiscing
             elit. Ut ullamcorper consequat dui tempor euismod.

Nam vel odio massa, sed lacinia sapien. Cras ac
             nisi.

</div>
</div>
</div>

The id of the link matches the first part of the id for the corresponding box. For the demo I’ve added in a container div so users can click anywhere on the page to make the box close.  There is also a container for the content within the box to stop the content wrapping as the box expands.

Now your CSS, which positions the box centrally over the link.  I’ve only put the key aspects of it here, check the demo for the full code:


#link {
    float: left;
    border: 1px solid red;
    text-align: center;

    width: 40px;
    height: 40px;
    padding: 5px;

    margin-left: 125px;
    margin-top: 125px;
}

#boxOneContent {
    background-color: #000;
    color: #fff;

    padding: 20px;
    width: 160px;
    height: 160px;
    position: absolute;

    top: 150px;
    left: 150px;

    margin-left: -100px;
    margin-top: -100px;

    display: none;
}

By defining the width, height, padding and margins for #link, the centre of this element is 150px from the top and 150px from the left. Here are the workings: 125+((40+(5*2))/2) = 150.

With padding included, the total width and height of #boxOneContent is 200px.  Therefore the margins set will move the div up and left by half the size of the box.

This is what makes the div ‘grow’ outwards when it appears as the div is expanding bottom right (as usual) but also moving top left to get to these margins.

Finally here is the jQuery that pulls it all together:


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

    $('a').click(function(){

        if($('.box#'+$(this).attr('id')+'Content').hasClass('active') == true) {
            $('.box#'+$(this).attr('id')+'Content').removeClass('active').hide(200);
        } else {
             $('.box.active').removeClass('active').hide(200);
             $('.box#'+$(this).attr('id')+'Content').addClass('active').show(1000);
        }
     });

     $("body").click(function(){
          $(".box").removeClass("active").hide(200);
     });

     $("a").click(function(e){
          e.stopPropagation();
     });

 });

If the box corresponding with clicked link is visible (active), then its hidden. Otherwise, any visible boxes are hidden and the box that corresponds with clicked link is shown.

If user clicks anywhere on the page (apart from links), any open boxes are closed.

Happy coding!

Scroll to Top