Using same variable multiple times in HTML - javascript

I have researched this and it seems it is complicated or at least not simple to use a variable declared in JavaScript in an HTML document multiple times.
For instance, I have multiple (hundreds) of div's with IMG statements referencing different JPG files. I want to give a path to those files that is the same on each div, and I want to be able to declare the path text in a variable and use it on each line. This would give me the ability to change the path by just changing the variable. The fact that I would be using it multiple times means that "id=" would not work since it can only be used once.
It is a shame there is not a simple way to do this, as I am sure it would be very useful. An example using an IMG in a DIV would be helpful.
Example:
<div class="column">
<img src="SomePathtoFile/images/1.jpg" class="myimages"
onclick="openModal();currentSlide(1)" class="hover-shadow cursor">
</div>
I want the "SomePathtoFile" to be a variable used in this and all following div's.

I'm not 100% on what you're trying to achieve, but looks on the face of it like a job for data-attributes
You can create them with any name you like: data-link, data-image, data-whatever and then get/set them with JS.
<span class="foo" data-info="nice">
// Get
span.dataset.info
// Set
span.dataset.info = "sweet";
I'd try to dynamically render the value of the attribute on each div at the same time the div and its content/image is generated, which should give you a clear reference to each.
Hope it helps and that I've understood your question!

Try this!
var imgVariable = "https://i.ibb.co/8BQcPn4/1.png"
const nodeList = document.querySelectorAll(".column img");
for (let i = 0; i < nodeList.length; i++) {
nodeList[i].src = imgVariable;
}
<div class="column">
<img src="1.png" alt="first" class="myimages" onclick="openModal();currentSlide(1)" class="hover-shadow cursor" width="50px">
<img src="2.png" alt="second" class="myimages" onclick="openModal();currentSlide(1)" class="hover-shadow cursor" width="50px">
<img src="3.png" alt="third" class="myimages" onclick="openModal();currentSlide(1)" class="hover-shadow cursor" width="50px">
</div>
Thanks and best regards!

I guess you refer to something called scoped variable, it works more js than data attributes, let's see this scoped variable example first (run it)
let arr = 'abcdef'.split('')
arr.forEach(x => createButton(x))
function createButton(x) {
let n = document.createElement('button')
n.innerHTML = x
n.addEventListener('click', () => alert(x))
document.body.append(n)
}
and data attribute example
let arr = 'abcdef'.split('')
arr.forEach(x => createButton(x))
function createButton(x) {
let n = document.createElement('button')
n.innerHTML = x
n.dataX=x
n.addEventListener('click', e => alert(e.target.dataX))
document.body.append(n)
}
div/img is no different than button
let arr = 'abcdef'.split('')
arr.forEach(x => createButton(x))
function createButton(x) {
let d = document.createElement('div')
let n = document.createElement('img')
n.alt = x
n.addEventListener('click', () => alert(x))
d.append(n)
document.body.append(d)
}

Closest I've found is to use render html using js. Using the dollar & curly braces to enclose your var.
<div id="fileList"></div>
<div id="more"></div>
<script type="text/javascript">
// local computer path same as html file
var myPath = "./photos";
var container = document.getElementById('fileList');
var div = document.createElement('div');
var image = `
<img src="${myPath}/frog.jpg" class="myimages"
onclick="openModal();currentSlide(1)" class="hover-shadow cursor">
`;
div.innerHTML = image;
container.appendChild(div);
var otherPath = "https://images.freeimages.com";
var container = document.getElementById('more');
var div = document.createElement('div');
var image2 = `
<img src="${otherPath}/images/large-previews/f41/white-tiger-1362375.jpg" class="myimages"
onclick="openModal();currentSlide(1)" class="hover-shadow cursor">
`;
div.innerHTML = image2;
container.appendChild(div);
</script>

Related

Create multiple div using data from array using for loop

