Setting a the background image of a div from an array - javascript

I have to make a div and set the background image from an array of images, and make a two buttons that will change the picture to the next image in the array, or the previous image of the array. I've been looking around stackoverflow and w3 schools, but I don't know why it's not working.
var backgroundImage = new Array();
backgroundImage[0] = "np.jpg";
backgroundImage[1] = "putin.png";
backgroundImage[2] = "fob.jpg";
function nextImage()
var img = document.getElementById(element);
for(var i = 0; i < backgroundImage.length;i++)
for(var i = 0; i < backgroundImage.length;i++) {
document.getElementById(element).src = [0].src;
document.style.backgroundImage="url(backgroundImage[0])";
}

You are not evaluating the array, you are creating a literal you want
document.style.backgroundImage="url(" + backgroundImage[0] + ")";

Related

How to insert a div tag in more than one location at the same time? [duplicate]

My question is:
Is that possible to add the same element without rewriting the same variable.
I am creating a slider, and i need to append a div with a class slide-el into block slider.
Here is a part of code
var body, html, sliderBody, btnLeft, btnRight, i, parts, vHeight, vWidth;
//Variable definitions
var i = 0,
parts = 3,
//Main html elements
body = document.body,
html = document.element,
//viewport Height and Width
vHeight = window.innerHeight,
vWidth = window.innerWidth,
sliderBody = _id("slider"),
btnLeft = _id("btn-left"),
btnRight = _id("btn-right"),
urls = ["http://www.wallpapereast.com/static/images/pier_1080.jpg",
"http://www.wallpapereast.com/static/images/pier_1080.jpg",
"http://www.wallpapereast.com/static/images/pier_1080.jpg",
"http://www.wallpapereast.com/static/images/pier_1080.jpg"];
slide = _createEl("div");
slide.className += "slide-el";
function _id(el){
return document.getElementById(""+ el +"");
}
function _createEl(el){
return document.createElement(""+ el +"");
}
window.onload = function(){
slideLayout();
}
function slideLayout(){
for(var i=0; i < urls.length; i++){
sliderBody.appendChild(slide);
}
}
The problem is that I can't append the same element that many times. It just creates one element instead of 4.
For you to understand better I made a fiddle:
https://jsfiddle.net/ud7dvn3z/
appendChild will remove the node from wherever it is before appending it to its new location, so you need to make copies of the node instead. You can use cloneNode for that. The true makes cloneNode perform a deep clone, i.e. with all its child nodes.
for(var i = 0; i < urls.length; i++){
sliderBody.appendChild(slide.cloneNode(true));
}
Okey guys! I found an answer. I have to put
slide = _createEl("div");
slide.className += "slide-el";
into for loop.
Now it looks like this:
for(var i=0; i < urls.length; i++){
slide = _createEl("div");
slide.className += "slide-el";
sliderBody.appendChild(slide);
}

I don't how why my backgroundImage doesn't work

Why does my banner doesn't change her background? Please help me.
When I run the file the console tells me:
Uncaught TypeError: flechedroite.addEventListener is not a function
I really don't understand. I'm a beginner in Javascript so please explain me with kind words how I can fix this error :)
var flechedroite = document.getElementsByClassName('fa-arrow-right');
var flechegauche = document.getElementsByClassName('switch-left');
var banner = document.getElementById('banner');
var images = [];
var changeBackground = function (bElement, bUrl) {
return bElement.style.backgroundImage = "url(" + bUrl + ")";
}
//image list
images[0] = 'images/image1.jpg';
images[1] = 'images/image2.jpg';
images[2] = 'images/image3.jpg';
flechedroite.addEventListener('click', function() {
for (var i = 0; i < images.length; i++) {
changeBackground(document.body, images[i]);
}
})
addEventListener should be called in window.onload or in $(document).ready()
Since getElementsByClassName returns an array, you need to use array index with flechedroite to add an event listener. i.e. flechedroite[0].addEventListener('click', function() {...});
You are calling changeBackground function in a loop to set the background image, effectively you will see only the last image from the array being set as background.
JS Code
var images = [];
var changeBackground = function (bElement, bUrl) {
return bElement.style.backgroundImage = "url("+bUrl+")";
}
//image list
images[0] = 'https://www.gettyimages.ie/gi-resources/images/Homepage/Hero/UK/CMS_Creative_164657191_Kingfisher.jpg';
images[1] = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTOGUhZo0Qe81U5qY_Z-seXgsD79LEEet832TVOlLMOEy10ZPsV';
images[2] = 'https://cdn.pixabay.com/photo/2016/06/18/17/42/image-1465348_960_720.jpg';
window.onload = function(){
var flechedroite = document.getElementsByClassName('fa-arrow-right');
var flechegauche = document.getElementsByClassName('switch-left');
var banner = document.getElementById('banner');
var currentImageIndex = 0;
flechedroite[0].addEventListener('click', function() {
currentImageIndex = (currentImageIndex+1)%images.length;
changeBackground(document.body, images[currentImageIndex]);
})
}
The function getElementsByClassName returns a HTMLCollection, which is an array like structure that can contain multiple elements. So you need to use an index to access the elements contained in it.
So flechedroite.addEventListener results in an error but flechedroite[0].addEventListener should work
https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByClassName
if you use 'getElementsByClassName' and you want to add an 'addEventListener', you can not do it in a 'generic' way: "flechedroite.addEventListener ('click', function () {}". You have to do this for each element:
var flechedroite = document.getElementsByClassName('fa fa-arrow-right');
//flechedroite contains all the elements that have the 'fa fa-arrow-right' classes
//on each element you have to add the "addEventListener"
for (var i = 0; i < flechedroite.length; i++) {
flechedroite[i].addEventListener('click', function() {
alert('flechedroite');
});
}
basic example JSFiddle1
a more advanced example
JSFiddle2

