Random background gifs doesn't work - javascript

I have code that when the body loads, it chooses a random gif from a folder and uses that as the background. When a new page loads, or the same page, it chooses another random gif as the background. I've looked online, and even though the code is relatively the same, it doesn't load the new gif as the background. Here's the HTML code.
<html lang="en">
<head>
<!-- Random Background Image -->
<script>
function newBackground()
{
// Set up the image files to be used.
var theBackgrounds = new Array() // do not change this
// To add more image files, continue with the pattern below, adding to the array.
theBackgrounds[0] = 'images/EXTRA/Backgrounds/equalizer.gif'
theBackgrounds[1] = 'images/EXTRA/Backgrounds/equalizer2.gif'
theBackgrounds[2] = 'images/EXTRA/Backgrounds/recordSpinning.gif'
var p = theBackgrounds.length;
var whichBackground = Math.round(Math.random()*(p-1));
document.body.style.background = theBackgrounds[whichBackground];
}
</script>
</head>
<body onLoad="newBackground();">
*some code*
</body>
</html>
And here's the body's CSS code that's in styles.css.
body{
background-size:cover;
background-repeat: repeat-y;
background-attachment: fixed;
background-color:#000000;
color:#FFF;
font-size:13px;
font-family: Helvetica, Arial, sans-serif;
text-align:left;
}
Why is the code not working?

because that is not how you set a background image with CSS. You are missing the url() portion.
It should be
document.body.style.backgroundImage = "url(" + theBackgrounds[whichBackground] + ")";

Related

how to change image when scrolling webpage [html, javascript]

Hi i need to modify java script that will by changing fixed image.
In for example:
when page is loaded then image will by on right site. Next after scrolling down page image should be changed to next one for each e.g. 100px. Images need to by loaded from image list or something similar.
I have found java script that make something similar to this. [Instead of creating images of numbers i need to load my own images]
<!DOCTYPE html>
<html>
<head>
<style>
html,body {
height: 400%;
background: white;
width: 100%;
}
.show {
width: 100px;
height: 100px;
position: fixed;
top: 300px;
right: 20px;
background: lime;
}
</style>
</head>
<body>
<img class="show" alt="0" src="img0.jpg" />
Text,Text,Text,Text,Text,Text,Text,Text,Text,Text,Text
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
<script type="text/javascript" src="jquery.easing.1.3.js"></script>
<script type="text/javascript">
var lastI
$(window).scroll(function() {
var scrollTop = $(this).scrollTop()
console.log(scrollTop)
var i = (scrollTop / 10).toFixed(0)
if (i !== lastI)
$(".show").attr({
"src": "img" + i + ".jpg",
"alt": i
})
lastI = i
})
</script>
</body>
</html>
Update:09.11.2017
Ok, I manage this code to work. What should I do it was to setup right path to image files like in my case ("src": "test/" + i + ".jpg",) where my images are in "test" folder, and change names of images [1.jpg, 2.jpg and so on].
You can easyli change your image with Native scroll event, without using JQuery :
You can see how to use native scroll event here
<body>
<!-- This is an image with a 'show' id -->
<img id="show" alt="0" src="img0.jpg" />
<script type="text/javascript">
/* this capture the `scroll event`*/
window.addEventListener('scroll', function(e) {
/* This generate a image name in case with scroll position (ex img1.jpg) */
let bgImage = 'img' + (window.scrollY / 10 ).toFixed(0) + '.jpg';
/* This specify the path where are your images list */
let bgImagePath = '../images/' + bgImage;
/* This get your element (img) with id `show` and change this background image by the path include in `bgImagePath` variable */
document.getElementById('show').style.backgroundImage = bgImagePath;
});
</script>
</body>
Native background image explain here
Native getElementById explain here
This sample of code do not use JQuery :) Just native Javascript : you van remove this lines in your code :
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
<script type="text/javascript" src="jquery.easing.1.3.js"></script>
Hope I help you.
I'am not sure, try this one:
$(document).scroll(function () {
var y = $(this).scrollTop();
if (y > 100) {
$('.Classname').css("background-image","../images/image.png");
} else {
$('.Classname').css("background-image","none");
}
});

Where did I go wrong with my javascript handling my slideshow image banner?

