Get Position of an element constantly changing - javascript

I was trying to make a kind of background in which some clouds were moving, but after I got the clouds moving I found that I should either make them stop and return when reaching the browser's max-width, or make them disappear. I was trying to get their position but I can't manage to get all the positions dynamically. Right now (for the sake of simplicity) I'm only using 1 cloud to test and I do this:
$(function () {
var p = $('.clouds').position();
var w = $("#sky").width();
while (p < w);
$('.clouds', this).stop().animate({ left: "+=50000px" }, { queue: false, duration: 90000 });
});
the thing is, that position isn't dynamically refreshed, it sticks with the first one it gets and I have tried to move it inside the while loop but it didn't work...so I'm kinda stuck at the moment...anyone has an idea of how I can achieve this? The image of the cloud is originally set at top:0 left:0

I think this code will be useful to u. Try this out!
$('.clouds').animate({ top: 0 }, { queue: false, duration: 90000 });
setInterval(function () {
if ($(".clouds").position().top == 0) alert("Rain");
}, 5000);
for every 5 seconds, it will check for the position of a "cloud" class if it is zero it will give alert!
for multiple clouds u can use below code
setInterval(function () {
if ($(".clouds").position().top == 0) {
$(".clouds").each(function () {
if ($(this).position().top == 0) $(this).remove();
});
}
}, 1000)

Is the code you've posted a direct copy of what you're using? If so, then the call to animate isn't included in the while loop since it's cut short by the semi-colon. Try to use curly braces; it makes it much easier to maintain and look at. :)
while(p < w) {
$('.clouds',this).stop().animate({left:"+=50000px"},{queue:false, duration:90000});
}
Also, I don't think that loop will ever complete. Neither of those variable's values are changing during iteration so it's never-ending. In order for it to work you'll need to modify (update) the 'p' variable within the loop, on every iteration.
EDIT: Actually, scratch that, the loop won't even begin because elem.position() returns an object, not a number (NaN). To make it work you'll need elem.position().left.

why not use a looping background image and modify the background-position css property?
edit: I don't know if there's a jquery plugin to do this automatically, but it should be easy enough in old fashioned javascript with setInterval and modulus.
for example, your background image is 400 pixels wide,
the css would be:
body {
background: transparent url(yourbackground.png) repeat-x scroll 0 0;
}
and javascript would be:
var BGPosition = 0;
var resetSize=400;
function scrollBodyBG() {
BGPosition = ++BGPosition % resetSize;
$('body').css("background-position", (-1 * BGPosition) + "px 0px");
}
var si = setInterval(scrollBodyBG,100)
Edit: Tested and working (without jquery) as
var BGPosition = 0;
var resetSize=400;
function scrollBodyBG() {
BGPosition = ++BGPosition % resetSize;
document.body.style.backgroundPosition = (-1 * BGPosition) + "px 0px";
}
document.addEventListener("DOMContentLoaded",function() { setInterval(scrollBodyBG,100);},false);
obviously this would need to change for IE event listener support

How about:
while($('.clouds').position().left < $("#sky").width())
{
// do stuff
}

The only way to do this reliably is to listen property changes on DOM elements, using mutation events DOMAttrModified (for ex.) and the proprietary "onpropertychange" on IE.
Someone ported this to Jquery, here's the article.
http://www.west-wind.com/Weblog/posts/453942.aspx

Put it all in a function, let's say moveCloud()
Then use the callback of the animate position and call that function.
At the beginning of the function check the position of the cloud:
-If it is 0 move it to the right until it reaches maxwidth
-If it is the maxwidth, move it to the left until it reaches 0
Once the animation is done, the callback executes and calls again the function, which will move the cloud to the other side of the screen.

Related

Counting up using jquery

So far I have a little script that detects the scroll top position and at a set level I want it to trigger a jquery counter. So far I have an array with the maximum number inside var = eightyS = [3]; then there is..
if (y > 630) {
$('.targetS').each(function() {
//counter
delay(1000);
});
} else {
return false;
}
Now I've made something similar in C++ years ago (couldn't do it now with a gun to my head) so I followed a similar logic. But this is where I'm stuck. The idea behind this function is that it will do a read out on screen of 0 then 1 then 2 then 3. Any help is greatly appreciated
You could use a setInterval() which executes a function ever second such as below:
var count = 0;
var interval = setInterval(function(){
count++;
$('#counter').text(count);
}, 1000);
I've created a quick JSFiddle
You should be able to wrap this in to your code fairly easily. You may also want to use clearInterval(interval) to stop the function executing when you scroll back up the page; or when you get in to your else block, which would have the same effect. I've added a clearInterval() example to the JSFiddle on click of the stop link. You'll need to make sure the interval variable is in scope when clearing it.

