I am trying to change the file path for an image depending on the width of the screen. I have gotten it to work so far as the file path does change but it ONLY affects the first element in the sense that it changes ALL file paths to the same one.
When I view my code in the browser both image 1 and image 2 are replaced with src="Images/image.jpg". Could someone help me in identifying what I need to do/change in order for it to affect EVERY element with the class name "swap-image" uniquely?
As in, change
src="Images/image.jpg"
src="Images/image1.jpg"
to
src="Images/tablet/image.jpg"
src="Images/tablet/image1.jpg"
Thank you in advance.
<body>
<img class="swap-image" src="Images/image.jpg" />
<img class="swap-image" src="Images/image1.jpg" />
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function () {
var swapImageClass = document.getElementsByClassName("swap-image");
var i;
for (i = 0; i < swapImageClass.length; i++) {
var src = $(swapImageClass).attr('src'); // "Images/image.jpg"
var tarr = src.split('/'); // ["static","Images","banner","image.jpg"]
var file = tarr[tarr.length - 1]; // "image.jpg"
var data = file.split('.')[0]; // "image"
$(window).on('load resize', function () {
$(swapImageClass).each(function () {
if ($(window).width() > 1025) {
$(swapImageClass).attr('src', 'Images/' + file);
}
else if ($(window).width() > 481 && $(window).width() < 1024) {
$(swapImageClass).attr('src', 'Images/tablet/' + file);
}
else if ($(window).width() > 0 && $(window).width() < 480) {
$(swapImageClass).attr('src', 'Images/mobile/' + file);
}
});
});
};
});
</script>
</body>
We base the filename on the current element in the loop and bind an eventlistener to it.
$(document).ready(function() {
var swapImageClass = $('.swap-image');
swapImageClass.each(function(index) {
var filename = $(this).attr('src').split('/').pop(),
img = $(this);
$(window).on('load resize', function() {
var w = $(window).width();
if (w > 1025) {
img.attr('src', 'Images/' + filename);
} else if (w > 481 && w < 1024) {
img.attr('src', 'Images/tablet/' + filename);
} else if (w > 0 && w < 480) {
img.attr('src', 'Images/mobile/' + filename);
}
});
});
});
When you are using jquery I think you can simply use class name and each() loop.
$(window).on('load resize', function () {
$(".swap-image").each(function () {
var src = $(this).attr('src'); // "Images/image.jpg"
var tarr = src.split('/'); // ["static","Images","banner","image.jpg"]
var file = tarr[tarr.length - 1]; // "image.jpg"
if ($(window).width() > 1025) {
$(this).attr('src', 'Images/' + file);
}
else if ($(window).width() > 481 && $(window).width() < 1024) {
$(this).attr('src', 'Images/tablet/' + file);
}
else if ($(window).width() > 0 && $(window).width() < 480) {
$(this).attr('src', 'Images/mobile/' + file);
}
});
});
check this function here https://jsfiddle.net/7619099p/
Just modifying your code here, was this the expected?
$(document).ready(function(e) {
//Here we are saving the file name as a data attribute to each images
$(".swap-image").each(function(index, element) {
var tarr = $(element).attr("src").split('/');
var file = tarr[tarr.length - 1];
$(element).data("filename",file);
});
$(window).on('load resize', function () {
$(".swap-image").each(function () {
// and here we are using the saved data attribute(filename) for new path [$(this).data("filename")] on resize.This will give you individual new paths based on screen resolution.
if ($(window).width() > 1025) {
$(swapImageClass).attr('src', 'Images/' + $(this).data("filename"));
}
else if ($(window).width() > 481 && $(window).width() < 1024) {
$(swapImageClass).attr('src', 'Images/tablet/' + $(this).data("filename"));
}
else if ($(window).width() > 0 && $(window).width() < 480) {
$(swapImageClass).attr('src', 'Images/mobile/' + $(this).data("filename"));
}
});
});
});
Related
$(function(){
var x = $('.my__list').children();
for (var i = 0; i < x.length ; i += 2) {
var windowSize = $(window).width();
if(windowSize < 500) {
x.slice(i,i+1).wrapAll('<div class="'+ i +'"></div>');
}
if(windowSize > 500) {
x.slice(i,i+2).wrapAll('<div class="'+ i +'"></div>');
console.log("test");
}
}
});
I want to unwrap all my list when the browser's width change. At the moment it only change when the user refresh the browser. Thank you.
I get the source from https://codepen.io/Kibs/pen/aNzvBG
I fixed the problem by using a row function from slick and some modification inside slick.js. There is some bug from rows: 2 to rows: 1 when i used it in responsive settings.
I got the answer from here and it works for me:
Slick.prototype.buildRows = function() { ... }
Slick.prototype.cleanUpRows = function() { ... }
and change the if condition from if(.options.rows > 1) to if(.options.rows > 0)
You can hook this up to the window resize event, or in JQuery $(window).resize():
$(function(){
resizeAndWrap(); // Runs once on page load
$(window).resize(function() {
resizeAndWrap(); // Runs everytime window is resized
});
});
function resizeAndWrap() {
var x = $('.my__list').children();
for (var i = 0; i < x.length ; i += 2) {
var windowSize = $(window).width();
if(windowSize < 500) {
x.slice(i,i+1).wrapAll('<div class="'+ i +'"></div>');
}
if(windowSize > 500) {
x.slice(i,i+2).wrapAll('<div class="'+ i +'"></div>');
console.log("test");
}
}
}
Here is the codepen example with my changes
my img has 3 attribute but if has one attribute (data-web-src,data-tablet-src,data-mobil-src) than set my src than one of them attribute is that possible ?
please click to see on codepen
function noLazyImages(e) {
$(e + '.lazy_res').attr('src', function(_, oldSrc) {
var elData = $(this).data(),
winWidth = $(window).width();
if (winWidth >= 768 && winWidth < 960) {
return elData['webSrc']
} else if (winWidth < 768 && winWidth >= 480) {
return elData['tabletSrc']
} else if (winWidth < 480) {
return elData['mobilSrc']
} else if (winWidth > 960) {
return elData['webSrc']
}
})
}
$(document).ready(function() {
noLazyImages("body img");
})
img {
width: 300px;
}
<img class="lazy_res" data-web-src="http://image.prntscr.com/image/bdf1d94b64104ef2acd2ceee19882cd1.jpg" data-mobil-src="http://image.prntscr.com/image/caa51ab4900448589201207e57b2630f.jpg" data-tablet-src="http://image.prntscr.com/image/4b2862a292b543139daa7805a58c17fd.jpg"
/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I think the following code will do what you want.
I removed the data-tablet-src from the img tag which is there in the question snippet so that you can run both and compare the results.
Logic
if(elData['tabletSrc']) will be false if elData['tabletSrc'] is not present. So it will return return elData['webSrc'] instead.
function noLazyImages(e) {
$(e + '.lazy_res').attr('src', function(_, oldSrc) {
var elData = $(this).data(),
winWidth = $(window).width();
if (winWidth < 768 && winWidth >= 480) {
if(elData['tabletSrc']){
return elData['tabletSrc'];
}
} else if (winWidth < 480) {
if(elData['mobilSrc']){
return elData['mobilSrc'];
}
}
return elData['webSrc'];
});
}
$(document).ready(function() {
noLazyImages("body img");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="lazy_res" data-web-src="http://image.prntscr.com/image/bdf1d94b64104ef2acd2ceee19882cd1.jpg" data-mobil-src="http://image.prntscr.com/image/caa51ab4900448589201207e57b2630f.jpg"
/>
Your script work fine you just need to add listener to window resize event:
$(document).ready(function() {
noLazyImages("body img"); // on Document ready
$( window ).resize(function() {
noLazyImages("body img"); // on window Resize
});
})
my image has data-web-src, data-tablet-src and data-mobil-src if my img tag has .lazy_res class instead of .lazyload then set value of data-web-src to src on web, but if screen (or device) is tablet than set data-tablet-src value's to src I want to do this for all images on my web page but I can’t find a solution here you are my code
$(document).ready(function() {
function noLazyImages(e) {
var getWebSrc = $(e).attr("data-web-src");
var getTabletSrc = $(e).attr("data-tablet-src");
var getMobilSrc = $(e).attr("data-mobil-src");
if ($(".box img").hasClass("lazy_res")) {
if ($(window).width() > 960) {
$(e).attr("src", getWebSrc);
} else if ($(window).width() < 768) {
$(e).attr("src", getTabletSrc);
}else if ($(window).width() < 480) {
$(e).attr("src", getMobilSrc);
}
} else {
// do nothing..
}
}
noLazyImages(".box img");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
<img class="lazy_res" data-web-src="http://image.prntscr.com/image/bdf1d94b64104ef2acd2ceee19882cd1.jpg" data-mobil-src="http://image.prntscr.com/image/caa51ab4900448589201207e57b2630f.jpg" data-tablet-src="http://image.prntscr.com/image/4b2862a292b543139daa7805a58c17fd.jpg"/>
</div>
you need to loop over all of them and get and set instance specific values
Can do it using attr(function)
function noLazyImages(e) {
$(e + '.lazy_res').attr('src', function(_, oldSrc) {
var elData = $(this).data(),
winWidth = $(window).width();
if (winWidth > 960) {
return elData['webSrc']
} else if (winWidth < 768 && winWidth >=480) {
return elData['tabletSrc']
} else if (winWidth < 480) {
return elData['mobilSrc']
}
})
}
DEMO
I've got the following code. I am working on an array. I found a javascript array instructions..if this is wrong, I'd love help to find out if there is a jQuery version of this.
My issue comes into play when I am trying to implement an if() and else if() conditions to the array. I am using i (variable) to count items in array.
It is saying that there is an issue on the line that reads else if(width <= Sizes[i]) { $(element).attr('src', 'images/' + Sizes[i] + '/' + name[name.length - 1]) }
Also, it appears that the array isn't working at all. Its pulling the default image.
I am probably doing this wrong. I am doing this trying to figure out how arrays work and implementing them into a code I already have. Can someone please help solve this? It isn't working. The code works perfectly without the array, so it is something in the array.
$(document).ready(function() {
window.onresize = resize;
function resize() {
var img = $('img.resizable');
var width = $(window).innerWidth();
var Sizes, sLength, i;
img.each(function(index, element) {
var name = element.src.split('/') // Split is a native javascript function, which 'splits' the string into an array with the components
Sizes = [2880, 1920, 1000, 600];
sLength = Sizes.length;
for (i = 0; i < sLength; i++) {
if (i == 0) {
if (width <= Sizes[i]) {
$(element).attr('src', 'images/' + Sizes[i] + '/' + name[name.length - 1])
}
}
if (i > 0) {
else if (width <= Sizes[i]) {
$(element).attr('src', 'images/' + Sizes[i] + '/' + name[name.length - 1])
}
}
} else {
$(element).attr('src', 'images/2880/' + name[name.length - 1])
}
})
}
resize();
});
The actual script I am trying to convert
$(document).ready(function() {
window.onresize = resize;
function resize() {
var img = $('img.resizable');
var width = $(window).innerWidth();
img.each(function(index, element) {
var name = element.src.split('/') // Split is a native javascript function, which 'splits' the string into an array with the components
if(width <= 600) {
$(element).attr('src', 'images/600/' + name[name.length - 1]) // This name[name.length -1] trick is being used to select the 'last value in the string' based on the length of the string.
}
else if(width <= 1000) {
$(element).attr('src', 'images/1000/' + name[name.length - 1])
}
else if(width <= 1920) {
$(element).attr('src', 'images/1920/' + name[name.length - 1])
}
else {
$(element).attr('src', 'images/2880/' + name[name.length - 1])
}
})
}
resize();
});
Here's a solution that simplifies matters by using Array#filter to select the appropriate width; the appropriate size will sit in the first position of the sizes array:
$(document).ready(function() {
window.onresize = resize;
resize();
});
function resize() {
// use $.each to iterate over each element
$('img.resizable').each(function(index, element) {
// get the image name directly
var name = element.src.substring(element.src.lastIndexOf('/'));
// let's whittle down sizes to *only* those that fit our screen width
var sizes = [600, 1000, 1920, 2880].filter(function(s){
return window.innerWidth < s || s == 2880;
});
// update the image with whatever size is in the first position
$(element).attr('src', 'images/' + sizes[0] + name);
});
}
We can move the resize function definition outside of your on ready handler, to make it globally accessible. We can dispense with use of split to just find whatever is after the last / (the image name). And we can avoid using loops and if statements with breaks, which tend to be difficult to read and maintain.
This is a bit verbose and follows your array starting with the largest value which I used instead of hard coding that for the "largest" (last) conditional. Remove the console logs prior to deployment.
$(document).ready(function() {
window.onresize = resize;
var sizes = [2880, 1920, 1000, 600];
function resize() {
console.log('si');
var img = $('img.resizable');
var width = $(window).innerWidth();
img.each(function(index, element) {
var name = element.src.split('/');
name = name[name.length - 1];
var setto = 0;
for (var i = sizes.length; i >= 0; i--) {
console.log(i,width,setto, sizes[i]);
if (width <= sizes[i]) {
setto = sizes[i];
break;
}
}
setto = width >= sizes[0] ? sizes[0] : setto;
$(element).attr('src', 'images/' + setto + '/' + name);
});
}
resize();
});
You are referencing Sizes array using lowercase s at sizes[i], where sizes is not defined
I hope this could solve your problem:
$(window).on('resize', function (e) {
var img = $('img.resizable');
var width = $(window).innerWidth();
var Sizes, sLength, i;
img.each(function (index, element) {
var name = element.getAttribute('src').split('/') // Split is a native javascript function, which 'splits' the string into an array with the components
Sizes = [2880, 1920, 1000, 600].sort((a, b) => {return a - b;});
sLength = Sizes.length;
for (i = 0; i < sLength; i++) {
if (width <= Sizes[i]) {
$(element).attr('src', 'images/' + Sizes[i] + '/' + name.pop())
console.log('New src for image N. ' + index + ' is: ' + $(element).attr('src'));
break;
}
}
});
});
$(function () {
// simulate a resize on dom ready: for testing
$(window).trigger('resize');
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<img class="resizable" src="images/100/nameofimage1.png">
<img class="resizable" src="images/100/nameofimage2.png">
You want something like this probably:
sort_array_small_to_large(Sizes)
for (i = 0; i < Sizes.length; i++)
{
if (width <= Sizes[i])
{
size = Sizes[i]
break
}
}
$(element).attr('src', 'images/' + size + '/' + name[name.length - 1])
I have the following piece of jQuery that checks the width of the browser on load, and runs accordingly. But to make sure the div keeps the right size when the browser-width is changed, I have placed the same piece of code in $(window).resize(function() {..});.
This seems very weird and unnecessary, so I'm wondering how I can place the code only once and have it run on both .resize and on load.
var windowWidth = $(window).width();
if(windowWidth > 768 && windowWidth < 1223){
$('.banner_image').show();
$('.banner_image').height($('.banner .span3').height());
$('.banner .span12 img').hide();
}
else {
$('.banner_image').hide();
$('.banner .span12 img').show();
}
$(window).resize(function() {
var windowWidth = $(window).width();
if(windowWidth > 768 && windowWidth < 1223){
$('.banner_image').show();
$('.banner_image').height($('.banner .span3').height());
$('.banner .span12 img').hide();
}
else {
$('.banner_image').hide();
$('.banner .span12 img').show();
}
});
You can trigger the event after binding the event:
$(window).resize(function() {
var windowWidth = $(window).width();
if(windowWidth > 768 && windowWidth < 1223){
$('.banner_image').show();
$('.banner_image').height($('.banner .span3').height());
$('.banner .span12 img').hide();
}
else {
$('.banner_image').hide();
$('.banner .span12 img').show();
}).resize();//resize to trigger on load
Working Demo
Just store the function in a variable and execute it everytime you want to:
$(window).load(function() {
wFunc();
});
$(window).resize(function() {
wFunc();
});
var wFunc = function() {
var windowWidth = $(window).width();
if(windowWidth > 768 && windowWidth < 1223){
$('.banner_image').show();
$('.banner_image').height($('.banner .span3').height());
$('.banner .span12 img').hide();
}
else {
$('.banner_image').hide();
$('.banner .span12 img').show();
}
}