Random background change upon refresh - javascript

I am trying to make it so that when the page is visited or refreshed, the background changes. I am trying to achieve this with JS.
This is the JS I currently have:
<script type="text/javascript">
var imgCount = 3;
var dir = 'img/';
var randomCount = Math.round(Math.random() * (imgCount - 1)) + 1;
var images = new Array
images[1] = "1.png",
images[2] = "2.png",
images[3] = "3.png",
document.body.style.background = "url(" + dir + images[randomCount] + ")";
</script>
Along with the HTML:
<html>
<head>
<!-- The JS was here but didnt liek to be pasted -->
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="page">
Rawr
</div>
</body>
</html>
And the CSS:
html, body {
background: no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
background-size: cover;
}
#page {
width: 900px;
height: auto;
border: #900 1px solid;
border-radius: 5px;
float: right;
margin-right: 20px;
}
My main problem is that images; firstly - don't appear and secondly - I don't know if the script is working or not because of this.
My file tree is as simple as a root directory and a folder named 'img' for images with 3 images, 1 - 3 that are png's.
Please could someone help me establish why the background doesn't show up, if the code is actually working.
Thanks. Sorry if my posting is inadequate, I'm really not the best at this kind of thing =/

As adeneo said you should put your script after DOM is ready, something like
Update
For not repeat the background you should use this snippet of code.
document.body.style.backgroundRepeat = "no-repeat";
Full Code
<html>
<head>
<!-- The JS was here but didnt liek to be pasted -->
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="page">
Rawr
</div>
<!-- put your script is here after dom is ready -->
<script type="text/javascript">
var imgCount = 3;
var dir = 'img/';
var randomCount = Math.round(Math.random() * (imgCount - 1)) + 1;
var images = new Array
images[1] = "1.png",
images[2] = "2.png",
images[3] = "3.png",
document.body.style.background = "url(" + dir + images[randomCount] + ")";
document.body.style.backgroundRepeat = "no-repeat";
//----^----for not repeat the background
</script>
</body>
</html>

Related

Code for a random background-image every time the page is refreshed

