I have a div absolutely positioned at top: 0px
and right: 0px
, and I would like to use jquery's .animate()
to animate it from it's current position to left: 0px
. How does one do this? I can't seem to get this to work:
$("#coolDiv").animate({"left":"0px"}, "slow");
Why doesn't this work and how does one accomplish what I am looking to do?
Thanks!!
This question is related to
jquery
jquery-animate
Here's a minimal answer that shows your example working:
<html>
<head>
<title>hello.world.animate()</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"
type="text/javascript"></script>
<style type="text/css">
#coolDiv {
position: absolute;
top: 0;
right: 0;
width: 200px;
background-color: #ccc;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
// this way works fine for Firefox, but
// Chrome and Safari can't do it.
$("#coolDiv").animate({'left':0}, "slow");
// So basically if you *start* with a right position
// then stick to animating to another right position
// to do that, get the window width minus the width of your div:
$("#coolDiv").animate({'right':($('body').innerWidth()-$('#coolDiv').width())}, 'slow');
// sorry that's so ugly!
});
</script>
</head>
<body>
<div style="" id="coolDiv">HELLO</div>
</body>
</html>
Original Answer:
You have:
$("#coolDiv").animate({"left":"0px", "slow");
Corrected:
$("#coolDiv").animate({"left":"0px"}, "slow");
Documentation: http://api.jquery.com/animate/
If you know the width of the child element you are animating, you can use and animate a margin offset as well. For example, this will animate from left:0 to right:0
CSS:
.parent{
width:100%;
position:relative;
}
#itemToMove{
position:absolute;
width:150px;
right:100%;
margin-right:-150px;
}
Javascript:
$( "#itemToMove" ).animate({
"margin-right": "0",
"right": "0"
}, 1000 );
This worked for me
$("div").css({"left":"2000px"}).animate({"left":"0px"}, "slow");
so the .animate method works only if you have given a position attribute to an element, if not it didn't move?
for example i've seen that if i declare the div but i declare nothing in the css, it does not assume his default position and it does not move it into the page, even if i declare property margin: x w y z;
Source: Stackoverflow.com