Reputation: 41
I've been trying to get a header to move in a 200 by 200-pixel square, but my code is not working. I was going to use the topOffset and setInterval method to move the header, but I don't understand how topOffset works. So far my code only moves the header right 200 pixels:
var leftOffset = 0;
var moveRight = function () {
$("#heading").offset({left:leftOffset});
leftOffset++;
if (leftOffset > 200) {
leftOffset = 200;
}
};
setInterval(moveRight, 4);
var offsetTop = 0;
var moveDown = function () {
$("#heading").offset({down:offsetTop});
offsetTop--;
if(offsetTop < 200) {
offsetTop = 200;
}
};
setInterval(moveDown,4);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<h1 id = "heading">Hello World!</h1>
Upvotes: 0
Views: 312
Reputation: 41
I don't see "down" listed as a possible coordinate for offset in jQuery's documentation, try "top" instead, that should be the only update needed.
var leftOffset = 0;
var moveRight = function() {
$("#heading").offset({
left: leftOffset
});
leftOffset++;
if (leftOffset > 200) {
leftOffset = 200;
}
};
setInterval(moveRight, 4);
var offsetTop = 0;
var moveDown = function() {
$("#heading").offset({
top: offsetTop
});
offsetTop--;
if (offsetTop < 200) {
offsetTop = 200;
}
};
setInterval(moveDown, 4);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<h1 id="heading">Hello World!</h1>
Upvotes: 0
Reputation: 337627
For animation like this you are much better off using CSS, not JS. For starters it performs much better due to CSS being hardware-accelerated. It's also much simpler to implement and works even if someone has JS disabled in their browser.
In your case you can use keyframe animation to set the position of the element at each stage. Try the below example. Note that I used 150px instead of 200px only so that the effect is easier to see in the snippet. You can easily change the top
and left
values to anything you need.
@keyframes square {
0% { top: 0; left: 0; }
25% { top: 0; left: 150px; }
50% { top: 150px; left: 150px; }
75% { top: 150px; left: 0; }
100% { top: 0; left: 0; }
}
h1 {
position: absolute;
animation-iteration-count: infinite;
animation-duration: 3s;
animation-name: square;
white-space: nowrap;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<h1 id="heading">Hello World!</h1>
Upvotes: 2
Reputation: 3614
You can change the function to:
var moveDown = function () {
$("#heading").offset({top:offsetTop});
offsetTop++;
if(offsetTop > 200) {
offsetTop = 200;
}
};
That should give you your desired effect.
Upvotes: 0