Search code examples
jquerycssanimationslidetoggle

jQuery slideToggle (Toggle from middle point)


I am using slideToggle(); method, it's working, I just want to slide in and out from middle point of image not slideup to left corner. I also don't want zoomIn or zoomOut event.

$(document).ready(function() {
  $('.btn').click(function() {
    $('img').stop().slideToggle(5000);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button class="btn btn-default">My Button</button>
<br><br><br>
<img class="img-responsive" src="http://news.stanford.edu/news/2012/september/images/online_keyboard_news.jpg">

JSFiddle


Solution

  • As an alternative to using jQuery animations, what you are looking for (assuming I understand what you are explaining) can be accomplished with a slight change to your DOM structure and adding a few lines of css.

    const toggleButton = document.getElementById("toggle-button");
    const imageContainer = document.getElementById("image-container");
    
    toggleButton.addEventListener("click", () => {
        imageContainer.classList.toggle("show");
    });
    button {
        position: relative;
        margin: 20px;
    }
    
    /* Create a wrapper element that matches the image size */
    /* and set it to the desired image reveal size */
    
    .wrapper {
        width: 600px;
        height: 400px;
        position: relative;
        margin: 0 auto;
    }
    
    /* Add the image container element and set it to the center of the wrapper */ 
    /* set the width and height to 0 so the image isn't visible */
    
    .image {
        top: 50%;
        left: 50%;
        width: 0;
        height: 0;
        position: absolute;
        background: url(http://news.stanford.edu/news/2012/september/images/online_keyboard_news.jpg)
        no-repeat center center;
        transition-duration: 1000ms;
        transition-timing-function: cubic-bezier(0.5, 0, 1, 1);
    }
    
    /* When we want to show the image animate the width and height */
    /* to fit the container as well as adjust the margin to keep it centered */
    
    .image.show {
        width: 100%;
        height: 100%;
        position: absolute;
        margin-left: -300px; /* set to half of the containing elements width */
        margin-top: -200px; /* set half of the containing elements height */
        transition-timing-function: cubic-bezier(0, 0, 0.5, 1);
    }
    <button id="toggle-button">
      Toggle Image
    </button>
    
    <div class="wrapper">
      <div class="image show" id="image-container"></div>
    </div>

    I created a quick example of how it could work with css only using javascript to toggle a class on the image element.

    Comments in the css describe how this was accomplished.