Your code works, just make sure #navarrow
is laid out in a way that marginLeft will matter, i.e. position:absolute
.
<div id="navitem-2" class="activeSlide"></div>
<div id="navarro"
style="width:10px;height:10px;background-color:green;position:absolute;">
</div>
<script>
$(document).ready(function() {
if($('#navitem-2').hasClass("activeSlide")){
$("#navarro").animate({marginLeft:"220px"}, 500);
};
});
</script>
Demo: http://jsfiddle.net/cameronjordan/uwf9y/
Updated based on your comment/example:
The class change and checking does not seem to be serving any purpose in this example it is much more straightforward to use live events and trigger the animation directly.
http://jsfiddle.net/cameronjordan/pn5sx/3/
<div id="navitem-1" class="slideable"><a href="#">Slide 1</a></div>
<div id="navitem-2" class="slideable"><a href="#">Slide 2</a></div>
<div id="navitem-3" class="slideable"><a href="#">Slide 3</a></div>
<div id="navarro"></div>
<script>
var prevSlideable;
$('.slideable').live('click', function(){
if(prevSlideable != this.id) {
// do you need this activeSlide class anymore?
if(prevSlideable) {
$(prevSlideable).removeClass('activeSlide');
}
$(this).addClass('activeSlide');
prevSlideable = this.id;
$('#navarro').animate({
marginLeft: this.offsetLeft + "px"
}, 500);
}
});
</script>
If the code needed to be any bigger than this I highly encourage you to use custom events so that code is not repeated and you can keep each code chunk focused on as little as possible; the animation is controlled in one place and triggered wherever needed.