Javascript, make random_generated image as background - javascript

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>

Related

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;
}

simple advert changer - each() loop won't delay()

I am trying to create advertisement box which simply changes picture after given time. I used each() loop to hide and display images one after another but all i get is same time effect on all pictures. Any clue how to fix that ?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
<link rel="stylesheet" type="text/css" href="advert.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<style>
.advert{
position: relative;
}
.advert img{
position: absolute;
/*visibility: hidden;*/
}
</style>
</head>
<body>
<div class="advert">
<img src="img/img1.jpg" alt="Smiley face" height="" width="">
<img src="img/img2.jpg" alt="Smiley face" height="" width="">
<img src="img/img3.jpg" alt="Smiley face" height="" width="">
</div>
</body>
<script>
$(function(){
function simpleAdvert(){
var section = $('.advert');
var images = section.find('img');
images.each(function(){
$( this ).fadeToggle(5000).fadeToggle(5000).delay(10000);
console.log($( this ));
});
}
simpleAdvert();
});
</script>
</html>
.each(function) calls the function for each item in the array immediately, which is why the time effect is applied to all items rather than doing what you expect. To get the pictures to show/hide in a loop you need something like a setInterval which calls a function repeatedly. This should work:
$(function(){
var timeToShow = 750;
var timeToFade = 250;
var timeTotal = timeToShow + timeToFade;
function simpleAdvert(){
var section = $('.advert');
var images = section.find('img');
var index = 0;
images.hide();
$(images[0]).show();
setInterval(function() {
var next = (index + 1) % images.length;
$(images[index]).fadeToggle(timeToFade);
$(images[next]).fadeToggle(timeToFade);
index = next;
}, timeTotal);
}
simpleAdvert();
});
Essentially this hides all images except the first, then fades out the shown picture and fades in the next picture on an interval.
You should call the delay before the fadeToggle method and if you want to show the images one by one you can use the index of the element in the set:
// using fadeIn() method
images.each(function(index) {
// since the indices are zero-based
// the first element is shown without delay
// you can add 1 to the index: 10000 * ++index
$(this).hide().delay(10000 * index).fadeIn(5000);
A suggestion:
function simpleAdvert() {
var section = $('.advert');
var images = section.find('img').hide();
images.each(function(index) {
$(this).delay(10000 * index).fadeIn(5000);
});
}
It's a small extension to working script by concrete_d (Accepted answer).
+ custom time delay with no animation
+ and random slide on the script start
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
<link rel="stylesheet" type="text/css" href="advert.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<style>
.advert{
position: relative;
}
.advert img{
position: absolute;
}
</style>
</head>
<body>
<div class="advert">
<img src="img/img1.jpg" alt="Smiley face" height="" width="">
<img src="img/img2.jpg" alt="Smiley face" height="" width="">
<img src="img/img3.jpg" alt="Smiley face" height="" width="">
</div>
</body>
<script>
$(function(){
var timeToShow = 500;
var timeDelay = 5000;
var timeToFade = 500;
var timeTotal = timeToShow + timeToFade + timeDelay;
var minimum = 0;
var maximum = $('.advert').find('img').length - 1;
var randomnumber = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
console.log(randomnumber);
function simpleAdvert(){
var section = $('.advert');
var images = section.find('img');
var index = randomnumber;
images.hide();
$(images[randomnumber]).show().delay(timeDelay);
setInterval(function() {
var next = (index + 1) % images.length;
$(images[index]).fadeToggle(timeToFade);
$(images[next]).fadeToggle(timeToFade);
index = next;
}, timeTotal);
}
simpleAdvert();
});
</script>
</html>

Random background change upon refresh

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>

Removing appended child on click

I am using the following to create an image popup on site load -
<script type="text/javascript">
function showPopup()
{
var div = document.createElement('div');
div.className += 'popup';
div.innerHTML = "<img src='startbutton.png' width='400' height='293' >"
document.body.appendChild(div);
}
window.onload = showPopup;
And here is the CSS
<style type="text/css">
.popup{
position:absolute;
width: 0px;
height: 0px;
left:40%;
top:30%;
}
How can I modify this so that the image goes away when clicked?
Is it possible to have the rest of the page "fade out" till the image is clicked?
Similar to a modal dialog box.
function showPopup() {
var div = document.createElement('div');
var cover = document.createElement('div');
var image = document.createElement('img');
image.src = 'startbutton.png';
image.width = 400;
image.height = 293;
cover.style.position = 'fixed';
cover.style.background = 'rgba(0,0,0,0.5)';
cover.style.height = '100%';
cover.style.width = '100%';
cover.style.top = '0';
cover.style.left = '0';
div.className = 'popup';
div.style.position = 'fixed';
div.style.top = '50%';
div.style.left = '50%';
div.style.margin = '-200px 0 0 -146px';
div.appendChild(image);
image.onclick = function() {
div.parentNode.removeChild(div);
cover.parentNode.removeChild(cover);
}
document.body.appendChild(cover);
document.body.appendChild(div);
}
window.onload = showPopup;
FIDDLE
Add an Action Listener to the DOM element
<!DOCTYPE html>
<html>
<head>
<title>Removable</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<style>
</style>
<script>
function main() {
var image = document.getElementById("myImage");
image.addEventListener("click", function() {
image.parentNode.removeChild(image);
});
}
window.onload = main;
</script>
</head>
<body>
<div>
<img src="../img/dice.png" alt="dice" id="myImage">
</div>
</body>
</html>
This is how I would do it, instead of messing with the javascript, it's a lot easier with the jQuery. And since you tagged jQuery, I'm providing what I think would work best.
$(document).ready(function() {
$('<div class="overlay" style="position: absolute; left: 0; right: 0; top: 0; bottom: 0; background: rgba(0, 0, 0, .5);">').appendTo('body');
$('<div class="popup" style="z-index: 8888;"><img src="startbutton.png" width="400" height="29" /></div>').appendTo('body');
$('.popup').on('click', function() {
$('.popup, .overlay').remove();
});
});

Get name of dynamically created div in javascript?

I cannot seem to make my javascript .click() method work with my dynamically created divs. In this code I have divs created each under the class name "class1" but my click method does not seem to detect their existence. Here is my code:
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" media="screen" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
function populate() {
var select = document.getElementById("centres");
for (var i = 1; i <= 10; i++) {
var option = document.createElement("option");
option.value = i;
option.text = i;
select.appendChild(option);
}
}
function divGenerator() {
var div;
for (var i = 1; i <= document.getElementById("centres").selectedIndex + 1; i++) {
div = document.createElement("div");
div.className = "class1";
div.innerHTML = "Space " + i;
div.style.width = "100px";
div.style.height = "100px";
div.style.float = "left";
document.getElementById("container2").appendChild(div);
}
}
function glassLoad() {
path_to_root_dir = "../../Content/";
var myBox = new GlassBox();
myBox.init('myBox', '128px', '62px', 'hidden');
myBox.apos('170px', '150px');
}
// window.onload = populate;
$(function () {
$("container2").on("click", ".class1", function () {
alert("The div was clicked.");
});
});
</script>
<div id="container1" style="width: auto; height: 50px;">
<div id="myBox">Hello World!</div>
<button style="margin: auto; vertical-align: top; float: left; font-size: 16px;" type="button" onclick="divGenerator();">Generate</button>
#Html.DropDownList("centres")
</div>
<div id="container2" style="margin: 10px; float: left;" />
<head>
<script type="text/javascript" src="../../Content/javascripts/glassbox/glassbox.js"></script>
<style type="text/css">
#myBox #myBox_content {
padding: 2px;
font-family: verdana, arial, helvetica;
font-size: 12px;
}
</style>
<title></title>
</head>
<body>
<!--
popup
-->
</body>
And here is what it returns (taken from google chrome):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta name="description" content="Description of your web page goes here." />
<meta name="keywords" content="Keywords for you web page go here. Each keyword or group of keyword phrases are separated by a comma. Keep this list short and relevant to the content and title of this specific page." />
<title>OneEighty Asset Manager
</title>
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<div id="header">
<div id="logo">
<p></p>
</div>
</div>
<!-- end #header -->
<div id="menu">
<ul>
<li>Home</li>
<li>About</li>
</ul>
</div>
<!-- end #menu -->
<div id="wrapper">
<div class="btm">
<div id="page">
<h1>
<img src="../../Content/Images/1Eighty.png" alt="" style="height: 100px; width: 750px;" /></h1>
<div id="content">
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" media="screen" />
<script type="text/javascript">
function populate() {
var select = document.getElementById("centres");
for (var i = 1; i <= 10; i++) {
var option = document.createElement("option");
option.value = i;
option.text = i;
select.appendChild(option);
}
}
function divGenerator() {
var div;
for (var i = 1; i <= document.getElementById("centres").selectedIndex + 1; i++) {
div = document.createElement("div");
div.className = "class1";
div.innerHTML = "Space " + i;
div.style.width = "100px";
div.style.height = "100px";
div.style.float = "left";
document.getElementById("container2").appendChild(div);
}
}
function glassLoad() {
path_to_root_dir = "../../Content/";
var myBox = new GlassBox();
myBox.init('#myBox', '128px', '62px', 'hidden');
myBox.apos('170px', '150px');
alert("div clicked");
}
// window.onload = populate;
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#container2").on("click", ".class1", function () {
path_to_root_dir = "../../Content/";
var myBox = new GlassBox();
myBox.init('#myBox', '128px', '62px', 'hidden');
myBox.apos('170px', '150px');
alert("div clicked");
});
});
</script>
<div id="container1" style="width: auto; height: 50px;">
<button style="margin: auto; vertical-align: top; float: left; font-size: 16px;" type="button" onclick="divGenerator();">Generate</button>
<select id="centres" name="centres"><option>Southdale</option>
<option>Sasolburg</option>
<option>Sandton City</option>
<option>Greenstone</option>
<option>Morningside</option>
<option>Easgate</option>
<option>Bedfordview</option>
<option>Fourways</option>
<option>Linksfield Terrace</option>
<option>Carlton Centre</option>
<option>testcentre1</option>
<option>testcentre2</option>
<option>testcentre3</option>
</select>
</div>
<div id="container2" style="margin: 10px; float: left;" />
<head>
<script type="text/javascript" src="../../Content/javascripts/glassbox/glassbox.js"></script>
<style type="text/css">
#myBox #myBox_content {
padding: 2px;
font-family: verdana, arial, helvetica;
font-size: 12px;
}
</style>
<title></title>
</head>
<body>
<!--
popup
-->
</body>
</div>
<!-- end #content -->
<div style="clear: both;">
</div>
</div>
<!-- end #page -->
</div>
</div>
<div id="footer">
<p>
Copyright (c) 2009 1eightyintra.com. All rights reserved.
</p>
</div>
<!-- end #footer -->
</body>
</html>
Because the element doesn't exist in the DOM on page load, you need to use an event delegate, such as on:
$(function () {
$("body").on("click", ".class1", function () {
alert("The div was clicked.");
});
});
Or for pre-1.7 jQuery, use delegate:
$(function () {
$("body").delegate(".class1", "click", function () {
alert("The div was clicked.");
});
});
click only binds handlers to elements that were present in the DOM when you called it.
Instead, use the jQuery on method:
$(document).ready(function () {
$("body").on("click", ".class1", function () {
alert("The div was clicked.");
});
});
You will need to re-apply the click handler to the newly created divs.

Categories