create billboard slideshow with jquery

i saw a tutorial in tympanus and i did some changes to look more like a billboard but something is wrong and i don't know what it is! and it's really makes me crazy that where the hell is problem!
the first time that you run it's exactly that i want but when time passes it's getting ugly!i did this modification:
$(function() {
$('#ad_1 > img').each(function(i,e){
rotate($(this),500,3000,i);
});
function rotate(elem1,speed,timeout,i){
elem1.animate({'marginLeft':'18px','width':'0px'},speed,function(){
var other;
if(elem1.parent().attr('id') == 'ad_1')
other = $('#ad_2').children('img').eq(i);
else
other = $('#ad_1').children('img').eq(i);
other.animate({'marginLeft':'0px','width':'35px'},speed,function(){
var f = function() { rotate(other,speed,timeout,i) };
setTimeout(f,timeout+i*100);
});
});
}});
all the rest is just like the tympanus
thank you!!
In the future it will be helpful for you to describe what you are hoping to achieve rather than leaving it to the people of whom you are asking for help to figure it out for themselves. With some fiddling, I determined that what you want is, instead of each panel animating at the same time, a slight delay of the animations from left to right, so that each panel begins animating after its left neighbor has begun its animation.
You attempted to achieve this by adding an increment to the duration between a panel's rotations. The increment, computed as a function of the panel's index, is larger for higher indexes. The problem with this approach is that each panel spends a different duration of time in its display state - so as time goes on, the whole image becomes increasingly mangled.
The panels all need to have the same display duration, so revert your change to the setTimeout.
setTimeout(f, timeout);
What you actually want to do is to delay when each panel starts rotating. This can be achieved by adding a setTimeout in the each handler that initiates the rotations:
$('#ad_1 > img').each(function (i, e) {
setTimeout($.proxy(function () {
rotate($(this), 500, 7000, i);
}, this), (i * 100));
});
You will notice that I have increased the timeout value passed to rotate because more time will be required to accommodate the sequential animations.
I would also recommend that you put some effort into better formatting your code. Your sample, due to poor indentation, lack of spacing, and omitted curly braces, makes reading it a chore.
It's hard to tell without looking at the rest of the code, but your else statement is missing brackets. I think you meant to do this:
$(function() {
$('#ad_1 > img').each(function(i,e){
rotate($(this),500,3000,i);
});
function rotate(elem1,speed,timeout,i){
elem1.animate({'marginLeft':'18px','width':'0px'},speed,function(){
var other;
if(elem1.parent().attr('id') == 'ad_1') {
other = $('#ad_2').children('img').eq(i);
} else {
other = $('#ad_1').children('img').eq(i);
other.animate({'marginLeft':'0px','width':'35px'},speed,function(){
var f = function() { rotate(other,speed,timeout,i) };
setTimeout(f,timeout+i*100);
});
}
});
}});
*edit: Did you remember to include jQuery?
<script src="jquery-1.3.2.js" type="text/javascript"></script>

Sprite Animation using a for loop

I am trying to create an animation using a sprite sheet and a for loop to manipulate the background position until it has reached the total number or rows in the sheet. Ideally a reset back to the initial position would be practical, but I cannot even get the animation itself to trigger...
With the current function, no errors occur and the background position in my CSS does not change. I even recorded using Chrome DevTools Timeline and there was nothing either then everything related to my page loading. I have also tried using "background-position-y" as well as a simpler value rather then the math I currently have in place.
This is my function:
$(document).load(function() {
var $height= 324;
var $rows= 34;
for(var i=0; i<$rows; i++){
setTimeout(function() {
$('#selector').css("background-position", "0px ", "0" - ($height*i) + "px");
}, 10);
}
});
I hate to ask a question that is similar to previous issues, but I cannot seem to find another individual attempting sprite sheet animation with a for loop, so I suppose it is it's own problem.
p.s. I didn't include a snippet of my HTML and CSS because it is pretty standard and I don't see how that could be the problem. That being said, I am all ears to any potential thoughts!
I am completely revamping my answer
This issue is that the for() loop is not affected by the setTimeout so the function needs to be written on our own terms, not with a loop
Working Fiddle
Here it is..
var $height= 5;
var $rows= 25;
var i = 1; // Starting Point
(function animateMe(i){
if(i<=$rows){ // Test if var i is less than or equal to number of rows
var newHeight = 0-($height*i)+"px"; // Creat New Height Position
console.log(i); //Testing Purposes - You can Delete
$('#selector').css({"background-position": "0px "+ newHeight}); // Set New Position
i++; // Increment by 1 (For Loop Replacement)
setTimeout(function(){animateMe(i)}, 1000); // Wait 1 Second then Trigger Function
};
})(0);
Here is your solution
First Change
$(document).load() To $(document).ready()
And Change .css Syntex as
$('#selector').css("background-position",'0px '+(0 - ($height*i))+'px');
Here is fiddle Check it ihad implemented it on my recent project http://jsfiddle.net/krunalp1993/7HSFH/
Hope it helps you :)

