Search code examples
javascriptjqueryhtmlcssscale

Using jQuery .scale to evenly reveal elements from their center


Fiddle here.

Description of problem:

I'm attempting to use the jQuery UI scale effect to reveal a large element (div with a background image) from its center point, and having it expand outward evenly across the screen. The effect I'm going for is to make it appear as though the element is zooming in toward you.

Unfortunately, it slides up and to the left instead of evenly bringing the image into visibility. Defining its origin and direction does not solve the issue. Any ideas?


Solution

  • You just need to use a technique described in the answer to Stretch and scale a CSS image in the background - with CSS only.

    For example, adding a background-size: 100% 100%; rule to your .box div works:

    // Small plugin to center any element.
    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;
    }
    
    // Call the .center(); function to the ".box" div.
    // This can be used to center anything. just use .center(); on any element.
    $('.box').center();
    
    // When the window is resized, center the div to adjust to the resize.
    $(window).resize(function() {
      $('.box').center();
    });
    
    // Now call the jQuery UI animation.
    $('.box').show("scale", {
      percent: 100
    }, 1000, function() {
      // on Animation Complete, do something.
    });
    .box {
      width: 820px;
      height: 461px;
      background: url('http://www.techulator.com/attachments/Resources/10090-1015-Transforming-Windows-Iron-Man-s-JARVIS-Theme-Interface.png') no-repeat;
      background-size: 100% 100%; /** this was added **/
      display: none;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
    
    <div class="box"></div>