How to add HTML append javascript... "quotation marks" problems - javascript

I'm trying to transform div content from img to div strong
for example
<div class="multi-gallery-image show" id="service_preview">
<img alt="image" src="チャイルドカット¥3000">
<img alt="image" src="ジュニアカット">
<img alt="image" src="ハナコカット">
<img alt="image" src="Hair Styling">
<img alt="image" src="Manicures">
<img alt="image" src="Hair Coloring">
</div>
I want to transform to div strong
<div class="multi-gallery-image show" id="service_preview">
<div><strong>チャイルドカット¥3000</strong></div>
<div><strong>ジュニアカット</strong></div>
<div><strong>トップスタイリストカット</strong></div>
<div><strong>Hair Styling</strong></div>
<div><strong>Manicures</strong></div>
<div><strong>Hair Coloring</strong></div>
</div>
I have this but the result is different as expected:
let servicePreview = document.getElementById('service_preview'); //parent where I am trying to introduce the src values
let myImg;
let mySrc;
let toPush;
if (servicePreview.getElementsByTagName('img').length > 0){
let servicesNumber = servicePreview.getElementsByTagName('img').length; //number of img tags inside the service_preview
for (let i = 0; i < servicesNumber; i++){
myImg = servicePreview.getElementsByTagName('img')[i]; //capturing the img tag
mySrc = myImg.getAttribute('src'); //capturing the src value from img tag
toPush = '<div><strong>' + mySrc + '</strong></div>'; //creating html tag for push to the parent service_preview
servicePreview.append(toPush); //appending the html tag
}
}
but the result of this is
<div class="multi-gallery-image show" id="service_preview">
<img alt="image" src="チャイルドカット¥3000">
<img alt="image" src="ジュニアカット">
<img alt="image" src="ハナコカット">
<img alt="image" src="トップスタイリストカット">
<img alt="image" src="Hair Styling">
<img alt="image" src="Manicures">
"<div><strong>チャイルドカット¥3000</strong></div>"
"<div><strong>ジュニアカット</strong></div>"
"<div><strong>ハナコカット</strong></div>"
"<div><strong>トップスタイリストカット</strong></div>"
"<div><strong>Hair Styling</strong></div>"
"<div><strong>Manicures</strong></div>"
</div>
I want to delete that "quotes" on every div strong, that is a string.
I have to delete the complete img tag after solve the "quotes"
problem

use createElement to create dom element to appendChild and removeChild to remove elements.
let servicePreview = document.getElementById('service_preview');
var myImg;
var mySrc;
let toPush;
var elements = servicePreview.getElementsByTagName('img');
while (elements[0]) {
newDiv = document.createElement('div');
newStrong = document.createElement('strong');
newStrong.innerHTML = elements[0].getAttribute('src');
newDiv.appendChild(newStrong);
servicePreview.appendChild(newDiv);
elements[0].parentNode.removeChild(elements[0]);
}
<div class="multi-gallery-image show" id="service_preview">
<img alt="image" src="チャイルドカット¥3000">
<img alt="image" src="ジュニアカット">
<img alt="image" src="ハナコカット">
<img alt="image" src="Hair Styling">
<img alt="image" src="Manicures">
<img alt="image" src="Hair Coloring">
</div>

Unlike jQuery append() the native method treats html strings as text
Use insertAdjacentHTML(position, html) instead
const str = '<div class="inserted">Test</div>'
document.getElementById('one').append(str);// shows as text
document.getElementById('two').insertAdjacentHTML('beforeend', str)
.inserted{color:red}
<div id="one"></div>
<div id="two"></div>

In raw JavaScript I believe its something like this.
const services = ['チャイルドカット¥3000', 'ジュニアカット', 'ハナコカット',
'Hair Styling', 'Manicures', 'Hair Coloring']
const preview = document.getElementById("service_preview")
services.forEach(service =>{
const div = document.createElement("div")
const strong = document.createElement("strong")
strong.innerText = service
div.appendChild(strong)
preview.appendChild(div)
})

