change background img each time by clicking link - javascript

<body>
<script language="JavaScript">
<!--
var backImage = new Array();
backImage[0] = "pics/img02.jpg";
backImage[1] = "pics/img03.jpg";
backImage[2] = "pics/img04.jpg";
backImage[3] = "pics/img05.jpg";
function changeBGImage(whichImage){
if (document.body){
document.body.background = backImage[whichImage];
backImage = backImage++;
}
}
//-->
</script>
Change
</body>
sorry, i don't get how i exactly should properly integrate code here -hopefully it still worked. what i want to do here: change the background (that works) than add plus one to the background counter so that the next time the link is clicked the next background shows (that doesn't work). it should be quite simple but i couldn't figure it out nevertheless...

Use a static counter that counts from 0 to 3.
var cnt = 0;
function changeBGImage(){
if (document.body){
document.body.background = backImage[cnt];
cnt = (cnt+1) % 4; // mod 4
}
}

There are a couple of issues in your code
backImage = backImage++;
Doesn't increment backImage as you expect. The syntax should be simply backImage++;
Also, to set the background image you need document.body.style.background or document.body.style.backgroundImage = url(...)
Edit
Over and above cycling through the backgrounds via the click handler, if you also need to set the initial background, try something like below, with the initial background set in window.onload.
jsFiddle here
var backImage = [];
var whichImage = 0;
backImage[0] = "http://dummyimage.com/100x100/000000/000000.png";
backImage[1] = "http://dummyimage.com/100x100/FF0000/000000.png";
backImage[2] = "http://dummyimage.com/100x100/00FF00/000000.png";
backImage[3] = "http://dummyimage.com/100x100/0000FF/000000.png";
function changeBGImage(reseedWhichImage){
// If caller has specified an exact index, then reseed to this
if (reseedWhichImage != undefined)
{
whichImage = reseedWhichImage;
}
if (document.body){
document.body.style.backgroundImage = "url(" + backImage[whichImage] + ")";
whichImage++;
if (whichImage >= 4){
whichImage = 0;
}
}
}
// During global load, set the initial background
window.onload = changeBGImage(2);
​

Related

How do I change only one image out of many onclick with appendChild?

I'm currently learning JavaScript at my university, so I apologize if my code is terrible. I'm new to it.
I'm having an issue only changing one image onclick using appendChild. What I want to happen is that if the person clicks on the image whose rng is <= 0.89, then only that image is changed to a different image. Every thing I've tried has changed all of the images whose rng was <=0.89.
Example: I click the first image (img1) which has rolled a number greater than 0.9. If (img2) has rolled the same (greater than 0.9), then it also changes. I'd only want img1 to change. Here is only some of my code as the whole thing is about 150 lines and I think this bit gets my point across somewhat well:
function myFunction() {
var rng=Math.random();
var rng2=Math.random();
if (rng <= 0.89){
var img1=document.createElement('img');
img1.src='card2.gif';
img1.id="bad1";
img1.onclick = goodbye;
document.getElementById('card').appendChild(img1);
}
if (rng2 <= 0.89){
var img2=document.createElement('img');
img2.src='card2.gif';
img2.onclick= goodbye;
img2.id="bad2";
document.getElementById('card2').appendChild(img2);
}
if (rng >= 0.9) {
var img1=document.createElement('img');
img1.src='card3.gif';
img1.id="good1";
img1.onclick = hello;
document.getElementById('card').appendChild(img1);
}
if (rng2 >= 0.9){
var img2=document.createElement('img');
img2.src='card3.gif';
img2.onclick= hello;
img2.id="good2";
document.getElementById('card2').appendChild(img2);
}
}
Like I said, every thing I've tried to only change the image that was clicked has changed all images whose rng is <=0.89. The answer's probably really obvious, but I'm new to this, like I said.
Based on the comments, the only change that your code needs is to make .onclick set to a function instead of a string. This way we also pass this the element reference to your functions goodbye and hello. You can also use this to read the element properties if you wanted to. If this is not what your looking for let us know.
img1.onclick = function(){goodbye(this)};
Script
function goodbye(e) {
e.src = 'https://www.youtube.com/yt/brand/media/image/YouTube-logo-full_color.png'
}
function hello(e) {
e.src = 'https://pbs.twimg.com/profile_images/767879603977191425/29zfZY6I.jpg'
}
function myFunction() {
var rng = Math.random();
var rng2 = Math.random();
if (rng <= 0.89) {
var img1 = document.createElement('img');
img1.src = 'card2.gif';
img1.id = "bad1";
img1.onclick = function () {
goodbye(this)
};
document.getElementById('card').appendChild(img1);
}
if (rng2 <= 0.89) {
var img2 = document.createElement('img');
img2.src = 'card2.gif';
img2.onclick = function () {
goodbye(this)
};
img2.id = "bad2";
document.getElementById('card2').appendChild(img2);
}
if (rng >= 0.9) {
var img1 = document.createElement('img');
img1.src = 'card3.gif';
img1.id = "good1";
img1.onclick = function () {
hello(this)
};
document.getElementById('card').appendChild(img1);
}
if (rng2 >= 0.9) {
var img2 = document.createElement('img');
img2.src = 'card3.gif';
img2.onclick = function () {
hello(this)
};
img2.id = "good2";
document.getElementById('card2').appendChild(img2);
}
}
jsfiddle if required