Here's what I have so far, it's a very basic slide image banner inside my header tag in html. Basically, every 3 seconds, I have a new image showing up. I plan on using that for the mock exercise I'm working on right now but unfortunately, something went wrong in Javascript. At least, that's what I think it is. The image banner does NOT keep going through the images. It just sticks to one picture and goes no where else. No other pictures show up. This is the error I'm getting inside my console log right now.
Uncaught TypeError: Cannot read property 'setAttribute' of null. at changeImage (slideshow.js:7)
Here's the HTML I have right now.
<html>
<head>
<title>Kenneth's Slide Show Demonstration</title>
<meta charset="UTF-8">
<link rel='stylesheet' type='text/css' href='slideshow.css'>
<script src="slideshow.js"></script>
</head>
<body>
<div id="wallpaper"><img src="ferrari-logo0.jpg" id="ferrari" alt="ferrari logo"/></div>
</body>
</html>
now for CSS.
body {
padding:0;
margin:0;
}
#wallpaper {
height:300px;
width:100%;
margin:auto;
background:rgba(0,0,0,0.7);
border-bottom:dashed black 1px;
transition:all 0.5s ease-in-out;
}
#ferrari {
margin-left:auto;
margin-right:auto;
display:block;
height:250px;
width:400px;
padding-top:20px;
}
#wallpaper:hover {
background:rgba(0,0,0,1);
}
And then here's the Javascript I've made.
var myImage = document.getElementById('ferrari');
var imageArray=['ferrari-logo0.jpg', 'ferrari-logo1.jpg', 'Ferrari-logo2', 'ferrari-logo3.jpg'];
var imageIndex=0;
function changeImage() {
myImage.setAttribute("src", imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
};
var intervalHandle = setInterval(changeImage(),4000);
function changeImage();
Where did I go wrong? If I can make a special request, I'd like straight Vanilla javascript. I know Jquery is popular but I'm not currently studying that right now.
No need in round brackets in setInterval for function changeImage();
var imageArray = ['ferrari-logo0.jpg', 'ferrari-logo1.jpg', 'Ferrari-logo2', 'ferrari-logo3.jpg'];
var imageIndex = 0;
function changeImage() {
var myImage = document.getElementById('ferrari');
if (myImage) {
myImage.setAttribute("src", imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
};
var intervalHandle = setInterval(changeImage, 4000);
Try it. You must pass a function, not invoke it.
You are loading your JavaScript in the head of your page, so when your JS runs, the ferrari element does not exist yet. getElementById returns null if it doesn't find an element with the id you provide. Thus, you are in effect trying to do null.setAttribute("src", imageArray[imageIndex]);. Since null doesn't have a setAttribute method you are getting the error message telling you Cannot read property 'setAttribute' of null.
Moving your script tag below the ferrari element should fix it. It has become a best practice to load your JS as low in the page as you can for other performance related reasons. You could also keep your script tag where it is if you wrap your code in a DOMContentLoaded event handler.
You just need to invoke changeImage, like this setInterval(changeImage,4000) also changeImage() is already defined, you just need to call it.
Here is a working example.
document.addEventListener("DOMContentLoaded", function() {
var myImage = document.getElementById('ferrari');
var imageArray=['http://placehold.it/350x150?text=1',
'http://placehold.it/350x150?text=2',
'http://placehold.it/350x150?text=3',
'http://placehold.it/350x150?text=4'
];
var imageIndex=0;
function changeImage() {
myImage.setAttribute("src", imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
var intervalHandle = setInterval(changeImage, 4000);
changeImage();
});
body {
padding:0;
margin:0;
}
#wallpaper {
height:300px;
width:100%;
margin:auto;
background:rgba(0,0,0,0.7);
border-bottom:dashed black 1px;
transition:all 0.5s ease-in-out;
}
#ferrari {
margin-left:auto;
margin-right:auto;
display:block;
height:250px;
width:400px;
padding-top:20px;
}
#wallpaper:hover {
background:rgba(0,0,0,1);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Wallpapers</title>
</head>
<body>
<div id="wallpaper">
<img src="" id="ferrari" alt="ferrari logo"/></div>
</body>
</html>
It's best practice to load your scripts after html is loaded, so place your html before then end body tag </body>, or use DOMContentLoaded https://developer.mozilla.org/en/docs/Web/Events/DOMContentLoaded

Bouncing img in div game

I have a problem with my code in javascript. I want to edit code to make my mini game.
This is the original code I'm trying to edit. It's about bouncing balls. When you press the button the balls starts bouncing. The balls are in random position and every ball is moving randomly. When they are about to escape the border they are returning. Everything in this code works perfect.
Original code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
#border {height:500px; width:500px; border:1px solid grey; margin:auto; position:relative}
b {display:block; height:10px; width:10px; border-radius:5px; background:red; position:absolute}
h1,div {text-align:center; margin:10px}
</style>
</head>
<body>
</body>
<h1>Balls</h1>
<div id='border'>
<b></b>
<b></b>
<b></b>
<b></b>
<b></b>
<b></b>
<b></b>
<b></b>
<b></b>
<b></b>
<b></b>
</div>
<div>
<button onclick="run=false"> Stop </button>
<button onclick="run=true;start()"> Start </button>
</div>
<script>
var b=document.getElementsByTagName('B');
var run=false;
var i;
for(i=0;i<b.length;i++)
{
b[i].x=Math.random()*490;
b[i].y=Math.random()*490;
b[i].vx=Math.random()*20-10;
b[i].vy=Math.random()*20-10;
b[i].style.left=b[i].x+"px";
b[i].style.top =b[i].y+"px";
}
function start()
{
var i;
for(i=0;i<b.length;i++)
{
b[i].x+=b[i].vx;
b[i].y+=b[i].vy;
if(b[i].x>490 || b[i].x<0) b[i].vx*=-1;
if(b[i].y>490 || b[i].y<0) b[i].vy*=-1;
b[i].style.left=b[i].x+"px";
b[i].style.top =b[i].y+"px";
}
if(run)
setTimeout(start,20);
}
</script>
</html>
I want to replace the balls with images. I think I did it but it doesn't work at all. Images are always in the same position. When I press the button to move them, images are moving in the same direction. Images are escaping from border (they should bounce on the walls and return).
My edit:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
#border {height:500px; width:500px; border:1px solid grey; margin:auto; position:relative}
img {display:block; height:10px; width:10px; position:absolute}
h1,div {text-align:center; margin:10px}
</style>
</head>
<body>
</body>
<h1>Balls</h1>
<div id='border'>
<img src="http://www.doktoranci.uj.edu.pl/image/image_gallery?uuid=8de2ed31-63f2-42f3-83fd-8fc0b7c48975&groupId=1167150&t=1287521328354">
<img src="http://www.doktoranci.uj.edu.pl/image/image_gallery?uuid=8de2ed31-63f2-42f3-83fd-8fc0b7c48975&groupId=1167150&t=1287521328354">
<img src="http://www.doktoranci.uj.edu.pl/image/image_gallery?uuid=8de2ed31-63f2-42f3-83fd-8fc0b7c48975&groupId=1167150&t=1287521328354">
</div>
<div>
<button onclick="run=false"> Stop </button>
<button onclick="run=true; start()"> Start </button>
</div>
<script>
var b=document.getElementsByTagName('IMG');
var run=false;
var i;
for(i=0; i<b.length; i++)
{
b[i].x=Math.random()*490;
b[i].y=Math.random()*490;
b[i].vx=Math.random()*20-10;
b[i].vy=Math.random()*20-10;
b[i].style.left=b[i].x+"px";
b[i].style.top =b[i].y+"px";
}
function start()
{
var i;
for(i=0; i<b.length; i++)
{
b[i].x+=b[i].vx;
b[i].y+=b[i].vy;
if(b[i].x>490 || b[i].x<0) b[i].vx*=-1;
if(b[i].y>490 || b[i].y<0) b[i].vy*=-1;
b[i].style.left=b[i].x+"px";
b[i].style.top =b[i].y+"px";
}
if(run)
setTimeout(start,20);
}
</script>
</html>
I want my images to behavior like the balls in original code.
You're my only hope.
Instead of using <img>, use
b {background-image: url("http://www.doktoranci.uj.edu.pl/image/image_gallery?uuid=8de2ed31-63f2-42f3-83fd-8fc0b7c48975&groupId=1167150&t=1287521328354");
background-repeat: no-repeat;
background-position: right top;}
The reason the code is not working with img tags is outlined in the documentation:
HTMLImageElement.x Read only Returns a long representing the
horizontal offset from the nearest layer. This property mimics an old
Netscape 4 behavior.
HTMLImageElement.y Read only Returns a long
representing the vertical offset from the nearest layer. This property
mimics an old Netscape 4 behavior.
As a work around you can use background-image on b tags or change the coordinates property names to i.e. currentX and currentY

Communicating between iframes

I'm trying to do something with iframes and am struggling a little bit at the moment. Basically, I have a script that generates a grid of squares (image below) and I want to make it so that when I click on a square, I display something in a different iframe.
So for instance, say I had frame 1 (which contains the grid) and frame 2 (this is the "display" frame). If I click the top left square, then I want to display "index(0,0)" in the display frame. If I click the (1, 1) square, then I want to display "index(1,1)" and so on.
I already know how to do this within the same frame (ie I can display "index(0,0)" within frame 1 if I click on a square in frame 1), but I am just confused on how to do this in a separate frame. I've tried quite a few things but nothing seems to be working.
I will include all of my code below as well as a picture for your reference. Any help is greatly appreciated!
Javascript:
// I know this isnt good coding practice, but I was getting desperate
// trying things xD
var currentDisplay = "display";
function changeSquare() {
var image = document.getElementById(this.id);
// If image is currently green square, change to red, and vice versa
if (image.src.match("http://www.clker.com/cliparts/b/d/4/F/W/N/green-square-button-md.png")) {
image.src = "http://www.clker.com/cliparts/1/J/s/o/7/y/red-square-button-md.png";
} else {
image.src = "http://www.clker.com/cliparts/b/d/4/F/W/N/green-square-button-md.png";
}
currentDisplay = this.id;
};
function printInfo() {
document.write(currentDisplay);
}
// Creates a grid of dimensions width by height
function makeGrid(height, width) {
// Loop over height and width to create black square objects with
// buttons in middle
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
// Outer div is black square
var div = document.createElement("div");
div.className = "square";
div.id = ("div").concat(i,",", j);
var innerDiv0 = document.createElement("div");
innerDiv0.className = "content";
div.id = ("innerDiv0").concat(i,",", j);
div.appendChild(innerDiv0);
// InnerDiv1 & 2 are table structures (necessary for alignment)
var innerDiv1 = document.createElement("div");
innerDiv1.className = "table";
div.id = ("innerDiv1").concat(i,",", j);
innerDiv0.appendChild(innerDiv1);
var innerDiv2 = document.createElement("div");
innerDiv2.className = "table-cell";
div.id = ("innerDiv2").concat(i,",", j);
innerDiv1.appendChild(innerDiv2);
// Add green square image
var image = document.createElement("img");
image.id = ("image").concat(i,",", j);
image.src = "http://www.clker.com/cliparts/b/d/4/F/W/N/green-square-button-md.png";
image.className = "rs";
innerDiv2.appendChild(image);
document.body.appendChild(div);
// Add onclick feature
image.onclick = changeSquare;
}
}
};
GridTest.html
<head>
<link rel="stylesheet" type="text/css" href="GridTest.css">
</head>
<body>
<script src="GridTest.js">
</script>
<script>
makeGrid(20, 20);
</script>
</body>
displayPanel.html
<head>
<link rel="stylesheet" type="text/css" href="GridTest.css">
</head>
<body>
<script src="GridTest.js">
</script>
<script>
printInfo();
</script>
</body>
nestTest.html (here is where I create the iframes)
<head>
<link rel="stylesheet" type="text/css" href="GridTest.css">
<script src = "GridTest.js"> </script>
</head>
<iframe id="frame1" scrolling="no" src="GridTest.html">
</iframe>
<iframe id="frame2" scrolling="no" src="displayPanel.html"></iframe>
CSS (probably unnecessary but I'll include it anyways)
.square {
float:left;
position: relative;
width: 5%;
padding-bottom: 2.8125%;
background-color:#1E1E1E;
overflow:hidden;
outline: 1px solid #FFFFFF;
}
.whiteSquare {
float:left;
position: relative;
width: 5%;
padding-bottom: 2.8125%;
background-color:#FFFFFF;
overflow:hidden;
outline: 1px solid #FFFFFF;
}
/*
Aspect ratio | padding-bottom | for 30% width
------------------------------------------------
1:1 | = width | 30%
1:2 | width x 2 | 60%
2:1 | width x 0.5 | 15%
4:3 | width x 0.75 | 22.5%
16:9 | width x 0.5625 | 16.875%
*/
.content {
position:absolute;
height:40%;
width:47%;
padding: 5% 26.5%;
text-align:center;
}
.content .rs{
width:auto;
height:auto;
max-height:90%;
max-width:100%;
}
.table{
display:table;
height:100%;
width:100%;
}
.table-cell{
display:table-cell;
vertical-align:middle;
height:100%;
width:100%;
}
body {
font-size:20px;
font-family: 'Lato',verdana, sans-serif;
color: #000000;
background:#ECECEC;
}
.numbers{
font-weight:900;
font-size:100px;
}
Picture of current result.
In your changeSquare method, try something like this:
var frame2 = $('#frame2', top.document) //Give you top level frame jQuery Object.
for more backwards compatibility, you can use something like:
window.parent.$('#frame2')
Or something like this for no jQuery:
window.parent.getElementById('#frame2')[attributeName]
Once you have the root iFrame object, you can proceed with regular jQuery/DOM manipulation.
EDIT: here is a fully working and tested solution (Safari/Mac OS). Only the changes are highlighted below:
displayPanel.html:
<head>
<link rel="stylesheet" type="text/css" href="GridTest.css">
</head>
<body>
<script src="GridTest.js">
</script>
<script>
printInfo();
</script>
<div id="label1"></div> <!--Added a div for displaying text -->
</body>
GridTest.js:
function changeSquare() {
var image = document.getElementById(this.id);
//First get a reference to the second frame document
var secondFrameDocument = window.top.document.getElementById('frame2').contentWindow.document;
//Now set the value of the Div
secondFrameDocument.getElementById('label1').textContent=this.id;
// If image is currently green square, change to red, and vice versa
if (image.src.match("http://www.clker.com/cliparts/b/d/4/F/W/N/green-square-button-md.png")) {
image.src = "http://www.clker.com/cliparts/1/J/s/o/7/y/red-square-button-md.png";
} else {
image.src = "http://www.clker.com/cliparts/b/d/4/F/W/N/green-square-button-md.png";
}
currentDisplay = this.id;
};
Depending upon your exact scenario, you may run into security issues, particularly with Chrome. A better solution would be to perhaps use two Divs instead of iFrames.
Here's a screenshot:

JQuery: Image appear by mouse move?

I want to make a image appear on my site when the mouse moves. It can appear to be a stupid thing to do, but it's really important that when the page loads the image is not yet visible.
My HTML is like this:
<html>
<head>
</head>
<body>
<div class="page-container">
<div>
<a id="entrar" href="_pt/log_in.html"><img src="_assets/entrar.jpg" alt="entrar"></a>
</div>
</div>
<script src="_js/jquery-1.10.2.js"></script>
<script src="_js/jquery-ui-1.10.3.js"></script>
<script src="_js/exp.js"></script>
</body>
</html>
In my CSS i'm making the image not visible
#entrar {
display: none;
}
And in my Javascript:
function PrepareHandlers() {
$(".page-container").mousemove(function(){
$("a#entrar").css("display", "inline");
});
}
...
window.onload = function(){
....
PrepareHandlers();
}
Could anyone tell me what I'm doing wrong plz. Thanks
Declare this in your source file , not inside a function !
$(document).ready( function(){
$(".page-container").mousemove(function(){
$("a#entrar").css("display", "inline");
});
})
It appears likely the page container is not taking up any space, and therefore it never receives a mousemove event. Here is an easy CSS fix to test this theory:
body { position : absolute; top :0; bottom : 0; left : 0; right: 0;}
.page-container { width : 100%; height : 100%; background-color : #ddd; }
Check out this solution.
You should preload the image to minimize or avoid an annoying/confusing lag like so:
var img = new Image();
img.src = '//your/url/to/image';

Categories

Resources