I want to assign array elements to multiple divs which also have image tag in them using for loop.
Array consists of image paths.
var img_list = ["one.png", "two.png", "three.png", "four.png"];
By using above array I have to create below HTML Structure. All divs should be inside "outer" div with a data-slide attribute which is without ".png".
<div id="outer">
<div class="slide" data-slide="one"><img src="Images/one.png" /></div>
<div class="slide" data-slide="two"><img src="Images/two.png" /></div>
<div class="slide" data-slide="three"><img src="Images/three.png" /></div>
<div class="slide" data-slide="four"><img src="Images/four.png" /></div>
</div>
This is what I wrote:
for (var i=0; i < img_list.length; i++){
var container = document.getElementById("outer").innerHTML;
var new_card = "<div class=\"slide\" data-slide=\'" + img_list[i] + "\'><img src=\'Images/" + img_list[i] + "\' /></div>";
document.getElementById("outer").innerHTML = new_card;
}
But it is only showing the last image.
Please help.
Each time your for loop runs, it is replacing the html element within the "outer" div with the current img html.
In order to have it append you can simply change
document.getElementById("outer").innerHTML = new_card;
to
document.getElementById("outer").innerHTML += new_card; so that the element is appended rather than overwritten.
The code at the question overwrites the .innerHTML within the for loop by setting .innerHTML to new_card at every iteration of the array. You can substitute .insertAdjacentHTML() for setting .innerHTML. Also, substitute const for var to prevent new_card from being defined globally. Include alt attribute at <img> element. You can .split() img_list[0] at dot character ., .shift() the resulting array to get word before . in the string img_list[i] to set data-* attribute value.
const img_list = ["one.png", "two.png", "three.png", "four.png"];
for (let i = 0, container = document.getElementById("outer"); i < img_list.length; i++) {
const src = img_list[i];
const data = src.split(".").shift();
const new_card = `<div class="slide" data-slide="${data}"><img src="Images/${src}" alt="${data}"/></div>`;
container.insertAdjacentHTML("beforeend", new_card);
}
<div id="outer"></div>
You are changing the innerHTML you need to add to it. And use Template literals for creating html strings
var img_list = ["one.png", "two.png", "three.png", "four.png"];
const outer = document.getElementById('outer')
img_list.forEach(img => {
outer.innerHTML += `<div class="slider" data-slide="${img.split('.')[0]}"><img src="Images/${img}" /></div>`
})
console.log(outer.innerHTML)
<div id="outer">
</div>
#Tony7931, please replace the last line of for loop with below code:
document.getElementById("outer").innerHTML += new_card;
You are almost there but, every time you are overriding the slider div.
You just have to add + at assignments section. like below.
document.getElementById("outer").innerHTML += new_card;
Here is the full example:
var img_list = ["one.png", "two.png", "three.png", "four.png"];
for (var i=0; i < img_list.length; i++){
var container = document.getElementById("outer").innerHTML;
var new_card = "<div class=\"slide\" data-slide=\'" + img_list[i].split('.')[0] + "\'><img src=\'Images/" + img_list[i] + "\' /></div>";
document.getElementById("outer").innerHTML += new_card;
}
<div id="outer"></div>
You could also use map method of array and Element.innerHTML to get the required result.
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
Demo
const img_list = ["one.png", "two.png", "three.png", "four.png"];
let result = img_list.map((v, i) => `<div class="slide" data-slide="${v.split(".")[0]}"><img src="Images/${v}"/>${i+1}</div>`).join('');
document.getElementById('outer').innerHTML = result;
<div id="outer"></div>
You can declare your variables outside of the loop and reuse them. This is more efficient.
const and let are preferable to var. You only need to set container once so it can be const. new_card should be let since you need to assign it more than once.
You can also use template string so you don't need all the back slashes.
using forEach will make the code cleaner:
const img_list = ["one.png", "two.png", "three.png", "four.png"];
const container = document.getElementById("outer")
let new_card;
img_list.forEach(i => {
new_card = `<div class=slide data-slide='${i.split(".")[0]}'><img src='Images/${i}'></div>`
container.innerHTML += new_card;
})
<div id="outer">
</div>
Alternately, using reduce:
const img_list = ["one.png", "two.png", "three.png", "four.png"];
const container = document.getElementById("outer")
const reducer = (a, i) => a + `<div class=slide data-slide='${i.split(".")[0]}'><img src='Images/${i}'></div>`
container.innerHTML = img_list.reduce(reducer, '')
<div id="outer">
</div>

memory game how to flip current card with set attribute

