Grow your CSS skills. Land your dream job.

jQuery .show() from center of element?

  • # July 15, 2013 at 12:14 am

    Is there a proper method when using jQuery **.show()** to display the element from its center as apposed to the default top/left?

    There is a way to accomplish this using the “scale” property of the jQuery UI library, but it seems a bit overkill to rely on that for something so simple. Also I’m aware this can be achieved using a css3 animation + transform scale… but I’m solely interested in a standard jQuery method. If anyone could shed some light on this matter, I would much appreciate it. Thanks!

    **jQuery UI example:**

    http://jsfiddle.net/r9aeb/

    # July 15, 2013 at 5:30 am

    It’s actually not really “simple” for javascript to create that effect. You’d have to add a wrapper with the same dimensions as the item you want to animate with position relative.
    Add position absolute to the target element, and set the height/width to be 0 and start animating that up, while repositioning it each time it increases in height/size.

    It’s not something that everyone wants to do by default which is why it’s not in the jQuery base library.

    Edit: To answer your question. There isn’t a simple way of doing that (since it’s a relatively complex animation) without either writing it yourself or including some library like jQueryUI to do it for you.

    # July 15, 2013 at 9:24 am

    I’m assuming you mean position the div in the middle? If so:

    Click Here for an example using jQuery.



    jQuery.fn.center = function () {

    this.css("position","absolute");
    this.css("top", Math.max(0, (($(window).height()
    - $(this).outerHeight()) / 2) +
    $(window).scrollTop()) + "px");
    this.css("left", Math.max(0, (($(window).width()
    - $(this).outerWidth()) / 2) +
    $(window).scrollLeft()) + "px");
    return this;
    }

    $('.box').center();

    $(window).resize(function() {
    $('.box').center();
    });

    $('.box').show("scale", 1000
    ,function() {
    // Do something...
    }
    );

    PS, instead of using window, you can use any div to center absolutely to.

    # July 15, 2013 at 4:04 pm

    Thanks for the suggestions!

    @jamy_za

    You clarified exactly what I was curious about… thanks

    @jamesMD

    Your solution is nice, but tackles a problem different than mine… anyways, thanks for the effort

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".