const servicePreview = document.getElementById("service_preview");
const imageSources = [...servicePreview.children].map((img) => img.src);
console.log(imageSources);
// Remove all images
while (servicePreview.firstChild) {
servicePreview.removeChild(servicePreview.firstChild);
}
// Add new div/strong tags
for (const imageSource of imageSources) {
const div = document.createElement("div");
const strong = document.createElement("strong");
strong.textContent = imageSource;
div.appendChild(strong);
servicePreview.appendChild(div);
}

simply use replaceChild() method
there is a trap with img.src because you get an URI
const servicePreview = document.getElementById('service_preview')
servicePreview.querySelectorAll('img').forEach(imgElm=>
{
let newDiv = document.createElement('div')
, newStrg = document.createElement('strong')
;
newDiv.appendChild( newStrg )
newStrg.textContent = imgElm.getAttribute('src') // or decodeURI( imgElm.src.split('/').pop() )
servicePreview.replaceChild( newDiv, imgElm )
})
<div class="multi-gallery-image show" id="service_preview">
<img alt="image" src="チャイルドカット¥3000">
<img alt="image" src="ジュニアカット">
<img alt="image" src="ハナコカット">
<img alt="image" src="Hair Styling">
<img alt="image" src="Manicures">
<img alt="image" src="Hair Coloring">
</div>

Related

How get the original size images (height and width) from your href and put them on your attr. using jquery

hello friends i am trying to get the size (height and width) of an image from an hrf and put these values ​​in its attribute
This is driving me crazy
this is my html:
<figure>
<a href="image-large-1.jpg">
<img src="image-small-1.jpg"/>
</a>
</figure>
<figure>
<a href="image-large-2.jpg">
<img src="image-small-2.jpg"/>
</a>
</figure>
<figure>
<a href="image-large-3.jpg">
<img src="image-small-3.jpg"/>
</a>
</figure>
this is what I want :
<figure>
<a href="image-large-1.jpg" original-size="1000x800"> //the sizes are example
<img src="image-small-1.jpg"/>
</a>
</figure>
<figure>
<a href="image-large-2.jpg" original-size="1200x700"> //the sizes are example
<img src="image-small-2.jpg"/>
</a>
</figure>
<figure>
<a href="image-large-3.jpg" original-size="900x980"> //the sizes are example
<img src="image-small-3.jpg"/>
</a>
</figure>
the "original-size" attribute I want to get it from " a hrf "
I was trying with this code that I found here, I get the original size of the image-large from the href (in the console.log) but I cannot print them in the html
help me please
$(".containerGallery figure a").each(function() {
var imgSrc, imgW, imgH;
function myFunction(image){
var img = new Image();
img.src = image;
img.onload = function() {
return {
src:image,
width:this.width,
height:this.height};
}
return img;
}
var x = myFunction($(this).attr('href'));
x.addEventListener('load',function(){
imgSrc = x.src;
imgW = x.width;
imgH = x.height;
});
$(this).each(function() {
x.addEventListener('load',function(){
console.log(imgW+'x'+imgH);
$(this).attr('original-size', imgW+'x'+imgH);
});
});
});
The JavaScript code in the question is overly complex and redundant.
Here's some simplified code that accomplishes the same thing.
// get all <a> elements inside <figure> elements
const atags = Array.from(document.querySelectorAll('figure a'));
// iterate over every <a> tag
atags.forEach(atag => {
// create blank image element
var img = new Image();
// when the image loads, store its dimensions to the atag's
// `data-original-size` attribute
img.addEventListener('load', () => {
let imgW = img.width,
imgH = img.height;
atag.dataset.originalSize = `${imgW}x${imgH}`;
console.log('atag:', atag);
});
// load image from atag's href
img.src = atag.href;
});
<figure>
<a href="https://i.picsum.photos/id/1077/200/300.jpg">
<img src="https://via.placeholder.com/40" />
</a>
</figure>
<figure>
<a href="https://i.picsum.photos/id/913/200/200.jpg">
<img src="https://via.placeholder.com/50" />
</a>
</figure>
<figure>
<a href="https://i.picsum.photos/id/1058/100/100.jpg">
<img src="https://via.placeholder.com/60" />
</a>
</figure>
Here is script that does absolutely what you're looking for!
const getOriginalSize = (target, url) => {
const image = document.createElement("img");
image.src = url;
image.onload = function(){
target.setAttribute("original-size", `${image.naturalWidth}x${image.naturalHeight}`);
}
return image;
}
<figure>
<a href="https://images.sftcdn.net/images/t_app-cover-l,f_auto/p/befbcde0-9b36-11e6-95b9-00163ed833e7/260663710/the-test-fun-for-friends-screenshot.jpg">
<img src="https://images.sftcdn.net/images/t_app-cover-l,f_auto/p/befbcde0-9b36-11e6-95b9-00163ed833e7/260663710/the-test-fun-for-friends-screenshot.jpg"/>
</a>
</figure>
<figure>
<a href="https://www.velior.ru/wp-content/uploads/2009/05/Test-Computer-Key-by-Stuart-Miles.jpg">
<img src="https://www.velior.ru/wp-content/uploads/2009/05/Test-Computer-Key-by-Stuart-Miles.jpg"/>
</a>
</figure>
<script>
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll("figure").forEach( (figure) => {
figure.querySelectorAll("a[href]").forEach( function(targetAhref) {
getOriginalSize(targetAhref, targetAhref.href);
console.warn("image loaded and size registred!");
} );
} );
} );
</script>

