Randomize background img with JS - javascript

I have working code, that randomly changes background of the body with my gif's.
var totalCount = 11;
function ChangeIt() {
var num = Math.ceil( Math.random() * totalCount );
document.body.background = '/static/img/'+num+'.gif';
document.body.style.backgroundRepeat = "repeat";
}
window.onload = ChangeIt;
Now I want to use it with another HTML element, one of the div's, for example. Changing document.body.background to document.getElementById('id').background doesn't work. How should I change the code?

document.body.background mostly worked for body background but not other html elements.So used this document.getElementById('id').style.backgroundImage = "url(..)";
var totalCount = 11;
function ChangeIt() {
var divs =document.getElementById('id');
var num = Math.ceil( Math.random() * totalCount );
divs.style.backgroundImage = 'url(/static/img/'+num+'.gif)';
divs.style.backgroundRepeat = "repeat";
divs.style.height = "300px"; //testing
}
window.onload = ChangeIt;

Have you tried this?
document.getElementById('id').style.backgroundImage = "url('/static/img/" + num + ".gif')";
Also, the RNG with Math.ceil() means that images are based on 1 not on 0:
1.gif
2.gif
...
11.gif
If this is not the case use Math.floor():
0.gif
1.gif
...
10.gif
Depending on what the element is, you may need to set its dimensions (width and height). This is an example HTML element:
<div id="imagediv" style="width: 320px; height: 640px; background-repeat: repeat;"></div>
This the resulting code:
var totalCount = 11;
window.onload = function () {
var num, node;
num = Math.ceil(Math.random() * totalCount);
node = document.getElementById("imagediv");
node.style.backgroundImage = "url('/static/img/" + num + ".gif')";
};

this should be the correct syntax:
document.getElementById('id').style.backgroundImage = "url('img_tree.png')";

Related

Changing the background color of an element sets websites text to the color

Im trying to make a javascript bookmark using The code I wrote. It's supposed to add an element (in this case it adds a div. The div is as large as the size of innerHeight and innerWidth. The height shrinks by a few pixels every 250 milliseconds. It works on CodePen, but when I try it on another website, it changes the entire HTML of the page to "white" (which is the background color of the added element). Here is the code:
var falseLoaderContainer = document.getElementsByTagName("html")[0];
falseLoaderContainer.innerHTML += `<div id="falseLoader"></div>`;
var falseLoader = document.getElementById("falseLoader");
falseLoader.style.position = `absolute`;
falseLoader.style.width = `${window.innerWidth}px`;
falseLoader.style.height = `${window.innerHeight}px`;
falseLoader.style.bottom = `0px`;
falseLoader.style.left = `0px`;
falseLoader.style.backgroundColor = `white`;
var falseLoaderHeight = falseLoader.style.height.replace(/px/g, "");
var updateFalseLoader = setInterval(function () {
falseLoaderHeight *= 1;
falseLoaderHeight -= Math.ceil(Math.random() * 4);
falseLoader.style.height = falseLoaderHeight + "px";
if (falseLoaderHeight <= 0) {
clearInterval(updateFalseLoader);
}
}, 250);
Try:
var element = document.getElementById("id");
element.setAttribute("style", "background-color: COLOR;");
or:
var element = document.getElementBYId("id");
element.style = "background-color: COLOR;");
Hope this helps!

Javascript help, Trying to animate two different sprites at same time

