JavaScript Change Images Path That Have The Same Id - javascript

I want to make a JavaSript code that changes the images. I mean there are two images and a button. The images path are /assets/images/svg/outline-img1.svg and /assets/images/svg/outline-img.svg. Also there is a button, that should change all the images path that have the same id (id="changeimg").
I want to make that when you click onto the button, it should change the images, that contains the changeid. It's pretty simple but what I really want is to only change a part of the path. I mean I want to change the path from /assets/images/svg/outline-img1.svg to /assets/images/svg/filled-img.svg. But is it possible to change all the images' path that contain the changeimg id?
Is there any code snippet for example this?
document.querySelector('.btn').addEventListener("click",
function () {
$('#changeimg').attr('src', '/assets/images/svg/filled-'+imgname+'.svg');
/*
imgname should be the name of the image between the '/assets/images/svg/outline' and the '-.svg'. (In this example imgname = shape and imgname = shape2)
So the it should change the elements that contains the '#changeimg' id from '/assets/images/svg/outline-shape.svg' to '/assets/images/svg/filled-shape.svg'
And all the images with the changeimg id should be changed.
*/
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="/assets/images/svg/outline-shape.svg" id="changeimg">
<img src="/assets/images/svg/outline-shape2.svg" id="changeimg">
<button class="btn">Change</button>
I know it's a bit hard to understand, if you want I can redefine my problem.

First, IDs should be unique. You might even get warnings if not doing so.
Use classes, and then
const elements = document.getElementByClassName('changeimg')
for (let i=0; i< elements.length; i ++) {
const imgPath = elements[i].src;
imgPath.replace('outlined', 'filled');
elements[i].src = imgPath;
}

Try this,
const x = document.querySelectorAll("#changeimg");
for (i = 0; i < x.length; i++) {
x[i].src = "/assets/images/svg/filled-img.svg";
}

Related

How to make an image play sound onclick using JavaScript?

So I want to create my 1st project using JS HTLM and CSS, which will be like a drum website ...
when I click on an image it should make sound . So, All I know is making a button make sound by clicking on it not an actual image. If you have any idea what should I put in this YYY place ?
here's my JS file code :
PS : soundi is this image's class
var soundi = document.querySelectorAll(".soundi").length;
for (var i = 0; i < soundi ; i++) {
document.querySelectorAll(".soundi")[i].addEventListener("click", function () {
var clickDe = this.YYYY;
switch (clickDe) {
case "YYYY" :
var tom1 = new Audio('sounds/tom-1.mp3');
tom1.play();
break;
}
})
}
You could add an Id to each image and then register the event listeners like so:
function imageClicked(event) {
const imgId = event.target.id; // imgId is the name of the instrument => the name of the sound file without the extension
const soundFile = new Audio(`sounds/${imgId}.mp3`); // this way, you don't have to use a switch statement which can get very long and chaotic
soundFile.play();
}
document
.querySelectorAll(".soundi") // querySelectorAll returns all the images so no need to put it in a for loop
.forEach((img) => img.addEventListener("click", imageClicked));
You will obviously have to choose the image ids properly so that they match up with the file names.

Loop through all images and change size?

The script below works for posts that are already on the page. But, when I click on load more posts, the new posts that get added to the page don't change the source of the image so that they are blurry.
Is there a way to loop through all images and change the src of it, even the ones that are not shown?
function resizeThumb(size) {
var popularPost = document.getElementById('Blog1');
var image = popularPost.getElementsByTagName('img');
for (var i = 0; i < image.length; i++) {
image[i].src = image[i].src.replace(/\/s72\-c/g, "\/s" + size + "-c");
image[i].width = size;
image[i].height = size;
}
}
// Resize to 200 × 200
resizeThumb(200);
Yes. Basically locate the button that loads more, find it's name.
If your button looks like this:
Load more
Put this before it so it looks like this:
<span onclick="resizeThumb(200); ">
Load more
</span>
It's the lousiest solution but the question is lousy too.

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);

get name of files in a folder with javascript

I have a background image folder that there is some picture that i want to use them for background.
how i can get their names and put them on array whit javascript?if i cant they do with javascript,how can i do that?
i want to read name of files and use javacsript and link for change background image whit css.
<script>
function nextbg(){
$('#bg').css('background-image','url(Images/bg2.jpg)');
}
</script>
This solution is created according to the fact that browser dont have access to folders/filesystem.
Javascript can not access the filesystem. This has to be done by a server script and then be feed to the javascript.
I had the simliar problem when building my game engine when I was loading all my diffrent tiles. I ended up doing it like this.
This solution do pose two a problems when implementing it.
You will have to define the amout of images in the "NrofTiles" array
The images must be named like tile1, tile2 ... tile9 so you can
increment the path to them.
The typeOfTiles[typeCounter] is just there to give me access to different folders, in my case for my tiles, grass, houses, water and so on.
for(var i = 0; i <= nrofTiles.length; i++)
{
for(var x = 0; x <= nrofTiles[i]; x++)
{
console.log
("Fetching tile "+(x + 1 )+" of " + 14);
img = new Image();
//My path
img.src = 'Images/Cart/' + typeOfTiles[typeCounter] + '/' + (x + 1) + '.png';
imgArray.push(img);
var intervalFunctionen = function () {
alert("calls back here");
};
}//end for loop!
}end outer for loop!
When everything is loaded(the tiles), you do this to change the background picture.
This is an example of a changing body background. You could make a link with an ID lets say "iamthelink".
HTML
Change BG
JAVASCRIPT
var link = document.getElementsById('iamthelink');
link.onclick= function() {
var body = document.getElementsByTagName('body')[0];
body.style.backgroundImage = 'url(http://localhost/background.png)';
}

How to populate alt fields with the src of an image for all images on page

I am working on a site that has a page that will have a couple hundred thumbnails. I would like to have the filenames (the src) of the images populate the alt fields. So for example, I currently have the thumbnails as follows:
<img src="images/thumb1.jpg" />
I would like to populate the alt fields with the filename. So, the desired result would be:
<img src="images/thumb1.jpg" alt="thumb1" />
Is there a way I can automatically generate these alt tags using the images src?
Any suggestions are appreciated. Thank you for the help!
An untested, first guess, would be:
var images = document.getElementsByTagName('img');
var numImages = images.length;
for (i=0; i<numImages; i++) {
images[i].alt = images[i].src;
}
JS Fiddle demo.
Just to demonstrate how much easier this can be, with a JavaScript library, I thought I'd also offer the jQuery demo too:
$('img').each(
function(){
this.alt = this.src;
this.title = this.src;
});
jQuery-based JS Fiddle demo.
Edited because I'm an idiot...
I forgot to point out that you'll need to wait for the window to finish loading (or, at least, for the document.ready event), so try it this way:
function makeAlt() {
var images = document.getElementsByTagName('img');
var numImages = images.length;
for (i = 0; i < numImages; i++) {
images[i].alt = images[i].src;
images[i].title = images[i].src;
}
}
And change the opening body tag to:
<body onload="makeAlt">
JS Fiddle demo.
Edited to address the OP's final question:
function makeAlt() {
var images = document.getElementsByTagName('img');
var numImages = images.length;
var newAlt, stopAt;
for (i = 0; i < numImages; i++) {
newAlt = images[i].src.split('/').pop();
stopAt = newAlt.indexOf('.');
newAlt = newAlt.substring(0,stopAt);
images[i].alt = newAlt;
images[i].title = newAlt;
}
}
JS Fiddle, though I suspect there's a far more concise way...
To get the file name you could add to David Thomas's code...
var name = images[i].getAttribute('alt').split('/');
name = name[name.length-1].split('.')[0];
So that you end up with...
var images = document.getElementsByTagName('img');
var numImages = images.length;
for (i=0; i<numImages; i++) {
var name = images[i].getAttribute('src').split('/');
name = name[name.length-1].split('.')[0];
images[i].setAttribute('alt') = name;
}
(Also amazingly untested)
Here it is, with some simple DOM operations and a dash of regex magic:
var imgs = document.getElementsByTagName('img');
// This will extract the file name (minus extension) from the image's `src`
// attribute. For example: "images/thumb1.jpg" => "thumb1"
var name_regexp = /([^/]+)\.[\w]{2,4}$/i;
var matches;
for ( i = 0; i < imgs.length; i++ ) {
matches = imgs[i].src.match(name_regexp);
if ( matches.length > 1 ) {
imgs[i].alt = matches[1];
imgs[i].title = matches[1];
}
}
See JSFiddle for a demo.
var images = document.getElementsByTagName("img");
var count = images.length;
for (i=0; i<count; i++){
var src = images[i].getAttribute("src");
var path = src.split("/");
var fullname = path[path.length - 1];
var name = fullname.split(".");
var result = name[0];
images[i].setAttribute("alt") = result;
}
I think the real questions you should be asking is will all this actually help my SEO, because I assume that is the reason why you would like your alt tags populated?
There is some evidence that Google is getting better at reading Javascript, but will it run the scrip before it crawls the pages and add the alt text then index the page with that alt text and consider that alt text to provide additional value outside of the keywords it already found in your file names, especially considering that it rendered the script so it will probably know that the alt is just being copied form the file name. Or will Google simply index all the html and not even bother trying to run the javascript?
I would be interested to hear any additional insight others may have on this.
I personally feel there is a low probably that this will end up helping your SEO. If you are using a content management system you should probably be looking at how to add alt text via PHP by taking the variable for the page heading or title and inserting that to the alt text.
Unless you don't care about your SEO and are really doing this for text readers, then forget everything i just said.

Categories

Resources