Automatic Cycling Carousel for several divs and different img

I am trying to write a function, that will automatically carousel cycle through img thumbs on my site with 12 different sets of images, which are just put together in one div. The javascript below works, but only as long, as I have the same amount of images in every div. I am also sure, that I took the long route of telling javascript, what to do in terms of variables so my question is, what should I change, so that I can have different amounts of img in my separate divs?
Thanks a lot for any tips!
var myIndex = 0;
carousel();
function carousel() {
var i;
var u = document.getElementsByClassName("thumbs1");
var v = document.getElementsByClassName("thumbs2");
var w = document.getElementsByClassName("thumbs3");
// and so on ...
for (i = 0; i < w.length; i++) {
u[i].style.display = "none";
v[i].style.display = "none";
w[i].style.display = "none";
// ...
}
myIndex++;
if (myIndex > w.length) {myIndex = 1}
u[myIndex-1].style.display = "inline-block";
v[myIndex-1].style.display = "inline-block";
w[myIndex-1].style.display = "inline-block";
// ...
setTimeout(carousel, 1200); // Change image every 2 seconds
}
<div class="imageholder">
<img class="thumbs1" src="image11.jpg">
<img class="thumbs1" src="image12.jpg">
<img class="thumbs1" src="image13.jpg">
<img class="thumbs1" src="image14.jpg">
</div>
<div class="imageholder">
<img class="thumbs2" src="image21.jpg">
<img class="thumbs2" src="image22.jpg">
<img class="thumbs2" src="image23.jpg">
</div>
<div class="imageholder">
<img class="thumbs3" src="image31.jpg">
<img class="thumbs3" src="image32.jpg">
<img class="thumbs3" src="image33.jpg">
<img class="thumbs3" src="image34.jpg">
<img class="thumbs3" src="image35.jpg">
</div>
<!-- ... -->
Keep counting the myIndex (so do not reset it) and use the modulus % operator with the array length of each image set.
Further notes:
The value of Timeout/Interval is in milliseconds. So 2000ms = 2s
You do not need to get all elements' references again with each call to carousel(). Just do it once at the beginning.
If something is not clear, please ask.
var myIndex = 0;
var i;
var u = document.getElementsByClassName("thumbs1");
var v = document.getElementsByClassName("thumbs2");
var w = document.getElementsByClassName("thumbs3");
var allThumbs = [u, v, w];
var myInterval = setInterval(carousel, 2000); // Change image every 2 seconds
function carousel() {
myIndex++;
for (i = 0; i < allThumbs.length; i++) {
allThumbs[i][(myIndex - 1) % allThumbs[i].length].style.display = "none";
allThumbs[i][myIndex % allThumbs[i].length].style.display = "inline-block";
}
}
.thumbs1:not(:first-child),
.thumbs2:not(:first-child),
.thumbs3:not(:first-child) {
display: none;
}
<div class="imageholder">
<img class="thumbs1" src="image11.jpg" alt="1">
<img class="thumbs1" src="image12.jpg" alt="2">
<img class="thumbs1" src="image13.jpg" alt="3">
<img class="thumbs1" src="image14.jpg" alt="4">
</div>
<div class="imageholder">
<img class="thumbs2" src="image21.jpg" alt="1">
<img class="thumbs2" src="image22.jpg" alt="2">
<img class="thumbs2" src="image23.jpg" alt="3">
</div>
<div class="imageholder">
<img class="thumbs3" src="image31.jpg" alt="1">
<img class="thumbs3" src="image32.jpg" alt="2">
<img class="thumbs3" src="image33.jpg" alt="3">
<img class="thumbs3" src="image34.jpg" alt="4">
<img class="thumbs3" src="image35.jpg" alt="5">
</div>

