Home > Net >  Animation to center a div in the window
Animation to center a div in the window

Time:05-14

Hi I need an animation that makes a div go from left to center, but it doesn't work. This is my code:

$(document).ready(function () {
        $(log).click(function () {
            var number = $(window).width() / 2;
            $(registrationDiv).animate({ left: number }, 200);
            $(registrationDiv).show();
            $(loginDiv).hide();
        });
    });

this code puts the div slightly to the right and not at center.

CodePudding user response:

The div position is relative to the top left of a div (box). As such your registrationDiv (0,0) point is exactly at the centre of the screen.

Remove half the width of your target div from the number

$(document).ready(function () {
        $(log).click(function () {
            let halfChildWidth = $(registrationDiv).width() * .5   
            var number = $(window).width() / 2;
            $(registrationDiv).animate({ left: number - halfChildWidth}, 200);
            $(registrationDiv).show();
            $(loginDiv).hide();
        });
    });

CodePudding user response:

There are at least a few ways you could achieve this (pure Javascript or jQuery, vanilla CSS with either transitions or CSS animations, an animation library, etc...) but I would suggest using jQuery/Javascript to catch the click event and adding a class with transitioning styles to your element like so:

HTML

<div ></div>

CSS

.box {
  height: 50px;
  width: 50px;
  background: black;
  position: fixed; // position the box relative to the viewport
  left: -25px; // hide the box by moving it over 50%. the other 50% is moved with translateX()
  top: 0;
  transform: translateX(-50%); // needed to align the center of the box with the center of the window
}

.box.animate {
  left: 50%; // position the box in the middle of the viewport
  transition: left 1000ms; // animate the 'left' CSS property with a duration of 1000 milliseconds
}

jQuery

(function ($) {
  $(document).ready(function () {
    $(window).click(function () {
      const box = $(".box");
      box.addClass('animate')
    });
  });
})(jQuery);

Vanilla Javascript (alternative to using jQuery)

window.addEventListener('DOMContentLoaded', () => {
  document.querySelector('.box').addEventListener('click', function(e) {
    e.target.classList.add('animate')
  })
});

CodePen Demo

  • Related