I'm trying to run an animation by altering the background-position of an image within a div. I'm using setTimeout to recall the function and continuously decrement the image position (so it appears to be animated). I've tested the the variables and setTimeout they seem to be working fine. The image however is not moving at all.
How can i amend the code to enable this animation to run ?
var decrement = 0;
function runningRobot() {
var robotCont = document.getElementById('robotCont');
if(decrement < -660) {
decrement = 0;
}
robotCont.style.backgroundPositon = decrement+ 'px' +' '+ 0 + 'px';
decrement -= 110;
timer = setTimeout(runningRobot,500);
}
runningRobot();
You misspelled backgroundPosition:
robotCont.style.backgroundPosition = decrement + 'px' + ' ' + 0 + 'px';
I also don't know if you'll need the position left setting. I think 0 is the default, and since it comes second to top, it can be omitted, right?
robotCont.style.backgroundPosition = decrement + 'px';
To improve to axiom82's answer, you can also reduce your code by putting the amount of seperate parts you have together. You'd change it from:
robotCont.style.backgroundPosition = decrement + 'px' + ' ' + 0 + 'px';
to:
robotCont.style.backgroundPosition = decrement + 'px 0px';
as was also suggested by antyrat in the comments.
And to correct axiom82, it is not allowed to omit the second 0px, as can be seen on the MDN docs, which says the background-position style needs "a list, each item consisting of two keywords". This means both the x and the y need to be specified, and the second value can't be omitted.
Related
I have this code to allow me to place a random image next to the user's cursor using javascript and styled using CSS. I would like images to fall down off the page after a few seconds, my first thought was to animate position but apparently that's not possible?
How could I achieve this? Here is my javascript and CSS code
Javascript
<script>
var myPix = new Array("/img/portfolio/30day.jpg", "/img/portfolio/animationposter.jpg","/img/portfolio/beetle.jpg","/img/portfolio/board.jpg","/img/portfolio/cyanotype.jpg","/img/portfolio/dissent.jpg")
document.addEventListener("click", showCoords);
function showCoords(event)
{
var randomNum = Math.floor(Math.random() * myPix.length);
var yourImage = document.createElement("img");
yourImage.src = myPix[randomNum] ;
yourImage.classList.add("mystyle");
yourImage.style.cssText = " width:360px;height:auto;position:fixed;top:" + event.clientY + "px;left:" + event.clientX + "px;";
document.body.appendChild(yourImage);
}
jQuery.fn.reverse = [].reverse;
</script>
CSS
.mystyle {
border-radius: 20px;
box-shadow: 0px 0px 10px 0 rgba(0, 0, 0, 0.1);
z-index: -2;
width: 360px;
height: auto;
position: fixed;
}
First create an images array so you can easily access all your images. Whenever you create an image, push it to the array:
var images = [];
function showCoords(event)
{
var randomNum = Math.floor(Math.random() * myPix.length);
var yourImage = document.createElement("img");
yourImage.src = myPix[randomNum] ;
yourImage.classList.add("mystyle");
yourImage.style.cssText = " width:360px;height:auto;position:fixed;top:" + event.clientY + "px;left:" + event.clientX + "px;";
images.push([yourImage,0,0]); // this line is where we add the image.
//In the same sub-array, put a number, 0, to store the image's age, and a velocity, 0, to make the physics look good. These will be used later.
document.body.appendChild(yourImage);
}
In order to animate your images, you need to set up some kind of animate loop and call it in a setInterval:
animate = function(){}
setInterval(animate,5); // choose whatever interval you want. Here, it is called every 5 milliseconds
Inside the animate function, we need to add the logic to change every image's position:
animate = function(){
for(image of images){ // loop over all elements of our array
image[1] += 1; //increase the age
if(image[1] > 400){ //if old enough, fall
image[2] += 0.1; //accelerate, tweak this value to change how strong gravity is
currentTop = parseFloat(image[0].style.top.replace("px","")); // get the current y position
currentTop += image[2]; //move
newTop = String(currentTop) + "px"; //change back to string
image[0].style.top = newTop; //set the attribute
if(newTop > document.documentElement.clientHeight){ //if off-screen, remove it
document.body.removeChild(image[0]);
images.splice(images.indexOf(image),1); //remove from array
}
}
}
}
Now you should be good to go. I tested this out in Chrome and it worked for the simple case where I just had one image on screen; hopefully I haven't made any typos writing it up here. To change the speed, either change the acceleration value or change the time in the setInterval. Hope this helps!
Edit: here is a working jsFiddle. I had to use spans instead of images because I don't have your exact image files, but everything else is the same.
I'm fairly new to jQuery , and I'm trying to scroll and image downwards. The code I'm using is successfully scrolling the image, but sideways, and that's not what I need.
This is the code I'm using
$(function(){
var y = 0;
setInterval(function(){
y -= 1;
$('.scroller').css('background-position', y + 'px 0');
}, 100);
})
If needed, I can provide the CSS and HTML, but those aren't the issue.
Probably because you are changing the X axis... (Read more about background-position or Cartesian coordinate system)
Try this:
$('.scroller').css('background-position', '0 ' + y + 'px');
I've spent a little time trying to figure this specific bit of Javascript out and why it seems to be so infuriating.
As it stands i currently have two functions. Which are shown as follows.
function startUpProc(id)
{
var log = window.document.getElementById(id);
log.style.transform = "rotate(0deg)";
var i = 10;
while ( i <= 360)
{
setTimeout('changeRotate(' + id + ',' + i + ')', 100);
i = i + 10;
}
}
function changeRotate(item, val)
{
item.style.transform = "rotate(" + val + "deg)";
item.style.webkitTransform = "rotate(" + val + "deg)";
item.style.mozTransform = "rotate(" + val + "deg)";
//alert(item.style.transform);
}
Relatively simple bit of Javascript that rotates a HTML element, in this case it's an image, this code is called with the use of a body onLoad handler as follows :
<body onLoad="startUpProc('logo');">
My intention as it stands is to have the image spin 360 degrees once which is regulated with the use of my while loop.
Where my confusion lies is in the fact that despite the timeout being set for this to take a total of 3.6 seconds to complete, it doesn't seem to even work, and there is no error being thrown, hence the alert that i placed in the function in an attempt to see what was occurring.
The alert was triggered 36 times, and visually i could see the image rotating on the page.
I found the following SO Q&A, but to no avail, the answer just wasn't applicable for the specific event i am trying to create, as the image is being rotated no matter what browser i attempt the code on, the only difference being, it only rotates when there is an alert or something in there to stop the flow of code...
Rotating a div element
Unfortunately for me, all other answers i find, seem to reference the use of JQuery, which for the moment i would like to stay away from and learn to proficiently develop in JavaScript without the use of third party extensions and plugins.
The issue is with the fact that the loop initiates the rotation 36 times, and after 100ms the rotation happens 36 times with i being set to "360".
Try something like this:
var STEP = 10;
function startUpProc(id)
{
var log = window.document.getElementById(id);
// initialized to 0 in changeRotate
makeCircle(log, 0);
}
function makeCircle(item, targetAngle) {
changeRotate(item, targetAngle);
if (targetAngle < 360) {
setTimeout(function (){
makeCircle(item, targetAngle + STEP);
}, 100);
}
}
This ensures that each rotation starts after the last one has finished.
Proof that it works
Your code initiates 36 timeouts that all fire off at once, and end up rotating the element full 360 degrees, so you might not even notice the result.
You can either fire a new timeout when the old one stops:
function changeRotate(item, val)
{
item.style.transform = "rotate(" + val + "deg)";
item.style.webkitTransform = "rotate(" + val + "deg)";
item.style.mozTransform = "rotate(" + val + "deg)";
val += 10;
setTimeout(function () {
changeRotate(item, i);
}, 100);
}
changeRotate(document.getElementById('foo'), 0);
Or you can use setInterval, which will repeat the same action every specified amount of milliseconds http://www.w3schools.com/jsref/met_win_setinterval.asp
var val = 0;
function changeRotate(item)
{
item.style.transform = "rotate(" + val + "deg)";
item.style.webkitTransform = "rotate(" + val + "deg)";
item.style.mozTransform = "rotate(" + val + "deg)";
val += 10;
}
setInterval(function () {
changeRotate(document.getElementById('foo'), 0);
}, 100);
Ok so i have this triangle div and when i click it, it only rotates 180deg. Ok so far so good but if i click it again it stays the same here is my code.
$('.Triangle').click(function()
{
var Location = $('.Triangle').offset().left;
$('#Account').css({"left" : Location});
$('#Account').slideToggle('fast');
$('.Triangle').css({"transform" : "rotate(180deg)"});
});
Transforms don't work that way (i.e. you can't apply it twice). You have to keep track of state:
$(".Triangle").on('click', function () {
if ($(this).data('flipped') {
$(this).data('flipped', false).css('transform', 'rotate(0deg)');
}
The 'transform' style sets the rotation of the element from it's original position. When you click it the first time, it rotates the element from 0deg to 180deg. When you click it again, it changes the rotation from 180deg to 180deg.
You need to keep a counter for the number of clicks and multiply that by your rate of rotation. Something like this should do the trick:
var count = 1;
$('.Triangle').click(function() {
var Location = $('.Triangle').offset().left;
$('#Account').css({"left" : Location});
$('#Account').slideToggle('fast');
$('.Triangle').css({"transform" : "rotate(" + (180 * count++) + "deg)"});
});`
var i = 0;
$('.Triangle').click(function() {
i++;
var Location = $('.Triangle').offset().left;
$('#Account').css({"left" : Location});
$('#Account').slideToggle('fast');
$('.Triangle').css({"transform" : "rotate(" + (i % 2 ? 0 : 180 + "deg)"});
});
I have an element of an arbitrary type. I'd like to create another element, of either the same or a different type that has the same position and size as the first. The element may or may not be positioned.
For example, I might start with a <select> with a certain size, possibly dependent on its contents, i.e. width/height auto. I want to create a new <div> that appears at the same position and has the same size.
I've tried copying the element's float, clear, position, width, height, margins and padding, but this is a little cumbersome. Also, while it works in Firefox, I'm running into some strange issues when testing on Webkit. Before I spend much more time figuring it out, I'd like to know whether there's some jQuery or jQuery UI functionality that already takes care of what I want to do.
I realize that this question is similar to an existing one, but mine has the important distinction of needing to work with elements of differing types, which precludes clone as a solution.
This is NOT efficient, tested, or complete. And it is probably similar to what you are already doing. But I thought I'd post it anyways:
var positioningProps = ["float","position","width","height","left","top","marginLeft","marginTop","paddingLeft","paddingTop"];
var select = $("#mySelect");
var div = $("<div>").hide().before(select);
// don't do this kind of loop in production code
// http://www.vervestudios.co/jsbench/
for(var i in positioningProps){
div.css(positioningProps[i], select.css(positioningProps[i])||"");
}
select.hide();
How about just copying the element's offset and absolutely positioning it on the page?
Say you had an input element somewhere on the page with dimensions 100x25px.
<input type="text" id="firstname" style="width: 100px; height: 20px" />
And you wanted to place a div right on top of it (and hide the input).
// Store the input in a variable
var $firstname = $("#firstname");
// Create a new div and assign the width/height/top/left properties of the input
var $newdiv = $("<div />").css({
'width': $firstname.width(),
'height': $firstname.height(),
'position': 'absolute',
'top': $firstname.offset().top,
'left': $firstname.offset().left
});
// Add the div to the body
$(body).append($newdiv);
You can find out an elements bounds using this plugin to jQuery. The it would be just a simple matter of setting whatever properties you are interested in to the other object.
http://code.google.com/p/jquery-ui/source/browse/branches/labs/powella/coverslide/res/js/jquery/jquery.bounds.js?r=2698
/*
* jQuery.bounds
* author: Andrew Powell
*/
(function($){
$.fn['bounds'] = function()
{
var t = this, e = t[0];
if (!e) return;
var offset = t.offset(), pos = { width:e.offsetWidth, height:e.offsetHeight, left: 0, top: 0, right: 0, bottom: 0, x: 0, y: 0 };
pos.left = offset.left;
pos.top = offset.top;
//right and bottom
pos.right = (pos.left + pos.width);
pos.bottom = (pos.top + pos.height);
pos.x = pos.left;
pos.y = pos.top;
pos.inner = {width: t.width(), height: t.height()};
$.extend(pos, {toString: function(){ var t = this; return 'x: ' + t.x + ' y: ' + t.y + ' width: ' + t.width + ' height: ' + t.height + ' right: ' + t.right + ' bottom: ' + t.bottom; }});
return pos;
};
})(jQuery);