JavaScript: set background image with size and no-repeat from random image in folder

I am a javascript newbie...
I'm trying to write a function that grabs a random image from a directory and sets it as the background image of my banner div. I also need to set the size of the image and for it not to repeat. Here's what I've got so far, and it's not quite working.
What am I missing?
$(function() {
// some other scripts here
function bg() {
var imgCount = 3;
// image directory
var dir = 'http://local.statamic.com/_themes/img/';
// random the images
var randomCount = Math.round(Math.random() * (imgCount - 1)) + 1;
// array of images & file name
var images = new Array();
images[1] = '001.png',
images[2] = '002.png',
images[3] = '003.png',
document.getElementById('banner').style.backgroundImage = "url(' + dir + images[randomCount] + ')";
document.getElementById('banner').style.backgroundRepeat = "no-repeat";
document.getElementById('banner').style.backgroundSize = "388px";
}
}); // end doc ready
I messed around with this for a while, and I came up with this solution. Just make sure you have some content in the "banner" element so that it actually shows up, because just a background won't give size to the element.
function bg() {
var imgCount = 3;
var dir = 'http://local.statamic.com/_themes/img/';
// I changed your random generator
var randomCount = (Math.floor(Math.random() * imgCount));
// I changed your array to the literal notation. The literal notation is preferred.
var images = ['001.png', '002.png', '003.png'];
// I changed this section to just define the style attribute the best way I know how.
document.getElementById('banner').setAttribute("style", "background-image: url(" + dir + images[randomCount] + ");background-repeat: no-repeat;background-size: 388px 388px");
}
// Don't forget to run the function instead of just defining it.
bg();
Here's something sort of like what I use, and it works great. First, I rename all my background images "1.jpg" through whatever (ex. "29.jpg" ). Then:
var totalCount = 29;
function ChangeIt()
{
var num = Math.ceil( Math.random() * totalCount );
document.getElementById("div1").style.backgroundImage = 'images/'+num+'.jpg';
document.getElementById("div1").style.backgroundSize="100%";
document.getElementById("div1").style.backgroundRepeat="fixed";
}
Then run the function ChangeIt() .

Need to set styling rules to a JavaScript image randomizing script