I need some javascript help. I am trying to set up two sprite animations with different frame rates in two separate div.
Here is a fiddle I started and i am very much stuck.
How do I combine the two div IDs into one statement? OR Should I be using ClassName in the statement to run on both divs?
http://jsfiddle.net/akwilinski/3t7d6qbL/1/
<div id="animate" class="animation"></div>
<div id="animate2" class="animation2"></div>
onload = function startAnimation() {
var frameHeight = 400;
var frames = 27;
var frame = 0;
var div = document.getElementById("animate");
setInterval(function () {
var frameOffset = (++frame % frames) * -frameHeight;
div.style.backgroundPosition = "0px " + frameOffset + "px";
}, 100);
}
Thank you for any assistance!
Simplest way to do this using the method you have already started using is to define 2 new variables, 1 for the second div and one for the second frame count. Then you can just add the call to your function.
Updated js:
onload = function startAnimation() {
var frameHeight = 400;
var frames = 27;
var frame = 0;
var div = document.getElementById("animate");
var div2 = document.getElementById("animate2");
setInterval(function () {
var frameOffset = (++frame % frames) * -frameHeight;
var frameOffset2 = (++frame % frames) * -frameHeight - 10;
div.style.backgroundPosition = "0px " + frameOffset + "px";
div2.style.backgroundPosition = "0px " + frameOffset + "px";
}, 100);
}
Fiddle
http://jsfiddle.net/f4v1vy7x/5/
I made a Can object to store the configuration for each can (so you can have different frameHeights, frames and frameRates.
I used window.requestAnimationFrame because it's far more efficient than setInterval. On each available frame I check whether it's time to animate based on each Can's set frame rate:
var Can = function( selector, frameHeight, frames, frameRate )
{
this.domCan = document.getElementById( selector );
this.frameHeight = frameHeight;
this.frames = frames;
this.frameRate = frameRate;
this.frame = 0;
};
onload = function startAnimation() {
var can1 = new Can( 'animate', 400, 27, 20 );
var can2 = new Can( 'animate2', 400, 27, 100 );
var cans = [ can1, can2 ];
window.requestAnimationFrame( function() {
can1.start = can2.start = new Date();
animate( cans );
} );
};
var animate = function( cans ) {
for( var i = 0; i < cans.length; i++ ) {
var now = new Date();
var can = cans[i];
if( now - can.start >= 1000 / can.frameRate ) {
can.start = now;
var frameOffset = (++can.frame % can.frames) * -can.frameHeight;
can.domCan.style.backgroundPosition = "0px " + frameOffset + "px";
}
}
window.requestAnimationFrame( function() {
animate( cans );
} );
}
You could do something like this:
var div = document.getElementById("animate");
var div2 = document.getElementById("animate2");
function anim(div) {
setInterval(function () {
var frameOffset = (++frame % frames) * -frameHeight;
div.style.backgroundPosition = "0px " + frameOffset + "px";
}, 100);
}
anim(div);
anim(div2);
You could then pass in additional parameters like frameHeight, frame, and frames to further customize each animation.

Modifying a simple jquery game

I am trying to modify this game, right now it shows 9 images at random positions and the user has to click on them and when it reaches 10 clicks the game ends. I want to appear only one image. I will share the original function and the function I have modified it.
Original
function createImages(){
var myarray= ["img/img1.gif","img/img2.gif","img/img3.png",
"img/img4.gif","img/img5.gif","img/img6.gif",
"img/img7.gif","img/img8.png", "img/img9.jpg"];
var count=0;
var div;
for (var i = 0; i < 9; i++) {
var randPos = 0 + Math.floor(Math.random() * 500);
this.img = document.createElement("img");
div = document.createElement("div");
$("div").attr("id","div"+i);
var randNew = 0 + Math.floor(Math.random() * (5));
var rand = 0 + Math.floor(Math.random() * (9-count));
this.img.src = myarray[rand];
$('#div'+i).css("left", randPosition());
$('#div'+i).css("right", randPosition());
$('#div'+i).css("top", randPosition());
$('#div'+i).css("bottom",randPosition());
$('#div'+i).css("position","relative");
$('#div'+i).show();
div.appendChild(this.img);
$("body").prepend(div);
myarray.splice(rand,1);
count++;
}
}
After I modified it
function createImages(){
var count=0;
var div;
for (var i = 0; i < 9; i++) {
var randPos = 0 + Math.floor(Math.random() * 500);
this.img = document.createElement("img");
div = document.createElement("div");
$("div").attr("id","div");
var randNew = 0 + Math.floor(Math.random() * (5));
var rand = 0 + Math.floor(Math.random() * (9-count));
this.img.src = "img/img1.gif";
$('#div').css("left", randPosition());
$('#div').css("right", randPosition());
$('#div').css("top", randPosition());
$('#div').css("bottom",randPosition());
$('#div').css("position","relative");
$('#div').show();
div.appendChild(this.img);
$("body").prepend(div);
count++;
}
}
The problem is that now it appears the same image 10 times, I want it to appear only once and then disappear and appear again. Can anyone help me fix this issue.
If it's not to much to ask I would like to put this image inside a div so it wouldn't appear all over the page.
function randPosition() {
return 0 + Math.floor(Math.random() * 500);
}
In createImages() function you have a loop that adds the image 10 times:
for (var i = 0; i < 9; i++) {
...
}
Remove it, and it'll do it only once. Also you can simplify the code removing some random variables that are not used.
Further, this two sentences aren't correct. The first one creates a div in a variable named also div. The second is selector for all div elements, you are not referencing the new created one as I think you expect.
div = document.createElement("div");
$("div").attr("id","div");
You should create a jQuery object with the new created div to work with it:
var div = document.createElement("div");
$div = $(div); // << Create jQuery object wrapping the new div
$div.css("left", randPosition());
Edited function:
function createImages(){
var div = document.createElement("div");
$div = $(div);
$div.css("left", randPosition());
$div.css("right", randPosition());
$div.css("top", randPosition());
$div.css("bottom",randPosition());
$div.css("position","relative");
$div.show();
var img = document.createElement("img");
img.src = "http://dummyimage.com/25x25/4F4/000.png";
div.appendChild(img);
$("body").prepend(div);
}
EDIT: I've built a JSFiddle for you so you can play with it: http://jsfiddle.net/6aLh9qam/3/

Jquery function should also work with other elements

I'm trying to make this function working multiple times:
Currently works only with the h1 tag
how can I make it working for the <div class="logo"> as well? I don't want to repeat the function, I need a way to make the function working for various elements.
demo: http://jsfiddle.net/33Ec8/4/
JS:
// Get the divs that should change
function displayThese() {
var $heading = $('h1');
var h1top = $heading.position().top;
var h1bottom = h1top + $heading.height();
var h1left = $heading.position().left;
var h1right = h1top + $heading.width();
var divs = $('li').filter(function () {
var $e = $(this);
var top = $e.position().top;
var bottom = top + $e.height();
var left = $e.position().left;
var right = left + $e.width();
return top > h1bottom || bottom < h1top || left > h1right || right < h1left;
});
return divs;
}
(function fadeInDiv() {
var divs = displayThese();
var elem = divs.eq(Math.floor(Math.random() * divs.length));
if (!elem.is(':visible')) {
elem.prev().remove();
elem.animate({
opacity: 1
}, Math.floor(Math.random() * 1000), fadeInDiv);
} else {
elem.animate({
opacity: (Math.random() * 1)
}, Math.floor(Math.random() * 1000), function () {
window.setTimeout(fadeInDiv);
});
}
})();
$(window).resize(function () {
// Get items that do not change
var divs = $('li').not(displayThese());
divs.css({
opacity: 0.3
});
});
Your question isn't stated very clearly, so I would strongly suggest describing what the code should do vs what it does.
That said, here is a half-blind attempt at answering what I think you want.
You could pass in the selector as a parameter to displayThese.
function displayThese(selectorString)
{
var $elementsUnderWhichNothingShouldFade = $(selectorString);
...
}
then when you call displayThese, you can pass in any complex selector you like.
var divsToChange = displayThese('h1, div.logo')
Of course, you would need to add extra logic to test whether the image elements were underneath any of the resulting $elementsUnderWhichNothingShouldFade (which is a list of elements).

Why is it looping through the 'else' in my if/else statement?

If you enable the alert(rand) at the bottom of my if/else statement, you will notice that when ran, it will constantly loop over the else section of my if/else statement. It's probably a simple fix, but I can't seem to figure it out. I had it working in the earlier stages of development but can't seem to figure it out now.
I'll post the code below, but it's probably easier to look at my jsfiddle, here: http://jsfiddle.net/zAPsY/7/ Thanks.
$(document).ready(function(){
//You can edit the following file paths to change images in selection
var img1 = '<img src="images/luke.jpg">';
var img2 = '<img src="images/luke.jpg">';
var img3 = '<img src="images/luke.jpg">';
var img4 = '<img src="images/luke.jpg">';
var img5 = '<img src="images/luke.jpg">';
var img6 = '<img src="images/luke.jpg">';
var all = img1 + img2 + img3 + img4 + img5 + img6;
//Rotation
var speed = 0.00;
var radius = 80;
var count = 0;
$("#run").bind("click",runButtonClick);
function rotate()
{
var centerx = $(document).width()/2;
var centery = $(document).height()/2;
var num_items = $("#container > img").length;
$("#container > img").each(function(){
var angle = count * (Math.PI/180);
var newx = centerx + Math.cos(angle)*radius - $(this).width()/2;
var newy = centery + Math.sin(angle)*radius - $(this).height()/2;
$(this).css("left",newx+"px").css("top",newy+"px");
count += 360/num_items + speed;
});
}
setInterval(rotate,100/1000);
//Append elements to container
$("#appendall").click(function(){$('#container').append(all);});
$('#append').children().eq(2).click(function(){$('#container').append(img1);});
$('#append').children().eq(3).click(function(){$('#container').append(img2);});
$('#append').children().eq(4).click(function(){$('#container').append(img3);});
$('#append').children().eq(5).click(function(){$('#container').append(img4);});
$('#append').children().eq(6).click(function(){$('#container').append(img5);});
$('#append').children().eq(7).click(function(){$('#container').append(img6);});
//Refresh page
$("#reset").click(function(){location.reload();});
//IF speed is greater than 0 - ELSE add animation to div element
function runButtonClick() {
var maxcount = 0.40;
var incdec = 0.01;
setInterval(function(){counter();}, 100);
counter()
speed;
function counter()
{
if (maxcount >= 0.00)
{
maxcount = maxcount - incdec;
speed = speed + incdec;
//alert(speed)
//alert(maxcount)
}
else if (maxcount <= 0.00)
{
speed = 0.00;
//Find amount of div elements and add 1
var brewees = $('#container').children().length +=1;
//get a random number
var rand = (Math.floor(Math.random()*brewees));
var ap = '20px';
var ab = '#ddd';
var ad = 1000;
//match random number corrosponding child in div
$('#container').children().eq(parseFloat(rand))
.animate({padding: ap, background : ab}, {duration:ad});
alert(rand);
}
}
}
});
You let your maxcount drop below zero but still your function is being called every 100ms (due to your setInterval).
So you should clear that interval eventually by doing:
/* first */
var intervalID = setInterval(function(){counter();}, 100);
/* later */
clearInterval(intervalID);
You're calling the function at a rate of 10 times per second (setInterval). Eventually, the maxcount variable will drop below 0, causing the else condition to execute.
You should store the interval call in a variable, and use clearInterval at else, so that the function runs only once after else:
//Store a reference to the interval
var interval = setInterval(function(){counter();}, 100);
...
function counter(){
...
else if(..){
...
clearInterval(interval); //Clear the previously defined interval
}
...
Another note: In the code, speed; has no use. Either prefix it by var (var speed;), or remove it.

Categories

Resources