How To Change Img Src Directory Or Image File Name With Jquery Or PHP
I would like to change the image path directory or append the the image file by adding a class to the parent container. Example: If I add a class of 'large' to the parent img conta
Solution 1:
For example like this, using lastIndexOf
$function() {
var img = $(".large-image > img").each(function() { // for each img found
var src = $(this).attr("src"); // get the src
var path = src.substring(0,src.lastIndexOf('/')); // get the path from the src
var fileName = src.substring(src.lastIndexOf('/')); // and filename
var newSrc = path+"/large"+fileName; // re-assemble
// or change filename:
// var newSrc = path+"/"+fileName.replace(".jpg","-large.jpg"); // re-assemble
$(this).attr("src",newSrc);
});
});
Solution 2:
you can use jquery to change the src, split it, and add your new folder
<div class="large-image">
<img src="/images/services/image.jpg" alt="" />
</div>
$('.large-image > img').each(function(){
var msrc=$(this).attr('src');
msrc=msrc.split('/'); //images, services, image.jpg
var lastelem = msrc.pop(); //images, services // lastelem: image.jpg
msrc.push('large'); //images, services, large // lastelem: image.jpg
msrc.push(lastelem); //images, services, large, image.jpg
msrc=msrc.join('/'); //"images/services/large/image.jpg"
$(this).attr('src', msrc);
})
Post a Comment for "How To Change Img Src Directory Or Image File Name With Jquery Or PHP"