Search code examples
jqueryhtmlscale

Trying to scale from middle with jQuery


I have a little problem with the 'scale' effect of jQuery-ui. When I hide the element (in this case, a red square), it goes from the top to the middle and from the bottom to the middle until it dissapears, but, when I wanna show it, it just expands both vertically and horizontally from the middle and the center. Any clues on how I can do the same animation when hiding and showing?

Here's the code with and the fiddle:

HTML:

<div id="container" style="position: relative;"></div>
<button onclick="init2();"><<</button>
<button onclick="init();">>></button>

JS:

function init()
{
    $('#container').show('scale', {direction: 'horizontal', origin: ['middle', 'center']}, 2000);
}

function init2()
{
    $('#container').hide('scale', {direction: 'vertical'}, 2000);
}

http://jsfiddle.net/yd1y6cbr/6/


Solution

  • The UI seem to be buggy in that effect.. (it cant scale up vertically)

    But you can use CSS transitions (a better solution than jquery UI)

    $('.hide').on('click', function() {
      $('#container').addClass('off');
    });
    
    $('.show').on('click', function() {
      $('#container').removeClass('off');
    });
    #container {
      background-color: red;
      width: 300px;
      height: 300px;
      -webkit-transition: -webkit-transform 2s;
      -moz-transition: -moz-transform 2s;
      -ms-transition: -ms-transform 2s;
      -o-transition: -o-transform 2s;
      transition: transform 2s;
    }
    .off {
      -webkit-transform: scaleY(0);
      -moz-transform: scaleY(0);
      -ms-transform: scaleY(0);
      -o-transform: scaleY(0);
      transform: scaleY(0);
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    
    <div id="container" style="position: relative;"></div>
    
    <button class="hide">&lt;&lt;</button>
    <button class="show">&gt;&gt;</button>

    http://jsfiddle.net/gaby/tcqjuf7j/