How to appendChild(element) many times. (The same element)

My question is:
Is that possible to add the same element without rewriting the same variable.
I am creating a slider, and i need to append a div with a class slide-el into block slider.
Here is a part of code
var body, html, sliderBody, btnLeft, btnRight, i, parts, vHeight, vWidth;
//Variable definitions
var i = 0,
parts = 3,
//Main html elements
body = document.body,
html = document.element,
//viewport Height and Width
vHeight = window.innerHeight,
vWidth = window.innerWidth,
sliderBody = _id("slider"),
btnLeft = _id("btn-left"),
btnRight = _id("btn-right"),
urls = ["http://www.wallpapereast.com/static/images/pier_1080.jpg",
"http://www.wallpapereast.com/static/images/pier_1080.jpg",
"http://www.wallpapereast.com/static/images/pier_1080.jpg",
"http://www.wallpapereast.com/static/images/pier_1080.jpg"];
slide = _createEl("div");
slide.className += "slide-el";
function _id(el){
return document.getElementById(""+ el +"");
}
function _createEl(el){
return document.createElement(""+ el +"");
}
window.onload = function(){
slideLayout();
}
function slideLayout(){
for(var i=0; i < urls.length; i++){
sliderBody.appendChild(slide);
}
}
The problem is that I can't append the same element that many times. It just creates one element instead of 4.
For you to understand better I made a fiddle:
https://jsfiddle.net/ud7dvn3z/
appendChild will remove the node from wherever it is before appending it to its new location, so you need to make copies of the node instead. You can use cloneNode for that. The true makes cloneNode perform a deep clone, i.e. with all its child nodes.
for(var i = 0; i < urls.length; i++){
sliderBody.appendChild(slide.cloneNode(true));
}
Okey guys! I found an answer. I have to put
slide = _createEl("div");
slide.className += "slide-el";
into for loop.
Now it looks like this:
for(var i=0; i < urls.length; i++){
slide = _createEl("div");
slide.className += "slide-el";
sliderBody.appendChild(slide);
}

ondragstart on an array of elements dynamically in javascript

I have an array of image elements,
var im = ["im1","im2"]; // from db or local drive
Then creating the images dynamically as:
var l = imagelist.length;
for (var i = 0; i < l; ++i) {
if (i in im) {
var s = im[i];
var img = document.createElement("img");
img.src = s;
img.width = width;
img.draggable = true;
var body = document.getElementById("body");
body.appendChild(img);
this.addEventListener('ondragstart', function(event) {
alert(event.target.id);
event.dataTransfer.setData('text/plain', event.target.id);
});
}
While the ondragstart event fires, but alert(event.target.id); shows blank.
That's the reason, the drag and drop functionality is not working for an array of images created dynamically .
Although tried dragging with a single image tag <img> which works absolutely fine, but the array of images doesn't work in this way.
Any solution for this?
You haven't assigned an id to any of your elements.
Something like this should do the trick:
var img = document.createElement("img");
img.src = s;
img.id = "image_" + i;
// The rest of your assignments and code...

Break javascript loop

I have following code to use google images search API:
google.load('search', '1');
function searchComplete(searcher) {
// Check that we got results
if (searcher.results && searcher.results.length > 0) {
// Grab our content div, clear it.
var contentDiv = document.getElementById('contentimg');
contentDiv.innerHTML = '';
// Loop through our results, printing them to the page.
var results = searcher.results;
for (var i = 1; i < results.length; i++) {
// For each result write it's title and image to the screen
var result = results[i];
var imgContainer = document.createElement('div');
var newImg = document.createElement('img');
// There is also a result.url property which has the escaped version
newImg.src = result.tbUrl;
imgContainer.appendChild(newImg);
// Put our title + image in the content
contentDiv.appendChild(imgContainer);
The problem is, it gives me 3 image results. How to break a loop and show only the 1st one instead of 3 images?
if I change for (var i = 1; i < results.length; i++) to for (var i = 3; i < results.length; i++) it shows only one image, but image shown is the 3rd one and I need to show 1st one :)
Please advice
Don't use a for loop at all. Just replace all instances of i with 0.
google.load('search', '1');
function searchComplete(searcher) {
// Check that we got results
if (searcher.results && searcher.results.length > 0) {
// Grab our content div, clear it.
var contentDiv = document.getElementById('contentimg');
contentDiv.innerHTML = '';
var result = searcher.results[0];
var imgContainer = document.createElement('div');
var newImg = document.createElement('img');
// There is also a result.url property which has the escaped version
newImg.src = result.tbUrl;
imgContainer.appendChild(newImg);
// Put our title + image in the content
contentDiv.appendChild(imgContainer);
0 means the first item returned (almost all number sequences in programming start at 0!) so all other results will be ignored.
When you only want one element, you don't need a for loop. You can access the first element of an array with
result = results[0];
Arrays are zero-based. So when it contains three images, the images are named results[0], results[1] and results[2].
use break statement. It will terminate the loop once the image is found and hence you will have only the first one.
for (var i = 1; i < results.length; i++) {
// For each result write it's title and image to the screen
var result = results[i];
var imgContainer = document.createElement('div');
var newImg = document.createElement('img');
// There is also a result.url property which has the escaped version
newImg.src = result.tbUrl;
imgContainer.appendChild(newImg);
// Put our title + image in the content
contentDiv.appendChild(imgContainer);
//Berore the end of the loop
if(i==1)
{
break;
}
}

Categories

Resources