how to stop moving background-image position

I've background image and by using small javascript code, it moves from right to left.
HTML code
<div id="clouds_image"></div>
Javascript code
var g=0;
var speed=30;
function rollClouds() {
document.getElementById('clouds_image').style.backgroundPosition=g+'px 0';
g--;
scroller=setTimeout(function(){rollClouds()},speed);
}
window.addEventListener?
window.addEventListener('load',rollClouds,false):
window.attachEvent('onload',rollClouds);
But i've noticed that, with time my PC CPU memory usage increased ! causing overload on my pc and if i disabled that javascript code, it back to normal.
My question
so i think i need to modify this javascript code that it not keep working forever, i mean, i want to make it to repeat that action only 5 times then stop , maybe i need to define value of g but i'm not good in javascript so any help ~ Thanks.
You need to use a variable to count how many times that function was executed, and use setInterval instead of setTimeout: See example
http://jsfiddle.net/EQDjx/206/ (my counter start from 100 and goes down to 0)
for a more nice effect i recomand you to use jquery. See animate function
http://api.jquery.com/animate/
var g = 1000;
var speed=300;
var counter = 100;
function rollClouds() {
document.getElementById('clouds_image').style.backgroundPosition=g+'px 0';
g--;
if (counter < 1) clearInterval(interval);
}
interval = setInterval(function(){rollClouds()}, speed)
A cleaner solution might be to use jQuery to move the background:
function moveClouds() {
$("#clouds_image").css({left:"-2000px"});
$("#clouds_image").animate({left:"2000px"},10000);
}
Then you might set an interval to trigger it every x milliseconds.
setInterval(moveClouds,10000)
JSFiddle is here: http://jsfiddle.net/qXpVX/

Continuous element movement with jQuery

I'm creating a game with jQuery, and I want my character to move automatically until it hits a boundary. Here is my movement code in right direction:
if (e.keyCode === 39 && (p1_left < 784)) {
$('#p1').rotate(0);
setInterval ( function() {
$('#p1').animate( { left: "+=16px", }, 50); }, 50);
}
This moves my character indefinetely to the right, and I haven't figured out myself how to create a stopper.
EDIT: Updated code snippet, Added jsfiddle http://jsfiddle.net/BjCeq/
You never actually increase pl_left so the loop will just run forever:
while (p1_left <= 784) {
pl_left+=16;
$('#p1').css('left', p1_left);
}
However, this is not going to animate the movement of your character, it will appear to just jump to the end point. For this reason it is kind of pointless to loop. What you probably want is either to use setTimeout to move every second one position or something. Or, you could use animate with a callback function:
function moveLeft(theID){
$(theIE).animate({...},1000, function(){
if(/* keep moving */){
move_left(theID);
}
}
}
What you need is code that's continually called. Your code, as you've written it, is called once, and it performs all of its DOM manipulation at once. What you need is a setInterval or a setTimeout to trigger your code to call itself a certain number of milliseconds in the future, incrementing the css property each time. The easiest way to accomplish this is to simply use jQuery.animate, which runs those methods internally.
var $p1 = $('#p1');
if (e.keyCode === 39 && (p1_left < 784)) {
$p1.rotate(0);
$p1.animate({ 'left' : 784 });
}
Check out the jQuery animate docs for more information, including how to set options and run a callback function with each frame of the animation: http://api.jquery.com/animate/.

Categories