<!DOCTYPE html>
<html>
<head>
<title>MouseMove</title>
</head>
<body>
<h1 id='heading'> Try and click me 10 times.</h1>
<script src='https://code.jquery.com/jquery-2.1.0.js'></script>
<script>
var leftOffset = 0;
var topOffset = (200, 0);
var rightOffset = 200;
var toTheTop = (0, 200);
var counter = 10;
var congrats = "Congrats you Win!"
var moveHeading = function() {
$('#heading').offset({
top:0,
left: leftOffset
});
leftOffset++;
if (leftOffset > 200) {
$('#heading').offset({
top: topOffset,
left: 200
});
topOffset++;
}
if (topOffset > 200) {
$('#heading').offset({
left:rightOffset,
top: 200
});
rightOffset--
};
if (rightOffset < 0) {
$('#heading').offset({
left:(200,0),
top:toTheTop
});
toTheTop--;
}
if (toTheTop < 0){
leftOffset = 0,
topOffset = (200, 0),
rightOffset = 200,
toTheTop= (200);
}
};
var ghost = function () {
$("#heading").text(counter)
counter--;
}
var nuts = function () {
if (counter < 8)
{ clearInterval(cc) }
if (counter === 9){
var cc = setInterval(moveHeading,10)
}
if (counter < 8)
{ clearInterval(cc) }
}
var x = setTimeout(nuts,20)
$("#heading").click(ghost)
$("#heading").click(moveHeading)
$("#heading").click(nuts)
</script>
</body>
</html>
I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.
Instead of using setInterval
you can set a global variable time
and use setTimeout(...,time)
. You can then lower time
everytime nuts()
gets run. You will also have to add setTimeout(..., time) inside your
moveHeading`.
Hey thanks man. It looks much better.
Okay so I did what you suggested and it does work. However The problem I am having now is stopping it. I know its clearTimeout. However because the timeout function is inside move heading isn’t it just repeating itself. How do I make it stop and display congrats after the counter reaches 1. Thanks for you help so far.this is challenge is from Javascript for kids. page 166
You could do something like this (in moveHeading
):
if(counter > 1){
setTimeout(moveHeading, time);
}
Oh my god, Thank you so much. I can finally move on. Thank you so much. Happy fourth of July. I can’t believe it was that easy. but in hind sight /////it totally makes sense.