Mygel Bergstresser
Mygel Bergstresser

Reputation: 90

Animate element using JQuery

I've been playing around with JQuery and had a few questions.

I would like to animate an element from off screen to it's position after the page is fully loaded.

I have the effect I like, but I feel i approached it from the wrong way. I am positioning the element off page with CSS and using Jquery to move it to the correct spot. Is this normal?

Here is my example:

JQuery

$(document).ready(function() {  
  $( "#box" ).animate({
    top: "62px",
  }, 1000, function() {
    // Animation complete.
  });   
});

CSS

#box {
  width: 100%;
  height: 62px;
  background-color: black;
  position: absolute;
  margin-top: -62px;
}

http://codepen.io/Legym/pen/vEbJqG/

Upvotes: 0

Views: 51

Answers (2)

Tharin Meggett II
Tharin Meggett II

Reputation: 86

I'm not sure what industry standard is, but if you're willing to forsake some early IE 8 compatibility I can offer an alternative using CSS3;

.boxSlideIn{
  animation: slideDown 2s;
  -webkit-animation: slideDown 2s;
}

@-webkit-keyframes slideDown{
  from {top: -62px;}
  to {top: 0px;}
}

@keyframes slideDown{
  from {top: -62px;}
  to {top: 0px;}
}

Then onload just add the class

$(document).ready(function(){
    $('#box').addClass('boxSlideIn');
});

This gives it the proper CSS off the bat, without any weird negative margins. Also you can customize it to your liking.

Upvotes: 0

Rufus
Rufus

Reputation: 171

You can set box style to display:none; :

#box {
  width: 100%;
  height: 62px;
  background-color: black;
  display:none;
}

and then show it

$(document).ready(function() {  
  $( "#box" ).show('slow');
  });   

Upvotes: 2

Related Questions