How to pass looped array items to function variable

I have a group of images and each image has a title I want to change the background and title of each image to a different color on hover.
Now I selected my images and titles and looped throw them to change their colors but its not working I am not surprised just want to know how to fix it.
function changeBgAndTitle(element, event, backgroundColor, titleColor) {
element.addEventListener(event, () => {
const projectThumbnail = document.querySelectorAll('.projects-list img');
const projectTitle = document.querySelectorAll('article h1');
for (i = 0; i < projectThumbnail.length; i++) {
console.log(projectThumbnail[0]);
}
for (i = 0; i < projectTitle.length; i++) {
projectTitle[i].style.color = titleColor;
}
})
}
changeBgAndTitle(projectThumbnail[0], 'mouseover', '#0090d8', 'white');
<div class="projects-list">
<article class="old-and-blue">
<h1>old and blue</h1>
<figure>
<a href="/old-and-blue.html" class="noclick">
<img src="assets/media/images/slides/old-and-blue.jpg" alt="">
</a>
</figure>
</article>
<article class="dably">
<h1>dably</h1>
<figure>
<a href="/old-and-blue.html">
<img src="assets/media/images/slides/dably.jpg" alt="">
</a>
</figure>
</article>
<article class="cairo">
<h1>cairo</h1>
<figure>
<a href="/old-and-blue.html">
<img src="assets/media/images/slides/cairoe.jpg" alt="">
</a>
</figure>
</article>
<article class="cta">
<h1>cta</h1>
<figure>
<a href="/cta.html">
<img src="assets/media/images/slides/cta.jpg" alt="">
</a>
</figure>
</article>
</div>
If you want to call addEventListener inside the loop:
function changeBgAndTitle(element, event, backgroundColor, titleColor) {
const projectThumbnail = element.querySelectorAll('.projects-list img')[0];
projectThumbnail.addEventListener(event, () => {
var projectTitle = element.querySelectorAll('h1');
projectTitle[0].style.color = titleColor;
})
}
const articles = document.querySelectorAll('.projects-list article');
for (i = 0; i < articles.length; i++) {
changeBgAndTitle(articles[i], 'mouseover', '#0090d8', 'white');
}
https://jsfiddle.net/zf2xb48e/
You should be calling addEventListener inside the loop, not passing a single element to the function.
function changeBgAndTitle(event, backgroundColor, titleColor) {
const projectThumbnail = document.querySelectorAll('.projects-list img');
const projectTitle = document.querySelectorAll('article h1');
projectThumbnail.forEach((element, i) => element.addEventListener(event, () => {
console.log(element);
projectTitle[i].style.color = titleColor;
projectTitle[i].style.backgroundColor = backgroundColor;
}));
}
changeBgAndTitle('mouseover', '#0090d8', 'white');
<div class="projects-list">
<article class="old-and-blue">
<h1>old and blue</h1>
<figure>
<a href="/old-and-blue.html" class="noclick">
<img src="assets/media/images/slides/old-and-blue.jpg" alt="">
</a>
</figure>
</article>
<article class="dably">
<h1>dably</h1>
<figure>
<a href="/old-and-blue.html">
<img src="assets/media/images/slides/dably.jpg" alt="">
</a>
</figure>
</article>
<article class="cairo">
<h1>cairo</h1>
<figure>
<a href="/old-and-blue.html">
<img src="assets/media/images/slides/cairoe.jpg" alt="">
</a>
</figure>
</article>
<article class="cta">
<h1>cta</h1>
<figure>
<a href="/cta.html">
<img src="assets/media/images/slides/cta.jpg" alt="">
</a>
</figure>
</article>
</div>

