PDA

View Full Version : Callback not working - jQuery



tonybabb
01-31-2015, 12:40 PM
Good morning,

I'm setting up a webpage which will have a text box float across the page from one side to the other and when it disappears it should float across again. The problem I'm having is that it only floats across once and doesn't appear again.

I must be missing something blindingly obvious but I just can't see it after a couple of hours of trying everything I could think of. I've set up a speeded up version on jsfiddle here http://jsfiddle.net/tonybabb/97rm8rkg/.

Once I get this working my next task will be to make the moving box appear at random positions on either the left or right side of the page and float to the other side of the page. The box will contain a randomly selected paragraph, which I was thinking could be held in a js array, there will be about 50 paragraphs to choose from. Is jQuery the right tool to use for this or should I be doing it some other way?

I'd really appreciate some direction on this.

Thank you,

Tony Babb

molendijk
01-31-2015, 04:28 PM
Your script doesn't tell the element to float back once it has reached the right side of the page. Here's a possible solution:


<!doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>

<title>Move it</title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<style>
.to-move {
width: 400px;
height:70px;
left: -400px;
top:100px;
position:absolute;
opacity: 0.6;
}
.link-spanner{
position:absolute;
width:100%;
height:100%;
top:0;
left: 0;
z-index: 1;
}
</style>


<script>
function move_it()
{
if($('.to-move').css({left: '-400px'}))
{$('.to-move').animate({left: '100%', top: '500px'}, 10000)}
if($('.to-move').css({left: '100%'}))
{$('.to-move').animate({left: '-400px', top: '100px'}, 10000)}
}

$(document).ready(function(){
move_it()
setInterval("move_it()",500)
});
</script>

</head>

<body>

<div class="to-move">
<h3>Some text, click on text to go to Sales page</h3>
<a href="store.php"><span class="link-spanner"></span></a>
</div>

</body>

</html>

tonybabb
02-01-2015, 12:28 PM
Aaah, of course, I should have thought of that, thank you. When I tried it in the jsfiddle I found it worked but only forward and back once. After digging around a bit I found that replacing
setInterval("move_it()",500)
with
setInterval(move_it,500) fixed the problem.

Thanks again for your time.

Tony