Generate array of image in javascript inside <div> - javascript

I need to make the background image in div tag and it has to change automatically, I already put the array of images inside the javascript, but the images is not showing when i'm run the site.The background should behind the menu header.
This is the div
<div style="min-height:1000px;position:relative;" id="home">
below of the div is containing the logo, menu and nav part.
<div class="container">
<div class="fixed-header">
<!--logo-->
<div class="logo" >
<a href="index.html">
<img src="images/logo.png" alt="logo mazmida" height="142" width="242">
</a>
</div>
<!--//logo-->
This is the javascript
<script>
var imgArray = [
'images/1.jpg',
'images/2.jpg',
'images/3.jpg'],
curIndex = 0;
imgDuration = 2000;
function slideShow() {
document.getElementID('home').src = imgArray[curIndex];
curIndex++;
if (curIndex == imgArray.length) { curIndex = 0; }
setTimeout("slideShow()", imgDuration);
}
slideShow();

You have a few issues with your script. I've made a live JSbin example here:
https://jsbin.com/welifusomi/edit?html,output
<script>
var imgArray = [
'https://upload.wikimedia.org/wikipedia/en/thumb/0/02/Homer_Simpson_2006.png/220px-Homer_Simpson_2006.png',
'https://upload.wikimedia.org/wikipedia/en/thumb/0/0b/Marge_Simpson.png/220px-Marge_Simpson.png',
'https://upload.wikimedia.org/wikipedia/en/a/aa/Bart_Simpson_200px.png'
];
var curIndex = 0;
var imgDuration = 1000;
var el = document.getElementById('home');
function slideShow() {
el.style.backgroundImage = 'url(' + imgArray[curIndex % 3] + ')';
curIndex++;
setTimeout("slideShow()", imgDuration);
}
slideShow();
</script>
There are a few issues with your script:
On the element since it's a div not an img, you need to set style.backgroundImage instead of src. Look at https://developer.mozilla.org/en-US/docs/Web/CSS/background for other attributes to related to background image CSS
Also it's document.getElementById
Optimizations
And you can use mod % trick to avoid zero reset
Use setInterval instead of setTimeout
Further optimzations
Use requestAnimationFrame instead of setTimeout/setInterval
I suggest getting familiar with your browser debugging tools which would help identify many of the issues you face.