I am working on an html-file that is supposed to show a new backround-image everytime the page is refreshed. This HTML-file is placed in a directory called "Startsida".
The images backgroundphoto1, backgroundphoto2 and backgroundphoto3 are placed in a folder called "images".
There's still something wrong with my code and I don't know how to fix it.
I don't know if it's worth noting, but this code is made on visual studios.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- The randomator -->
<script>
var images = [
"../images/photobackground1.jpg",
"../images/photobackground2.jpg",
"../images/photobackground3.jpg",
];
function randomator() {
document.getElementsByClassName("bg")[0].style.backgroundImage =
"url(" + images[Math.floor(Math.random() * images.length)] + ")";
}
randomator();
</script>
<style>
body,
html {
height: 100%;
margin: 0;
}
.bg {
/* Full height */
height: 100%;
/* Center and scale the image nicely */
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
</style>
</head>
<body>
<div class="bg">randomator</div>
</body>
</html>```
From your code, it looks like you have several misunderstandings regarding the fundamentals of HTML, JavaScript, and CSS. I'll break these issues down for you, sorted by language. At the very bottom, you'll find a completely fixed version that works perfectly.
HTML
Closing tags
Tags with child elements must be opened and closed. You wrote:
<div> randomator.bg <div>
The correct syntax is:
<div> randomator.bg </div>
Without the slash in the closing tag, there's no way for the browser to know where an element starts or ends.
Classes
You can't give a class to an HTML div by simply writing .classname inside. You have to add the class attribute to the opening tag. You wrote:
<div> randomator.bg </div>
The correct syntax is:
<div class="bg"> randomator </div>
JavaScript
Line endings
Semicolons should only be used at the very end of a line of JavaScript code. You wrote:
randomator(); {
...
}
The correct syntax is:
randomator() {
...
}
Function definitions
You must provide either the function identifier or use ES6 arrow functions when defining a function. You wrote:
randomator() {
...
}
The correct syntax is:
function randomator() {
...
}
Class matching with HTML
You need to select the correct element if you want to change its background. If you've been following along from above, you should only have an element with a class of bg. You wrote:
document.getElementsByClassName("mainview")[0].style.backgroundImage = "url(" + images[Math.floor(Math.random() * images.length)] + ")";
The correct syntax is:
document.getElementsByClassName("bg")[0].style.backgroundImage = "url(" + images[Math.floor(Math.random() * images.length)] + ")";
CSS
JavaScript vs CSS
JavaScript and CSS are two different languages, and though JavaScript does have the ability to change CSS properties, the two don't share variables. You wrote:
background-image: mainview;
There's no way to do this exactly, though you could technically use JS to change CSS variables. In your case, I'd recommend just removing this line entirely.
Complete example
The code below should work perfectly - all bugs have been fixed.
var images = ["images/photokacround1.jpg", "images/photobackround2.jpg", "images/photobackround3.jpg"];
function randomator() {
document.getElementsByClassName("mainview")[0].style.backgroundImage = "url(" + images[Math.floor(Math.random() * images.length)] + ")";
}
randomator();
body,
html {
height: 100%;
margin: 0;
}
.mainview {
/* Full height */
height: 100%;
/* Center and scale the image nicely */
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
<div class="mainview"> randomator </div>
I solved it! the problem is that I didn't mention the as javascript! In this part...
var images = [
"../images/photobackground1.jpg",
"../images/photobackground2.jpg",
"../images/photobackground3.jpg",
];
function randomator() {
document.getElementsByClassName("bg")[0].style.backgroundImage =
"url(" + images[Math.floor(Math.random() * images.length)] + ")";
}
randomator();
...Is was supposed to mention < script type="text/javascript"> and then ending it of with < script>.
While I was using that I was supposed to write
<script type="text/javascript">
randomator();
</script>
I have tested the code and it now works! This is the full code:
<!DOCTYPE html> <html> <head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- The randomator -->
<script type="text/javascript">
var images = [
"../images/bakgrundbilder/photobackground1.jpg",
"../images/bakgrundbilder/photobackground2.jpg",
"../images/bakgrundbilder/photobackground3.jpg",
];
function randomator() {
document.getElementsByClassName("bg")[0].style.backgroundImage =
"url(" + images[Math.floor(Math.random() * images.length)] + ")";
}
randomator();
</script>
<style>
body,
html {
height: 100%;
margin: 0;
}
.bg {
/* Full height */
height: 100%;
/* Center and scale the image nicely */
background-position: center;
background-repeat: no-repeat;
background-size: cover;
} </style> </head> <body>
<div class="bg"> </body> <script type="text/javascript">
randomator();
</script> </html>
Just don't forget to replace the backgroundimages and reference them correctly!

How to Display one Image at a Time from external JSON file - creating Slideshow

I am trying to create a slideshow by using an external JSON array of Images, and I have managed to make the 'next' button to display all the images on click, but I cannot seem to figure out how to make only one different image appear at one time when the button is clicked.
I need help with the following:
1) How to make next button show an image one at a time
2) How to make caption show in similar fashion
This is my HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<link rel="stylesheet" type="text/css" href="slideshow.css">
<title> JSON SlideShow </title>
</head>
<body>
<header>
<h1> JSON SlideShow </h1>
</header>
<br>
<button id="nextbtn"> Next </button>
<div id="slideshow"></div>
<div id="caption"></div>
<script src="slideshow.js"></script>
</body>
</html>
This is my Java Script:
var prevbtn = document.getElementById("prevbtn");
var nextbtn = document.getElementById("nextbtn");
var slideContainer = document.getElementById("slideshow");
nextbtn.addEventListener("click", function() {
var JSONarray = new XMLHttpRequest();
JSONarray.open('GET', 'http://localhost/slide.json');
JSONarray.onload = function () {
var mySlides = JSON.parse(JSONarray.responseText);
createHTML(mySlides);
};
JSONarray.send();
});
function createHTML(slide) {
var i;
var image = "";
for (i = 0; i < slide.length; i++) {
image += '<img src=" '+ slide[i].image_name + '"></img>';
}
slideContainer.insertAdjacentHTML('beforeend', image);
};
This is my CSS
/* Slideshow container */
.slideshowcontainer {
max-width: 1000px;
position: relative;
margin: auto;
}
/* Hide the images by default */
#slideshow {
display: none;
}

Why are my generated images not setting their position based on my mouse cursor?

I am fairly new to web development and I wanted to practice the HTML, CSS, and Javascript that I learned over the weekend. I am having trouble positioning my images correctly based on my mouse cursor. I can see that my images are being appended in the "inspect" section of google chrome but their positioning is not matching up with how the style indicates. Is there a problem with my HTML, CSS, or Javascript or all three? I want it to work similarly to http://howlooongcanthisgoon.com/
1[]2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Jaws that Bite My Claws That Catch</title>
<style>
*{
padding: 0;
margin: 0;
}
#witchwood{
background: url("witchwood.jpg");
height: 100vh;
background-position: 75% 20%;
overflow: hidden;
}
.shudder{
position: absolute;
}
</style>
</head>
<body>
<div id="witchwood" onclick="wok(event)"></div>
</body>
<script type="text/javascript">
//document.getElementById('witchwood').addEventListener("click", wok);
var z = 0;
function wok(e){
//finds position of mouse
var x= e.clientX;
var y= e.clientY;
//creates the img element
var img = document.createElement("img");
img.src = "shudderwock.png";
img.class = "shudder";
img.style.top = y + "px";
img.style.left = x + "px";
//appends the img into the div class="witchwood"
document.getElementById('witchwood').appendChild(img);
}
</script>
</html>
Here is a link to the jsfiddle.
Your .shudder class is not being applied. The appropriate DOM property is called className. You don't set an HTMLElement attribute with img.class.
Change
img.class = "shudder";
To
img.className = "shudder";
Alternatively, you could use;
img.setAttribute('class', 'shudder');

Javascript, make random_generated image as background

What I have
I have a HTML & javascript code : The javascript generate a random_number and use it as indexing on the array of images.Then,the script add the selected picture to the <img> tag of html code.
It's works very well.
What I need
I want to make the tags as background_image(display texts in it,buttons and more). Is there any way to do it? /searched lot of in google and there's no excellent result/.
Thank you for help. :(
window.onload = function() {
var cGamePic = new Array("http://advsys.net/ken/voxlap/voxlap_lib.jpg","http://advsys.net/ken/voxlap/cave.png");
var cGameName = new Array("Voxlap1", "Voxlap2");
var randomItemContainer1 = Math.floor(Math.random() * cGamePic.length); //container1
var randomItemContainer2 = Math.floor(Math.random() * cGamePic.length); //container2
var comp1GameTitle = document.querySelector("#container1 h1"); //Heading from main container
var comp1GameImage = document.querySelector("#container1 img"); //Image from main container
var comp2GameTitle = document.querySelector("#container2 h1"); //Heading from main container
var comp2GameImage = document.querySelector("#container2 img"); //Image from main container
comp1GameTitle.innerHTML = cGameName[randomItemContainer1]; //Random Title
comp1GameImage.src = cGamePic[randomItemContainer1]; //Random image
comp2GameTitle.innerHTML = cGameName[randomItemContainer2]; //Random Title
comp2GameImage.src = cGamePic[randomItemContainer2]; //Random image
};
<!doctype html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<title>Random_page</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript" src="rnd.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<!--width:45%; margin: 10px;-->
<div id="container1" style="float:left; width:45%; margin: 10px;">
<h1>Title</h1>
<img src="" width='100%' height='100%' />
</div>
<div id="container2" style="float:left; width:45%; margin: 10px;">
<h1>Title</h1>
<img src="" width='100%' height='100%' />
</div>
</body>
</html>
If you need to apply those random images as a background, it will be set as a background image of a div and not an img, so replace your img with a div and instead of writing:
comp1GameImage.src = cGamePic[randomItemContainer1];
You will need to write:
comp1GameImage.style.backgroundImage = "url('"+ cGamePic[randomItemContainer1]+"')";
Where comp1GameÎmage is your div.
Here's your updated Snippet:
window.onload = function() {
var cGamePic = new Array("http://advsys.net/ken/voxlap/voxlap_lib.jpg", "http://advsys.net/ken/voxlap/cave.png");
var cGameName = new Array("Voxlap1", "Voxlap2");
var randomItemContainer1 = Math.floor(Math.random() * cGamePic.length); //container1
var randomItemContainer2 = Math.floor(Math.random() * cGamePic.length); //container2
var comp1GameTitle = document.querySelector("#container1 h1"); //Heading from main container
var comp1GameImage = document.querySelector("#container1"); //Image from main container
var comp2GameTitle = document.querySelector("#container2 h1"); //Heading from main container
var comp2GameImage = document.querySelector("#container2"); //Image from main container
comp1GameTitle.innerHTML = cGameName[randomItemContainer1]; //Random Title
comp1GameImage.style.backgroundImage = "url('" + cGamePic[randomItemContainer1] + "')";
//cGamePic[randomItemContainer1]; //Random image
comp2GameTitle.innerHTML = cGameName[randomItemContainer2]; //Random Title
comp2GameImage.style.backgroundImage = "url('" + cGamePic[randomItemContainer2] + "')";
//cGamePic[randomItemContainer2]; //Random image
};
#container1,
#container2 {
display: inline-block;
width: 45%;
height: 100%;
float: left;
margin: 10px;
}
<!doctype html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<title>Random_page</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript" src="rnd.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<!--width:45%; margin: 10px;-->
<div id="container1">
<h1>Title</h1>
</div>
<div id="container2">
<h1>Title</h1>
</div>
</body>
</html>
EDIT:
To make the two divs split the page into two frames, give them these styles:
#container1, #container2{
display:inline-block;
width:45%;
height:100%;
}
You could make images look like background (NOT in background) by overlapping H1 on IMG using CSS :
[id*=container] {
position:relative; /*--container is relative*/
}
h1 {
position:absolute; /*Image title is absolute*/
top:30px;
left:30px;
}
DEMO :
window.onload = function() {
var cGamePic = new Array("http://advsys.net/ken/voxlap/voxlap_lib.jpg","http://advsys.net/ken/voxlap/cave.png");
var cGameName = new Array("Voxlap1", "Voxlap2");
var randomItemContainer1 = Math.floor(Math.random() * cGamePic.length); //container1
var randomItemContainer2 = Math.floor(Math.random() * cGamePic.length); //container2
var comp1GameTitle = document.querySelector("#container1 h1"); //Heading from main container
var comp1GameImage = document.querySelector("#container1 img"); //Image from main container
var comp2GameTitle = document.querySelector("#container2 h1"); //Heading from main container
var comp2GameImage = document.querySelector("#container2 img"); //Image from main container
comp1GameTitle.innerHTML = cGameName[randomItemContainer1]; //Random Title
comp1GameImage.src = cGamePic[randomItemContainer1]; //Random image
comp2GameTitle.innerHTML = cGameName[randomItemContainer2]; //Random Title
comp2GameImage.src = cGamePic[randomItemContainer2]; //Random image
};
[id*=container] {
position:relative;
}
h1 {
position:absolute;
top:30px;
left:30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--width:45%; margin: 10px;-->
<div id="container1" style="float:left; width:45%; margin: 10px;">
<h1>Title</h1>
<img src="" width='100%' height='100%' />
</div>
<div id="container2" style="float:left; width:45%; margin: 10px;">
<h1>Title</h1>
<img src="" width='100%' height='100%' />
</div>

Is there a way to make a preloader for swfs in Javascript or JQuery

Is there a way to make a preloader in Javascript or JQuery so that all the elements in a webpage like the swfs and images load fully before they play and show. I have a preloader in the flash of the swfs, but some times it plays choppy. My code works properly but is it a way to preload the whole page using Javascript or JQuery before the webpage plays or shows the element with the website?
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>???</title>
<script type="text/javascript" src="swfobject-1.5.js"></script>
<script language="javascript" type="text/javascript" src="jquery-1.2.6.min.js"> </script>
<script type="text/javascript">
$(document).ready(function(){
if(readCookie("flashPlayed") == "true"){
Jvid()&&Bg()
}
});
function launchFlash(){
if(readCookie("flashPlayed") != "true"){
var homeflash = new SWFObject("???.swf", "BG", "100%", "100%", "8");
homeflash.addParam("wmode","transparent");
homeflash.write("videoBg");
var homeflash = "Bg";
setTimeout("Bg()");
setTimeout("Jvid()",5000);
setTimeout("removeFlash()",5000);
}
}
function readCookie(cookieName){
var searchName = cookieName + "="
var cookies = document.cookie
var start = cookies.indexOf(cookieName)
if (start == -1){ // cookie not found
return ""
}
start += searchName.length //start of the cookie data
var end = cookies.indexOf(";", start)
if (end == -1){
end = cookies.length
}
return cookies.substring(start, end)
}
function Jvid(){
$("#videos").hide();
}
function Bg(){
$("#test").css({"background":'url("???.jpg")',"background-position":'top center'});
}
function removeFlash(){
$("#videoBg").empty();
$("#videoBg").animate( { top:"-9999px"}, 1 );
window.location.assign("http://???.com")
}
</script>
<style>
#test {
font-family: Geneva,Arial,Helvetica,sans-serif;
font-size: 12px;
height: 100%;
margin: 0;
padding: 0;
text-align: left;
width: 100%;
position:relative;
background:url(???.jpg) top center repeat #000;
}
#videoBg{
position:fixed;
top:-5px;
left:0px;
height:100%;
width:100%;
}
#videos{margin:0 auto 0;
padding:0;
height:301px;
width:205px;
position:absolute;
/*border-style:solid;
border-color:red;*/
top:134px;
left:800px;
*left:645px;
left:645px\0/;
}
</style>
</head>
<body id="test">
<div id="videos">
<script src="swfobject.js" type="text/javascript"></script>
<script type="text/javascript">
var flashvars = {};
var params = {};
params.wmode = "transparent";
swfobject.embedSWF("???.swf", "videos", "205", "301", "8.0.0", '', flashvars, params);
</script>
</div>
<div id="videoBg"></div>
<script type="text/javascript">
setTimeout("launchFlash()", 7000);
</script>
</body>
It could be done if the flash parts would be yours. This means to make use of External Interface from AS and call JavaScript functions to tell how much is loaded, and ask when to start to play, but it is a non religious way of doing it.

Categories