I Hope you can help me.
When I click button it adds night before file extension ex.(interior-1.jpg to interior-1-night) but it only affects the first image which is interior-1.jpg.
What I want is to add "night" text before the file extension of all images under the "image" ID.
Here is my html code
<button onclick="changeMode()">switch</button>
<img id="image" src="interior-1.jpg"/>
<img id="image" src="interior-2.jpg"/>
<img id="image" src="interior-3.jpg"/>
<img id="image" src="interior-4.jpg"/>
<img id="image" src="interior-5.jpg"/>
Here is my javascript code
<script>
function changeMode() {
var filename = document.getElementById("image").src;
var modfilename = filename.replace(/(\.[\w\d_-]+)$/i, '-night$1');
document.getElementById("image").src = modfilename;
</script>
}
You should never use same id name on elements in the dom. Instead use same class name. To apply the src on all the img tag get all the tags using document.getElementsByClassName. Iterate over each element and change the src using a forEach loop
function changeMode() {
var filename = document.getElementsByClassName("image");
var a = '';
Object.values(filename).forEach((e) => {
a = e.src;
var modfilename = a.replace(/(\.[\w\d_-]+)$/i, '-night$1');
e.src = modfilename;
})
}
<button onclick="changeMode()">switch</button>
<img class="image" src="interior-1.jpg" />
<img class="image" src="interior-2.jpg" />
<img class="image" src="interior-3.jpg" />
<img class="image" src="interior-4.jpg" />
<img class="image" src="interior-5.jpg" />
The problem is that you are getting your element by GetElementById which only returns one element. You should change the id tag to name like this:
<img name="image" src="interior-1.jpg"/>
Then you should be able to retrieve all the elements using var els = document.getElementsByName('image');
now you need to change their file names, so
for (let i = 0; i<els.length; i++){
els[i].src = els[i].src.replace(/(\.[\w\d_-]+)$/i, '-night$1');
}
Here is my two cents. Use classes. This way you can query multiple elements instead of just one. Then apply your changes to each element using, in this case, a forEach.
The elements returend from document.querySelectorAll is a nodeList. That's why I use Array.prototype.forEach.call.
function changeMode() {
const imageNodes = document.querySelectorAll(".image");
Array.prototype.forEach.call(imageNodes, (node) => {
let modfilename = node.src.replace(/(\.[\w\d_-]+)$/i, '-night$1');
node.src = modfilename
})
}
<button onclick="changeMode()">switch</button>
<img class="image" src="interior-1.jpg"/>
<img class="image" src="interior-2.jpg"/>
<img class="image" src="interior-3.jpg"/>
<img class="image" src="interior-4.jpg"/>
<img class="image" src="interior-5.jpg"/>
Related
If there is HTML code like below
<img src="https://example.com/img_01.png">
<img src="https://example.com/img_02.png">
<img src="https://example.com/img_03.png">
<img src="https://example.com/img_04.png">
I'd like to change these like:
<img src="https://example2.com/img_01.png">
<img src="https://example2.com/img_02.png">
<img src="https://example2.com/img_03.png">
<img src="https://example2.com/img_04.png">
How can I make this?
You can use replace to change url inside loop to get new url like below.
$('img').each(function() {
var newSrc = $(this).attr('src');
newSrc = newSrc.replace('example', 'example2')
$(this).attr('src', newSrc);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://example.com/img_01.png" />
<img src="https://example.com/img_02.png" />
<img src="https://example.com/img_03.png" />
<img src="https://example.com/img_04.png" />
You can use .attr()
$('img').attr('src',"https://example2.com/img_01.png");
console.log(Array.from(document.querySelectorAll('img')))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://example.com/img_01.png">
<img src="https://example.com/img_02.png">
<img src="https://example.com/img_03.png">
<img src="https://example.com/img_04.png">
You can make this with jQuery:
<img src="https://example.com/img_01.png">
<img src="https://example.com/img_02.png">
<img src="https://example.com/img_03.png">
<img src="https://example.com/img_04.png">
JavaScript code:
$("img").each(img => img.src.replace("example.com", "example2.com"));
You can try like this
var newDOmain = "https://example2.com/";
$('img').each(function(){
var imgName = $(this).attr('src').split('/').pop();
$(this).attr('src', newDOmain + imgName);
$(this).attr('alt', newDOmain + imgName);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://example.com/img_01.png">
<img src="https://example.com/img_02.png">
<img src="https://example.com/img_03.png">
<img src="https://example.com/img_04.png">
if some day ur url changes to "https://example.net/img_01.png" then u have to modify the code if u will use direct string replacements. So to make ur code more efficient use regex way to do the same.
var domainRegex = /\/{2,}((?:[^\.]+\.)*\w+)\//;
$("img").each(img => {
img.src = img.src.replace(img.src.match(domainRegex)[1], "example2.com");
});
This regex can replace any domain name to ur chosen one.
I am trying to change the img src based on what button I have clicked.
My current approach is to add event listeners to each img id and change then change the image of the top img tag. The issue with this apporach is that I will have a lot of repetetive code especially when im adding more buttons.
So i would like someone to give advice or show me a different and better approach to do this. Im requesting help in only native javascript. Thanks.
document.getElementById("human").addEventListener("click", e => {
document.getElementById('imageChange').src = "dir/images/human.png";
})
document.getElementById("dwarf").addEventListener("click", e => {
document.getElementById('imageChange').src = "dir/images/dwarf.png";
})
document.getElementById("elf").addEventListener("click", e => {
document.getElementById('imageChange').src = "dir/images/elf.png";
})
<img id="imageChange" src="dir/images/human.png" alt="">
<div class="buttonContainer">
<img src="../dir/images/race/human_male.png" id="human" class="race human_container"></img>
<img src="../dir/images/race/dwarf_male.png" id="dwarf" class="race dwarf_container"></img>
<img src="../dir/images/race/elf_male.png" id="elf" class="race elf_container"></img>
</div>
You are right, that having multiple event handler is not a good solution. You can have single one attached to the common container. Something like this:
document.querySelector(".buttonContainer").addEventListener("click", e => {
if (e.target.tagName === 'IMG') {
document.getElementById('imageChange').src = e.target.src
}
})
.buttonContainer img {
height: 30px;
width: 30px;
}
<img id="imageChange" src="https://cdn2.iconfinder.com/data/icons/oxygen/64x64/mimetypes/unknown.png" alt="">
<div class="buttonContainer">
<img src="https://cdn0.iconfinder.com/data/icons/social-network-7/50/4-64.png" id="human" class="race human_container" />
<img src="https://cdn0.iconfinder.com/data/icons/social-network-7/50/6-64.png" id="dwarf" class="race dwarf_container" />
<img src="https://cdn0.iconfinder.com/data/icons/social-network-7/50/29-64.png" id="elf" class="race elf_container" />
</div>
It is necessary to check event target e.target.tagName === 'IMG' because click event bound like this might get triggered by clicking on elements other than images (so with no src).
Since you already know what you want to change the image to why not add it in the html as a data- attribute then just replace the current src with the data- value?
var clickables = document.querySelectorAll('.race');
function showImage(e) {
var src = e.target.src;
document.getElementById('imageChange').src = src;
}
for (var i = clickables.length - 1; i >= 0; i--) {
clickables[i].addEventListener('click', showImage);
}
.buttonContainer img {max-width: 100px}
<img id="imageChange" src="https://upload.wikimedia.org/wikipedia/en/e/ed/Nyan_cat_250px_frame.PNG" alt=""/>
<div class="buttonContainer">
<img src="https://vignette.wikia.nocookie.net/nyancat/images/f/ff/Mexinyan.gif/revision/latest?cb=20150409011153" id="human" class="race human_container"/>
<img src="http://www.nyan.cat/cats/original.gif" id="dwarf" class="race dwarf_container"/>
<img src="https://upload.wikimedia.org/wikipedia/en/e/ed/Nyan_cat_250px_frame.PNG" id="elf" class="race elf_container"/>
</div>
var imageNodes = document.getElementsByClassName("race");
for(var i = 0; i < imageNodes.length; i++){
imageNodes[i].addEventListener('click', (e) =>{
const imageId = e.target.id;
document.getElementById('imageChange').src = 'dir/images/' + imageId + '.png';
})
}
I have the following elements in a html document
<div id="u11" class="ax_default image" data-label="image1">
<img id="u11_img" class="img " src="images/image1_u11.png">
</div>
<div id="u23" class="ax_default image" data-label="image2">
<img id="u23_img" class="img " src="images/image2_u23.png">
</div>
I want to write a javascript onclick function for another element that set image2 src to image1 src
The problem is that ids are random so I cannot use them but fortunately I can use the data-label to get the external div objects with $('[data-label=image1]')
¿How can I set the src in the inner img?
You can use the following
var image1 = document.querySelector('[data-label="image1"] img'),
image2 = document.querySelector('[data-label="image2"] img');
document.querySelector('#button').addEventListener('click', function(){
image2.src = image1.src;
});
here is an example using each function :
$( "#change" ).click(function() {
// get all image element in body
var selects = $('body').find('img');
// loop throw them
selects.each(function(index, el) {
if(index !== selects.length - 1) {
//save the img src to local variable
var img1 = selects[index].getAttribute('src');
var img2 = selects[index+1].getAttribute('src');
// change the imgs src
selects[index].src = img2;
selects[index+1].src = img1;
// and have a nice day ^^'
}
});
});
img{
max-width:95px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="u11" class="ax_default image" data-label="image1">
<img id="u11_img" class="img " src="https://media-cdn.tripadvisor.com/media/photo-s/0e/4c/55/8d/merzouga.jpg">
</div>
<div id="u23" class="ax_default image" data-label="image2">
<img id="u23_img" class="img " src="http://www.classetouriste.be/wp-content/uploads/2012/11/sahara-01.jpg">
</div>
<button id="change">Change images</button>
this code will work no matter how many img you have in your body or you can just set the element that contain the image var selects $('#yourelementid').find('img');
You could change the entire code with the src included.
function myFunction() {
document.getElementById("u11").innerHTML = '<img id="u23_img" class="img " src="images/image2_u23.png">';
}
}
<div id="u11" class="ax_default image" data-label="image1">
<img id="u11_img" class="img " src="images/image1_u11.png">
</div>
<div id="u23" class="ax_default image" data-label="image2">
<img id="u23_img" class="img " src="images/image2_u23.png">
</div>
I am a beginner for Javascript, read several post here but could not get my codes work. Hope you can explain the solution :)
So basically I have four set of images, but I need to replace all of the $_12.JPGto $_57.JPG in their URL so I get bigger size of pictures (only images that are assigned to class="ebay" / id="ebay"). I need this to be executed when the browser starts reading the page, no events or buttons involved.
The following is my source code:
<div>
<img class="ebay" id="ebay" u="image" src="http://i.ebayimg.com/00/s/NzgwWDc4MA==/z/neAAAOSwrklU28I8/$_12.JPG?set_id=880000500F">
<img u="thumb" src="http://i.ebayimg.com/00/s/NzgwWDc4MA==/z/neAAAOSwrklU28I8/$_12.JPG?set_id=880000500F">
</div>
<div>
<img class="ebay" id="ebay" u="image" src="http://i.ebayimg.com/00/s/NzgwWDc4MA==/z/r8cAAOSwNSxU28I9/$_12.JPG?set_id=880000500F">
<img u="thumb" src="http://i.ebayimg.com/00/s/NzgwWDc4MA==/z/r8cAAOSwNSxU28I9/$_12.JPG?set_id=880000500F">
</div>
<div>
<img class="ebay" id="ebay" u="image" src="http://i.ebayimg.com/00/s/NzgwWDc4MA==/z/HLgAAOSwPhdU28I-/$_12.JPG?set_id=880000500F">
<img u="thumb" src="http://i.ebayimg.com/00/s/NzgwWDc4MA==/z/HLgAAOSwPhdU28I-/$_12.JPG?set_id=880000500F">
</div>
<div>
<img class="ebay" id="ebay" u="image" src="http://i.ebayimg.com/00/s/NzgwWDc4MA==/z/6VkAAOSwPYZU28I-/$_12.JPG?set_id=880000500F">
<img u="thumb" src="http://i.ebayimg.com/00/s/NzgwWDc4MA==/z/6VkAAOSwPYZU28I-/$_12.JPG?set_id=880000500F">
</div>
I also like to loop the function so when I have more than 4 sets of pictures (maximum 15 sets) and the javascript can still replace the URL for me.
The following is what I had tried:
window.onload = function() {
for ( var i = 0; i < currentLink.length; i++) {
var currentLink=document.getElementByClassName('ebay');
var newLink = currentLink.src.replace('$_12.JPG','$_57.JPG');
currentLink.src = newLink;
}
}
You have to realize that getElementsByClassName returns an HTMLCollection, not a single element. So you cannot simply change all the elements in the collection by accessing the .src property of the collection.
You need to iterate over the collection to do this:
var currentLinks = document.getElementsByClassName('ebay');
Array.prototype.forEach.call(currentLinks, function(currentLink) {
var newLink = currentLink.src.replace('$_12.JPG','$_57.JPG');
currentLink.src = newLink;
});
Also, you have a typo in your getElementByClassName (you're missing the s in Elements).
See MDN
Misplacement of var currentLink=document.getElementByClassName('ebay');
Do,
window.onload = function() {
var currentLink=document.getElementsByClassName('ebay');
for ( var i = 0; i < currentLink.length; i++) {
var newLink = currentLink[i].src.replace('$_12.JPG','$_57.JPG');
currentLink[i].src = newLink;
}
}
I have a simple list of images that is being controlled via a CMS (ExpressionEngine). Like this:
<div class="wrapper">
<img src="#" />
<img src="#" />
<img src="#" />
<img src="#" />
<img src="#" />
<img src="#" />
<img src="#" />
<img src="#" />
</div>
What I want to do is for every 5 images, wrap them in a div with a class of "slide." To look like this:
<div class="wrapper">
<div class="slide">
<img src="#" />
<img src="#" />
<img src="#" />
<img src="#" />
<img src="#" />
</div>
<div class="slide">
<img src="#" />
<img src="#" />
<img src="#" />
</div>
</div>
The reason I am not manually coding the "" in is because of a jQuery content slider that I am using which requires every 5 images to be wrapped inside a slide div.
I'm not sure how what the code in ExpressionEngine would be to do this, but I figure it might just be easier to use Javascript to wrap every 5 images with the div. And to just have ExpressionEngine output the different images all at once.
Any help?
Here's one way:
Example: http://jsfiddle.net/T6tu4/
$('div.wrapper > a').each(function(i) {
if( i % 5 == 0 ) {
$(this).nextAll().andSelf().slice(0,5).wrapAll('<div class="slide"></div>');
}
});
Here's another way:
Example: http://jsfiddle.net/T6tu4/1/
var a = $('div.wrapper > a');
for( var i = 0; i < a.length; i+=5 ) {
a.slice(i, i+5).wrapAll('<div class="slide"></div>');
}
You can just create a div for every fith element and move the links into them using the append method:
var wrapper = $('.wrapper');
var div;
$('a', wrapper).each(function(i,e){
if (i % 5 == 0) div = $('<div/>').addClass('slide').appendTo(wrapper);
div.append(e);
});
Demo: http://jsfiddle.net/Guffa/ybrxu/
I think this would do that:
var links = $('.wrapper').children();
for (var i = 0, len = links.length; i < len; i += 5) {
links.slice(i, i + 5).wrapAll('<div class="slide"/>');
}
Try this:
$(function(){
var curDiv = null;
var mainDiv = $("div.wrapper");
$("span", mainDiv).each(function(i, b){
if(i%5 == 0) {
curDiv = $("<div class='slide'/>").appendTo(mainDiv);
}
curDiv.append(b);
});
});
You need to use jQuery slice with wrap
Check this question
Use slice() to select the element subset then wrapAll() to wrap the div around them. Here's a function that does that.
var wrapEveryN = function(n, elements, wrapper) {
for (var i=0; i< elements.length; i+=n) {
elements.slice(i,i+n).wrapAll(wrapper);
}
}
wrapEveryN( 5, $(".wrapper a"), '<div class="slide"></div>' );
Demo: http://jsfiddle.net/C5cHC/
Note that the second parameter of slice may go out of bounds, but jQuery seems to handle this automatically.