I am trying to set the background images to be fixed and be stretched to fit the screen. the js that i am using if to switch the backgroud image on every pageload
Head
<script language="JavaScript">
<!-- Activate cloaking device
var randnum = Math.random();
var inum = 1;
// Change this number to the number of images you are using.
var rand1 = Math.round(randnum * (inum-1)) + 1;
images = new Array
images[1] = "http://simplywallpaper.net/pictures/2010/10/22/how_to_train_your_dragon_monstrous-nightmare.jpg"
images[2] = "tiler3.jpg"
images[3] = "wicker3.jpg"
images[4] = "aaa4.jpg"
// Ensure you have an array item for every image you are using.
var image = images[rand1]
// Deactivate cloaking device -->
</script>
Body
<script language="JavaScript">
<!-- Activate cloaking device
document.write('<body background="' + image + '" text="white" >')
</script>
The js itsself works fine to randomize the images but is currently set to 1 image
Simple, change both scripts to:
<script type="text/javascript">
var images = [ 'http://tinyurl.com/qhhyb8k'
, 'http://tinyurl.com/nqw2t9b'
, 'http://tinyurl.com/nkogvoq'
// , 'url 4'
]
, image = images[ (Math.random() * images.length)|0 ]
; //end vars
window.onload=function(){
document.body.style.background=
"url('"+image+"') no-repeat center center fixed";
document.body.style.backgroundSize=
"cover"; // width% height% | cover | contain
};
</script>
Nothing more to configure, just add/remove/change urls.
Example fiddle here.
Hope this helps.
inum needs to be set to something other than 1. You can set it to the number of images in the array.
Also, arrays start with index 0, so to be safer, you should index your array accordingly.
<script language="JavaScript">
// setup your image array
var images = new Array;
images[0] = "firstImage.jpg";
...
images[4] = "lastImage.jpg";
// alternative image array setup
var images = [ 'firstImage.jpg', 'secondImage.jpg', ... ,'lastImage.jpg' ];
// check to see if the image list is empty (if it's getting built somewhere else)
if (images.length) {
// set inum
var inum = images.length;
var randnum = Math.random();
var randIndex = Math.floor(randnum * inum);
// Ensure you have an array item for every image you are using.
var imageFile;
if (randIndex < images.length) {
imageFile = images[randIndex];
}
...
</script>
In the body
<script type="text/javascript">
window.onload = function() {
if (imageFile) {
var body = document.getElementsByTagName("body")[0];
if (body) { body.setAttribute('style',"background:url('"+imageFile+"'); text: white;"); }
}
}
</script>

Mouseover even in javascript wont output

Oh the splash screen of my new site I wish to have a mouseover event which will change the colour of my logo every time the mouse is moved. Below I have listed the code I have so far, but I cannot get it to display my image.
var images = new Array()
images[0] = 'img/CMbl.png'
images[1] = 'img/CMo.png'
images[2] = 'img/CMg.png'
images[3] = 'img/CMp.png'
images[4] = 'img/CMblu.png'
var p = images.length;
logo = document.getElementById( 'logo' ),
console = document.getElementById( 'console' );
logo.addEventListener('mousemove', changeImage);
function changeImage() {
var rand = Math.round(Math.random()*(p-1));
var image = p[ rand ];
if ( image == logo.src ) {
changeImage();
return false;
}
logo.src = console.innerText = image;
function showImage(){
document.write('<img src="+image[rand]">');
}
}
and my output in html should be (Inside the class 'logo')
<script language="javascript">
showImage()
</script>
I cannot see why it's not working. I am using a similar code to change image on refresh, which still uses math.random() and an array to call the images.
This is the way this should look:
document.write('<img src="' + image[rand] + '">');
(your script is full of mistakes from what I can see. I'll make a quick, working one for you as an example.)
Here is a working example(I think this is what you're going for) Jsfiddle example
As you can see, it comes out to a terrible looking effect, I wouldn't suggest using it.
I've made a JSfiddle which cleans up some of the code, and makes use of jQuery.
http://jsfiddle.net/jackcannon/2EXs5/
var images = [
'http://colorvisiontesting.com/plate%20with%205.jpg',
'http://regentsparkcollege.org.uk/wp-content/uploads/2012/09/test.jpg',
'http://nyquil.org/uploads/IndianHeadTestPattern16x9.png',
'http://25.media.tumblr.com/tumblr_m9p3n1vJmZ1rexr16o1_400.jpg',
'http://www.themoralofthestoryis.com/wp-content/uploads/2013/01/test.gif'
];
$('#logo').mouseover( changeImage );
function changeImage() {
var rand = Math.floor(Math.random() * images.length);
var image = images[ rand ];
if ( image == $('#logo').attr('src') ) {
changeImage();
return false;
}
$('#logo').attr('src', image);
};

I'm trying to stop snow script and clear the page after x seconds

How can I make the snow clear after a certain time. I've tried using variables and the calling a timeout which switches on to false and stops the makesnow() function but that doesn't seem to clear the page at all.
<script language="javascript">
ns6 = document.getElementById;
ns = document.layers;
ie = document.all;
/*******************[AccessCSS]***********************************/
function accessCSS(layerID) { //
if(ns6){ return document.getElementById(layerID).style;} //
else if(ie){ return document.all[layerID].style; } //
else if(ns){ return document.layers[layerID]; } //
}/***********************************************************/
/**************************[move Layer]*************************************/
function move(layer,x,y) { accessCSS(layer).left=x; accessCSS(layer).top = y; }
function browserBredde() {
if (window.innerWidth) return window.innerWidth;
else if (document.body.clientWidth) return document.body.clientWidth;
else return 1024;
}
function browserHoyde() {
if (window.innerHeight) return window.innerHeight;
else if (document.body.clientHeight) return document.body.clientHeight;
else return 800;
}
function makeDiv(objName,parentDiv,w,h,content,x,y,overfl,positionType)
{
// positionType could be 'absolute' or 'relative'
if (parentDiv==null) parentDiv='body';
var oDiv = document.createElement ("DIV");
oDiv.id = objName;
if (w) oDiv.style.width = w;
if (h) oDiv.style.height= h;
if (content) oDiv.innerHTML=content;
if (positionType==null) positionType="absolute";
oDiv.style.position = positionType;
if (x) oDiv.style.left=x; else oDiv.style.left=-2000;
if (y) oDiv.style.top=y; else oDiv.style.top=-2000;
if (overfl) oDiv.style.overflow=overfl; else oDiv.style.overflow="hidden";
eval(' document.'+parentDiv+'.appendChild (oDiv); ');
delete oDiv;
}
var snowC=0;
var x = new Array();
var y = new Array();
var speed = new Array();
var t=0;
var cC = new Array();
var ra = new Array();
function makeSnow() {
x[snowC] = Math.round(Math.random()*(browserBredde()-60));
y[snowC] = 10;
makeDiv("snow"+snowC,"body",32,32,'<img src="http://i693.photobucket.com/albums/vv296/KIBBLESGRAMMY/CAT/Orange-tabby-cat-icon.gif">');
speed[snowC] = Math.round(Math.random()*8)+1;
cC[snowC]=Math.random()*10;
ra[snowC] = Math.random()*7;
snowC++;
}
function moveSnow() {
var r = Math.round(Math.random()*100);
if (r>70 && snowC<20) makeSnow();
for (t=0;t<snowC;t++) {
y[t]+=speed[t];move("snow"+t,x[t],y[t]);
if (y[t]>browserHoyde()-50) {y[t] = 10;x[t] = Math.round(Math.random()*(browserBredde()-60));}
cC[t]+=0.01;
x[t]+=Math.cos(cC[t]*ra[t]);
}
setTimeout('moveSnow()',20);
}
moveSnow();
</script>
makeSnow just adds the snowflakes. Stopping that, as you say, does not clear anything. moveSnow handles the animation, and calls itself at a timeout. If instead of setting a timeout for the next moveSnow each time, you set it up to run in an interval just once, you would have an easier time stopping it.
window.snowAnimation = window.setInterval(moveSnow, 20);
If you add a css class to your snow flakes, it would be easier to target them for deletion.
oDiv.className = 'snowflake';
Then your clear function could look something like:
function clearSnow() {
window.clearTimeout(window.snowAnimation);
var flakes = document.getElementsByTagName('snowflake');
for(var i = 0, l = flakes.length; i < l; i++) {
document.body.removeChild(flakes[i]);
}
}
Timeout doesnt help, it helps you only to stop creating new snowdivs, however if you see makeDiv is the one which creates new divs on to the body, if you clear / display:none the divs which got created on makeDiv i hope it will clear all the divs on the screen.
You need to remove the divs that were created. It might be easier if you give them all some sort of class, like ".snowflake" as you create them (in makeDiv), then start removing them from the dom.
You will have to clear the elements created after the time you wanna stop snow falling.
Following code snippet will help you to clear the elements
if(count < 500){
setTimeout('moveSnow()',20);
}else{
var i = 0;
var elem = document.getElementById('snow'+i);
do{
elem.parentNode.removeChild(elem);
elem = document.getElementById('snow'+ ++i);
}while(elem != null)
}
count++;
you have to create a global variable count.

Categories

Resources