I'm making a memory game and trying to flip a card to its image value. when I click on the card it should change the image to the current image in the array but for some reason, it's not working.
JS
var faces = []; //array to store card images
faces[0] = 'images/king-of-diamonds.png';
faces[1] = 'images/king-of-hearts.png';
faces[2] = 'images/queen-of-diamonds.png';
faces[3] = 'images/queen-of-hearts.png';
var cardsInPlay = [];
var checkForMatch = function (cardId) {
if (faces[cardId] === faces[cardId + 1]) {
console.log("You found a match!");
} else {
console.log("Sorry, try again.");
}
}
var flipCard = function (cardId, name) {
document.getElementById('image1')[this].getAttribute("id").src = faces[cardId]
checkForMatch();
}
HTML
<div>
<img onclick="flipCard(1,this)" id="image1" src="images/back.png" alt="Queen of Diamonds">
<img onclick="flipCard(2,this)" id="image1" src="images/back.png" alt="Queen of Hearts">
<img id="image3" src="images/back.png" alt="King of Diamonds">
<img id="image4" src="images/back.png" alt="King of Hearts">
</div>
You should avoid using the same id in different elements. Id is thought to be unique and so you should not have more elements with the same id in the entire page.
At this point you can directly do:
var flipCard = function (cardId, name) {
document.getElementById('image1').src = faces[cardId];
checkForMatch();
}

how to change a part of urls using javascript

hi i went to change a part of urls please help me
here's my code
<script>
<!-- javascript -->
</script>
<div class="image">
<img src="https://2.bp.blogspot.com/-UKS5LdO25Gw/VuBJoOR50FI/AAAAAAAARHs/006EudMG_gk/s72-c/j1mini.jpg">
</div>
<div class="image">
<img src="https://1.bp.blogspot.com/-411tLg200L0/VuAH-4z3zqI/AAAAAAAAdYY/0GFl4x7K9bk/s72-c/etoro.jpeg">
</div>
<div class="image">
<img src="https://4.bp.blogspot.com/-wv3KvVVLZwI/VtyYmB6LRUI/AAAAAAAAHV0/a86DOrdL1js/s72-c/Untitled-1.png">
</div>
i went to change the s72 to s300
note : there is many urls
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
var image = images[i];
image.src = image.src.replace('s72', 's300');
}
This is dangerous to do replacement like this. If "s72" occurs elsewhere in the image url other than where you're trying to replace it, things will go bad.
If you're using an IDE or text editor like Sublime, then you can use the Find->Replace->Replace All functionality to change all the s72s to s300s.
I would do this:
function changeSizeImages() {
var images = document.querySelectorAll(".image img");
var total = images.length;
for(var i = 0; i<total; i++) {
images[i].src = images[i].src.replace("s72", "s300");
}
}

Inserting img in a div using another div's background image as a src in JS

there. How can I change my JS code in order to have only one image in my hidden_div? Here is my code.
Best regards.
<div onClick="show(this);" class="img" style="background-ima ge:url('css/images1/img/img1.jpg');background-size:100% 100%;")></div>
<div onClick="show(this);" class="img" style="background-image:url('css/images1/img/img2.jpg');background-size:100% 100%;")></div>
<div onClick="show(this);" class="img" style="background-image:url('css/images1/img/img3.jpg');background-size:100% 100%;")></div>
<div id="hidden_div"></div>
<script>
function show(element) {
var hidden = document.getElementById("hidden_div");
var imgElement = document.createElement("IMG");
imgElement.src=element.style.backgroundImage.replace('url(','').replace(')','');
hidden.appendChild(imgElement);
};
</script>
You make a small change in your script as follows
function show(element) {
var hidden = document.getElementById("hidden_div");
var imgURL = element.style.backgroundImage.replace('url(','').replace(')','');
var imgElement = "<img src='"+ imgURL +"' />
hidden.innerHTML = imgElement;
};
I don't understand very much what do you want, if you can explain to me, please.. But, I think inside of every 'div', in the 'style', there's a extra ) at the end.

how to place a array[i] items in <img src=""> and <a href=""> tags

i have an retrieved array items in the var test,
for example :
var test = img;
Where test[0] holds the value that is grabbed from database as /images/gallery/1.jpp
Now i need to place the var test[0] to be place within img src="" and a href="", so how can i achieve this?
Assign a value to the property "id" of your img and play with its attributes.
<img src="" id="image_id_here" width="300" height="400">
<script>document.getElementById('image_id_here').setAttribute('src', test[0]);</script>
Assumptions made:
"test" is an array of strings
You demand working through a client-sided scripting language such as Javascript to perform front-end operations.
you need a div tag with the id of container:
<div id="container"></div>
You can then use javascript to iterate over the list:
var imgs = "";
for (var i = 0; i < test.length; i++) {
var img = document.createElement('img');
img.setAttribute('src', test[i]);
imgs += img.outerHTML;
}
var container = document.getElementById('container');
container.innerHTML = imgs;
See plunker

Categories

Resources