Append 2 json objects per div

I am trying to append two different JSON items per div. I empty the div before looping through the json and then append the objects.
But I need to append two per div and each item has to be different.
Eg. div1 has img1 & img2, div2 has img3 & img4 etc.
This is the result I am getting -
<div class="gallery-sub-slider">
<div>
<img class="img1">
<img class="img2">
<img class="img3">
<img class="img4">
<img class="img5">
</div>
<div>
<img class="img1">
<img class="img2">
<img class="img3">
<img class="img4">
<img class="img5">
</div>
</div>
But this is the result that I need -
<div class="gallery-sub-slider">
<div>
<img class="img1">
<img class="img2">
</div>
<div>
<img class="img3">
<img class="img4">
</div>
<div>
<img class="img5">
<img class="img6">
</div>
</div>
$.each(data.carImages, function(i){
counter++;
imgLink = data.carImages[i].imgLink;
console.log(counter);
$('.gallery-slider').append('<div><img src="' + imgLink + '" class="gallery-img" data-tag="' + i + '"></div>');
$('.gallery-sub-slider').append('<div class="sub-gallery-item" data-index="' + i + '"></div>');
$('.gallery-sub-slider div').append('<img src="' + imgLink + '" class="sub-gallery-img" data-tag="1"><img src="' + imgLink + '" class="sub-gallery-img">');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Rather than looping through each data.carImage, you can consider first calculating the number of divs you will require:
var divCount = Math.ceil(data.carImages.length / 2)
And loop through those:
for (var i = 0; i < divCount; i++) {
var firstImgIndex = i*2;
var secondImgIndex = firstImgIndex + 1;
var firstImg = data.carImages[firstImgIndex];
var secondImg = data.carImages[secondImgIndex];
// create your div now, with your first and second img, but you might have to check that secondImg !== null or undefined
}

javascript function is executed only one time

I have a javascript function and I want to call it 12 times.
So I did like this:
Here I have 12 images:
<img id="img1" src=""> </img>
<img id="img2" src=""> </img>
<img id="img3" src=""> </img>
<img id="img4" src=""> </img>
<img id="img5" src=""> </img>
<img id="img6" src=""> </img>
<img id="img7" src=""> </img>
<img id="img8" src=""> </img>
<img id="img9" src=""> </img>
<img id="img10" src=""> </img>
<img id="img11" src=""> </img>
<img id="img12" src=""> </img>
Here the function is defined:
function addImageSource(id,another_variable) {
var imageSource = "http://..."+ another_variable + "test";
$("#img" + id).attr("src", imageSource);
}
And here I call it:
var itm_id = 1;
while(itm_id < 13){
addImageSource(item_id, "another_variable" );
itm_id++
}
Why is this function executed only one time? Can somebody tell me why?
You'll need to use a for loop so you'll want something like
for (var itm_id = 1; itm_id < 13; itm_id++){
addImageSource(itm_id, "another_variable" );
}
You need for instead of if:
for (var itm_id = 1 ; itm_id < 13; itm_id++) {
addImageSource(itm_id, "another_variable" );
}
also you made a mistake with this line:
addImageSource(item_id, "another_variable" );
it should be:
addImageSource(itm_id, "another_variable" );
You need to place the function call inside of a loop. Right now you are using a conditional which is a decision making construct, not a loop.
Replace:
var itm_id = 1;
if (itm_id < 13){
addImageSource(item_id, "another_variable" );
itm_id++
}
With a for loop like this:
for (var itm_id=1 ; itm_id < 13 ; itm_id++) {
addImageSource(itm_id, "another_variable" );
}

Categories