document.getElementID('home').src = imgArray[curIndex]
You are targeting a div with an ID of home, but this is not an Image element (ie ,
But since you want to alter the background colour of the DIV, then you use querySelector using javascript and store it in a variable, then you can target the background property of this div (ie Background colour).
I hope this helps.

You are trying to change the src property of a div, but divs do not have such property.
Try this:
document.getElementById('home').style.backgroundImage = "url('" + imgArray[curIndex] + "')"
This changes the style of the target div, more precisely the image to be used as background.

As you want to change the background image of the div, instead of document.getElementID('home').src = imgArray[curIndex] use
document.getElementById("#home").style.backgroundImage = "url('imageArray[curIndex]')";
in JavaScript or
$('#home').css('background-image', 'url("' + imageArray[curIndex] + '")'); in jquery.

To achieve expected result, use below option of using setInterval
Please correct below syntax errors
document.getElementID to document.getElementById
.src attribute is not available on div tags
Create img element and add src to it
Finally use setInterval instead of setTimeout outside slideShow function
var imgArray = [
'http://www.w3schools.com/w3css/img_avatar3.png',
'https://tse2.mm.bing.net/th?id=OIP.ySEgAgJIlDQsIQTu_MeoLwHaHa&pid=15.1&P=0&w=300&h=300',
'https://tse4.mm.bing.net/th?id=OIP.wBAPnR04OfXaHuFI9Ny2bgHaE8&pid=15.1&P=0&w=243&h=163'],
curIndex = 0;
imgDuration = 2000;
var home = document.getElementById('home')
var image = document.createElement('img')
function slideShow() {
if(curIndex != imgArray.length-1) {
image.src = imgArray[curIndex];
home.appendChild(image)
curIndex++;
}else{
curIndex = 0;
}
}
setInterval(slideShow,2000)
<div style="position:relative;" id="home"></div>
code sample - https://codepen.io/nagasai/pen/JLKvME

Related

Generate html using Javascript

I have a gallery page that is updated often with new images. I use simple HTML to post the photos. My process currently is copy and paste the set of tags for a photo and change the number to correspond with the image file name. E.G. I change the number 047 to 048. Copy-Paste, change it to 049. This goes on until I have reached the number of additional photos. As you can see, this is very inefficient and there must be a better way of doing this. I was wondering if there is a simpler way to achieve this with Javascript? Perhaps generate additional tags by inputing a certain number or range?
Any ideas that would make this process efficient are welcomed please! Thank you!
<div class="cbp-item trim">
<a href="../assets/images/trim/img-trim-047.jpg" class="cbp-caption cbp-lightbox" data-title="">
<div class="cbp-caption-defaultWrap">
<img src="../assets/images/trim/img-trim-047.jpg" alt="">
</div>
</a>
</div>
You could use a templating solution. There are several libraries for that, but you can also implement it yourself.
Here is one way to do that:
Put the HTML for one image in a script tag that has a non-standard language property so the browser will just ignore it
Put some keywords in there that you'll want to replace, e.g. {url}. You can invent your own syntax.
Read that template into a variable
In the JS code, put all the images' URLs in an array of strings
For each element in that array, replace the keywords in the template string with that particular URL, and concatenate all these resulting HTML snippets.
Inject the resulting HTML into the appropriate place in the document.
Here is a snippet doing that:
// Add new images here:
var images = [
"https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/330px-SNice.svg.png",
"https://nettemarie357.files.wordpress.com/2014/09/smiley-face.jpg?w=74&h=74",
];
// Load the template HTML
var template = document.querySelector('script[language="text/template"]').innerHTML;
// Use template to insert all the images:
container.innerHTML = images.map(url => template.replace(/{url}/g, url)).join('');
img { max-width: 50px }
<div id="container"></div>
<script language="text/template">
<div class="cbp-item trim">
<a href="{url}" class="cbp-caption cbp-lightbox" data-title="">
<div class="cbp-caption-defaultWrap">
<img src="{url}" alt="">
</div>
</a>
</div>
</script>
This would help you creating it programatically:
var new_row = document.createElement('div');
new_row.className = "cbp-item trim";
var a = document.createElement('a');
a.href = "../assets/images/trim/img-trim-047.jpg";
a.className= "cbp-caption cbp-lightbox";
document.body.appendChild(a);
var div = document.createElement('div');
div.className = "cbp-caption-defaultWrap";
var img = document.createElement('img');
img.src= "../assets/images/trim/img-trim-047.jpg";
div.appendChild(img);
a.appendChild(div);
new_row.appendChild(a);
If it is just about printing HTML, I suggest you to use plugins like Emmet for Sublime Text editor.
When you install this plugin and see how it works, you can simple create a complex html in a way that 'for' loop would do this. This will help you to change only the image/link number of every item.
Check the demo in the link, that I added.
Here's an example in Java Script that will generate the html you will need. Set the total to whatever number you need to generate the number of images you want.
var total = 47;
var hook = document.getElementById('hook');
// Main Node for SlideShow
var node = document.createElement('div');
node.classList = "cbp-item trim";
// Work out the correct number
var n = function(int) {
var length = int.toString().length;
return length === 1
? '00' + int
: length === 2
? '0' + int
: length
}
// Create the item
var createItem = function(int){
// Create Anchor
var a = document.createElement('a');
a.href = '../assets/images/trim/img-trim-' + ( n(int) ) + '.jpg" class="cbp-caption cbp-lightbox';
a.classList = 'cbp-caption cbp-lightbox';
// Create Div
var div = document.createElement('div');
div.classList = 'cbp-caption-defaultWrap';
// Create Image
var img = document.createElement('img');
img.src = '../assets/images/trim/img-trim-' + ( n(int) ) + '.jpg';
img.alt = 'gallery image';
// Finalise Dom Node
var container = div.appendChild(img)
a.appendChild(div);
// Return Final Item
return a
}
// Create Items
for (var i = 1; i < total + 1; i++) {
node.appendChild(createItem(i));
}
// Append Main Node to Hook
hook.appendChild(node);
<div id="hook"></div>

Can you generate html locally, without using a server?

I'm trying to show images in a local html file using a loop. This is what I want it to show in the web browser:
<div id="polybridges">
<img src="polybridge_1.gif">
<img src="polybridge_2.gif">
<img src="polybridge_3.gif">
<img src="polybridge_4.gif">
<img src="polybridge_5.gif">
</div>
This is my attempt to do this with javascript:
<script>
for(var i = 1; i <= 5; i++) {
var elem = document.createElement("img");
elem.src='polybridge_'+i+'.gif';
document.getElementById("polybridges").appendChild(elem);
}
</script>
<div id="polybridges">
This doesn't generate anything. Is there a way to show images in a loop without using a server / localhost?
At first your element must be defined before script execution (so change the order). I suppose you want to append elem (instead of "hallo" string):
<div id="polybridges"></div>
<script>
for(var i = 1; i <= 5; i++) {
var elem = document.createElement("img");
elem.src='polybridge_'+i+'.gif';
document.getElementById("polybridges").appendChild(elem);
}
</script>
Put your images in the same directory as your html file.
for(var i = 1; i <= 5; i++) {
var elem = document.createElement("img");
elem.src='polybridge_'+i+'.gif';
document.getElementById("polybridges").appendChild(elem);
}
And change the argument for appendChild.
As malix states in his comment, you should use document.getElementById("polybridges").appendChild(elem); instead of document.getElementById("polybridges").appendChild("hallo"); (so append the element instead of string "hallo").
And, as the rest states, the images should be where you tell the browser they are.
Yes you can display images without server, you have to have that images in same directory as your html file or in images folder which in same level as your html file ( for that case images would be available as <img src="images/polybridge_5.gif">
appendChild take Node as parameter (not string)
for(var i = 1; i <= 5; i++) {
var elem = document.createElement("img");
elem.src='polybridge_'+i+'.gif';
document.getElementById("polybridges").appendChild(elem);
}
You need to take care of one thing. You are trying to get element by ID. So you need to make sure that html is valid. Provide proper close tag for the element. Also use the elem variable in the appendChild().
for (var i = 1; i <= 5; i++) {
var elem = document.createElement("img");
elem.src = 'polybridge_' + i + '.gif';
console.log(elem)
document.getElementById("polybridges").appendChild(elem);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="polybridges"></div>

Dynamically change <div> background-image with javascript

I'm looking for some help writing a javascript snippet that will DYNAMICALLY update a div style= "background-image:url..." to match the a href above it. This is on a portfolio website, so this is a gallery where all the images are live at once. I need the snippet to run through each individual a href and nested div underneath it and have them match, unique to each image (Don't want a page of the same picture 20 times)
I'm just starting to learn JS, so I've been struggling with this one. Here's the html.
<a id ="tobematched" href="imgs/galleryphotos/1.jpg">
This href should from above should be copied to the div style url below.
<div id ="matcher" class="img-container" style="background-image: url('imgs/notcorrect/currently.jpg');"></div>
</a>
This is what it looks like as a whole...
<a id ="tobematched" href="imgs/galleryphotos/1.jpg">
<div id ="matcher" class="img-container" style="background-image: url('imgs/notcorrect/currently.jpg');"></div>
</a>
Any help would be greatly appreciated!
This is what I'm thinking, so far...
function abc() {
var a = document.getElementById("tobematched").
var b = document.getElementById("matcher").style.backgroundImage;
}
Not sure where to go from here, since I don't know how to grab the href... I think I'm on the right track.
You can use a combination of querySelector() and the .href property to get what you need:
var targetDiv = document.querySelector('#matcher');
var url = targetDiv.parentNode.href;
targetDiv.style.backgroundImage = 'url(' + url + ')';
Alternatively you can use:
var url = document.querySelector('#tobematched').href
This second option does not depend on the structure of the document, but causes JS to look through the whole document again.
If you were using jQuery:
var url = $('#tobematched')attr('href');
$('#matcher').css('background-image', 'url(' + url + ')');
Live Example
Edit: As per the further description by OP in the comments, here is the code you actually need:
var targetDivs = document.querySelectorAll('.img-container');
for (var i = 0; i < targetDivs.length; i++) {
var url = targetDivs[i].parentNode.href;
targetDivs[i].style.backgroundImage = 'url(' + url + ')';
}

Showing random divs images every time page is load

Lets say I have these images gallery, how do i randomly display the images everytime when i reload the page?
http://creativepreviews.com/fiddle/study/20131007/
Let's say the image will display in the background of the DIV, then the following should do it.
// JS
var imgArray = ["img1.jpg", "cat.jpg", "sky.jpg"]
function randomBg() {
x = Math.random()
y = Math.round(x * 10)
if (imgArray[y] != undefined) {
document.getElementById("blah").style.backgroundImage = "url('" + imgArray[y] + "')"
} else {
document.getElementById("blah").style.backgroundImage = "url('default.jpg')"
}
}
...and the HTML.
<script src="test.js"></script>
<body onload="randomBg()">
<div id="blah"></div>
...or you could replace the style.backgroundImage in the JS with innerHTML = <img src=" etc...
You could do something along these lines (not tested)
var grd = $('#grid');
var imgs = grd.children();
imgs.sort(function(){return (Math.round(Math.random()) - 0.5);});
grd.remove('li');
for(var i=0;i < imgs.length;i++) grd.append(imgs[i]);
In essence what we are doing is getting all the li elements in 'grid' into an array, randomizing them, removing them all from 'grid' and then putting them back in again.
If you had supplied a working fiddle rather than a link to the finished article it would be easier to modify it and provide a more complete solution.

Javascript gallery with prev/next function AND thumbnail... nothing else

Short of going for something like Galleriffic
and modifying, hiding and removing elements, what would be a way to add a function by which thumbnails can also be clicked to display the image?
Much obliged to anyone who can point me in the right direction. I'm using the following by Paul McFedries at mcfedries.com.
<script type="text/javascript">
<!--
// Use the following variable to specify
// the number of images
var NumberOfImages = 3
var img = new Array(NumberOfImages)
// Use the following variables to specify the image names:
img[0] = "yellow1.jpg"
img[1] = "blue2.jpg"
img[2] = "green3.jpg"
var imgNumber = 0
function NextImage()
{
imgNumber++
if (imgNumber == NumberOfImages)
imgNumber = 0
document.images["VCRImage"].src = img[imgNumber]
}
function PreviousImage()
{
imgNumber--
if (imgNumber < 0)
imgNumber = NumberOfImages - 1
document.images["VCRImage"].src = img[imgNumber]
}
</script>
in the html:
<div class="galleryarrows">
<A HREF="javascript:PreviousImage()">
<IMG SRC="previous.png" BORDER=0></A>
<A HREF="javascript:NextImage()">
<IMG SRC="next.png" BORDER=0></A>
</div>
A quick, basic solution: Save the full size versions of your images in a folder called say, 'full_images', with the same names as the thumbnails.
Add an onClick event into the element img elements that display your thumbnails in the html, so they look something like this.
<img src = "yellow1.jpg" name = "thumb[0]" style = "cursor:pointer" onClick = "Javascript:DisplayImage(0);" alt = "yellow"/>
<img src = "blue2.jpg" name = "thumb[1]" style = "cursor:pointer" onClick = "Javascript:DisplayImage(1);" alt = "blue"/>
<img src = "green3.jpg" name = "thumb[2]" style = "cursor:pointer" onClick = "Javascript:DisplayImage(2);" alt = "green"/>
In your javascript, add this function
function DisplayImage(id){
imgNumber = id;
document.images["VCRImage"].src = "full_images/" + img[id];
}
This will display in an element with the name 'VCRImage'.
Not my favourite solution this, but quick, and should work. If Javascript is new to you, then you might as well check out jQuery. It's a lot easier to use, and is way more cross-browser compatible.

Categories

Resources