Dynamically change <div> background-image with javascript - 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 + ')';
}

Related

DOM background-Image add

I'm a beginner.
I encounter a small problem which is I cannot add an image to my div block.
here is my HTML code
<span class = 'memepic'>
<img src ="https://encryptedtbn0.gstatic.com/imagesq=tbn:ANd9GcTmvCGIVavqB6jVObiS1sqkvwlzYgpjCVfWBg&usqp=CAU">
</span>
and I wrote my js code is like this one
//it is my <span> id
const img = document.getElementsByClassName('memepic')
//it is my divblock id
const memebox = document.querySelector('#meme')
for(i of img){
i.addEventListener("click", function(e) {
console.log(e)
memebox.style.backgroundImage = 'url("e.path[0].currentSrc")';
});
}
the error shows my console is
e.path[0].currentSrc:1 GET file:///C:/Users/kevin/Desktop/bootcamp/officialclass/meme%20generator/e.path[0].currentSrc net::ERR_FILE_NOT_FOUND
my purpose is when I click that picture, that picture will show on my divblock which is in the center of the screen.
I checked the path[0].currentSrc is correct.
and it will show the picture if I replace 'e.path[0].currentSrc' to the content inside the 'e.path[0].currentSrc'.
like this
memebox.style.backgroundImage = 'url("https://encryptedtbn0.gstatic.com/imagesq=tbn:ANd9GcTmvCGIVavqB6jVObiS1sqkvwlzYgpjCVfWBg&usqp=CAU");
Hey can you try this code in for loop :
`url(${e.srcElement.currentSrc})`
Javascript doesn't parse variables that are inside a string, so you're asking for the background URL to literally be set as "e.path[0].currentSrc".
Instead of this:
memebox.style.backgroundImage = 'url("e.path[0].currentSrc")';
Do this:
memebox.style.backgroundImage = 'url("' + e.path[0].currentSrc + '")';

Generate array of image in javascript inside <div>

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

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>

Fade In don't work

I have wrote this javascript to show some images with id: imgFotogramma1/imgFotogramma2/ecc.. randomly in 8 different div with id Fotogramma1/Fotogramma2/ecc..:
function rullino() {
var immagini = new Array("strutture/1.jpg", "strutture/2.jpg", "strutture/3.jpg", "strutture/4.jpg", "strutture/5.jpg", "strutture/6.jpg", "strutture/7.jpg", "strutture/8.jpg", "strutture/9.jpg");
for (i = 1; i < 9; i++) {
var x = Math.floor(immagini.length * Math.random(1));
var imgId = "imgFotogramma" + i;
$(function () {
$(imgId).fadeIn(1000);
src = $(imgId).attr('src');
src = immagini[x];
alert(src);
});
}
setInterval("rullino()", 4000);
};
Now,this code start when body is loaded and its repeated every 4 seconds but i don't understand why the images are not displayed. I have started to work with Jquery not too much time ago and probably something are wrong.
I want to specify that: if i use normally javascript to assign to the src attribute the value of immagini[x],all work fine and the images are displayed.I have problem only to apply the fadein() motion.
I need a help to understand where is wrong,i have studied the fadeIn() API and i have tried to apply to my case.
Thanks in advance to anyone want to help me.
$(imgId).fadeIn(1000);
should be:
$('#'+imgId).fadeIn(1000);
Use # + idOfElemnt to select element with particular id.
You already doing it right. Just replace
var imgId = "imgFotogramma"+i;
With
var imgId = "#imgFotogramma"+i;
Since your are using the ID of the image, then your must have to use the "#" for id for applying the jQuery on it.
To select an ID, use # + elemID. Like this:
var imgId = "#imgFotogramma" + i;
Also, fade will not occur if the element is not hidden. First hide it, and then fade it in:
$(imgId).hide().fadeIn(1000);

Create JavaScript fill href based upon var

I'm using a lovely Lightbox plugin that requires the following piece of code per image
<a href="images/portfolio/full/1.jpg"
data-target="flare"
data-flare-plugin="shutter"
data-flare-scale="fit"
data-flare-gallery="portfolio"
data-flare-thumb="images/portfolio/thumbs/1.jpg"
data-flare-bw="images/portfolio/bw/1.jpg"
class="kleur multiple">
<img src="images/portfolio/thumbs/1.jpg" width="375px" height="250px" />
</a>
And I would like to write, together with some of you, a piece of Javascript/jQuery script that elminates writing some of the lines of the above piece of code.
Let me explain: The
- full image (href),
- blackwhite version (data-flare-bw=""),
- lightbox thumb (data-flare-thumb="")
- and the page thumb (<img src=""/>)
all have one thing in common: The filename is identical, only the path differs from eachother. So I would like to write/have a script that, based upon a var it automatically writes those lines of code. Not only the SRC, but also the attribute itself, so the href="", data-flare-bw="", data-flare-thumb="" and the <image src=""/>
As I'm not a Jquery master, i'll try to write down the code that, I'd think somewhat give you guys an idea of what should come:
$function(InsertAttributesAutomaticcly() {
var filenames = $('#container a').attr('data-flare-title', this')
$('#container a').each(function() {
$(this).append('href', 'images/portfolio/full/' + 'filenames' + '.jpg');
$(this).append('data-flare-bw', 'images/portfolio/blackwhite/' + 'filenames' + '.jpg');
$(this).append('data-flare-thumb', 'images/portfolio/thumb/' + 'filenames' + '.jpg');
$(this).html('<img src=" 'images/portfolio/thumb/' + 'filenames' + '.jpg'">');
});
});
Let me explain the code:
It searches within #container for a and then appends the href, data-flare-thumb, data-flare-bw tag to it, with the src/url/href image location, which would be + var (identical to data-flare-title="") + .jpg.
After inserting those three attributes, it inserts a <img> within the a tag, with an src of <path> + var (as before) + '.jpg'
I'm pretty sure this isn't that hard to write, but I'm not that skilled to create a working piece of script, sadly.
Thanks guys!
Bonus task: Those who succesfully write a piece of code above, including a script that tracks the size of the thumb (width + height) and writes that, next to the , will get a beer from me!
Granted that you have such links for example:
<div id="container">
</div>
This would be a viable approach:
$(function(){
$('#container a').each(function(){
var $link = $(this),
title = $link.data('flare-title');
$link.attr('href', 'images/portfolio/full/' + title);
$link.attr('data-flare-bw', 'images/portfolio/blackwhite/' + title);
$link.attr('data-flare-thumb', 'images/portfolio/thumbs/' + title);
$link.append($('<img>', {
src : 'images/portfolio/thumbs/' + title,
width : '375px',
height : '250px'
}));
});
});
Edit: see fiddle.

Categories

Resources