Change image source folder for mobile version with javascript - javascript

Sorry I'm a newbie with JS and I've been having trouble with some JS I found here on stackoverflow. My situation is that I have a div with two images inside, and I want to change the source path of those images when the window is less than 480px. My code is this:
<div id="bigFoto">
<img src="img/photo1.jpg" alt="text for alt" id="photo1">
<img src="img/photo2.jpg" alt="text for alt" id="photo2">
</div>
And The current script I'm running is:
$(window).resize(function(){
var width = $(window).width();
if (width < 481) {
$("#bigFoto img#photo1").attr("src","img/mobile/photo1.jpg");
$("#bigFoto img#photo2").attr("src","img/mobile/photo2.jpg");
}
else{
$("#bigFoto img#photo1").attr("src","img/photo1.jpg");
$("#bigFoto img#photo2").attr("src","img/photo2.jpg");
}
});
This script is working right, but now let's say I want that div to have 20 images, my guess is that I would have to add every one of them in this script right?
The real question: is there a way to target all images instead and just add the /mobile part on the source path? ,since the filename remains the same.
Thanks so much for your help!

You can use jQuery's each function to loop through all the elements returned by a query
$(window).resize(function(){
var width = $(window).width();
if (width < 481) {
$("#bigFoto img").each(function(index){
var src = $(this).attr("src")
var photoName = src.substr(src.lastIndexOf("/"));
$(this).attr("src", "img/mobile/"+photoName)
})
}
else{
$("#bigFoto img").each(function(index){
var src = $(this).attr("src")
var photoName = src.substr(src.lastIndexOf("/"));
$(this).attr("src", "img/"+photoName)
})
}
});

Related

Change img src with another img attribute on Responsive

I created a attribute for img tag as in the example code like data-tablet, data-mobil
<div class="myDiv">
<img src="img-1.jpg" data-tablet="img-2.jpg" data-mobil="img-3.jpg">
</div>
and I want if my screen change for tablet my img src change with data-tablet or my screen is for mobil my src must change with data-mobil
MY JS
$(document).ready(function(){
$(window).resize(function(){
var tabletSrc = $(".main-carousel img").attr("data-tablet");
var mobilSrc = $(".main-carousel img").attr("data-mobil");
if($(window).width() <=768){
$('img').attr('src',tabletSrc);
}
if($(window).width() <=480 ) {
$('img').attr('src',mobilSrc);
}
});
});
click to see my works
question is how can I do that I want if u click you gonna see nothing work
note: I don't want to use srcset or css
Please see this CodePen for a working version.
There were some issues with your code:
Both the case for mobile and tablet was executed in the mobile case.
$(".main-carousel img") is a collection of images. Instead of that, you probably want to operate on a single image. This can be done with the help of .each().
Here is the relevant code:
$(window).resize(function() {
if ($(window).width() <= 480) {
$('img').each(function() {
$(this).attr('src', $(this).attr('data-mobil'));
});
} else if ($(window).width() <= 768) {
$('img').each(function() {
$(this).attr('src', $(this).attr('data-tablet'));
});
}
});
Use srcset instead of js based validations for device dimensions.
<img src="images/space-needle.jpg"
srcset="images/space-needle.jpg 200w, images/space-needle-2x.jpg 400w,
images/space-needle-hd.jpg 600w">
So, now the browser will automatically device which image to download and show depending on the browser dimensions.
Check out more
https://www.sitepoint.com/how-to-build-responsive-images-with-srcset/
You can try this for you carousel multiple images
function makeResize(){
var imageSrc = $(".myDiv img");
if($(window).width() <=768 && $(window).width()>480){
$(imageSrc).each(function(key,value){
$(value).attr('src',$(value).data('tablet'));
});
}else if($(window).width() <=480 ) {
$(imageSrc).each(function(key,value){
$(value).attr('src',$(value).data('mobile'));
});
}else{
$(imageSrc).each(function(key,value){
$(value).attr('src',$(value).data('default'));
});
}
}
$(document).ready(function(){
$(window).resize(function(){
makeResize();
});
makeResize();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="myDiv">
<img src="org1.jpg" data-default="org1.jpg" data-tablet="tablet1.png" data-mobile="mobile1.jpg">
<img src="org2.jpg" data-default="org2.jpg" data-tablet="tablet2.png" data-mobile="mobile2.jpg">
<img src="org3.jpg" data-default="org3.jpg" data-tablet="tablet3.png" data-mobile="mobile3.jpg">
</div>
Note Copy and add proper image source then try. Above code will work for multiple images.
You are using wrong class name. Your div has class "myDiv" and you are selecting by "main-carousel"
$(document).ready(function(){
$(window).resize(function(){
var tabletSrc = $(".myDiv img").attr("data-tablet");
var mobilSrc = $(".myDiv img").attr("data-mobil");
if($(window).width() <=768){
$('img').attr('src',tabletSrc);
}
if($(window).width() <=480 ) {
$('img').attr('src',mobilSrc);
}
});
});
Here is codepen
Keep the short width first. Your validation always goes for tablet first. since 480 < 768
Change your conditions like this.
$(window).resize(function(){
var tabletSrc = $(".someDiv img").attr("data-tablet");
var mobilSrc = $(".someDiv img").attr("data-mobil");
var imgSrc = "defaultImageSrc" //src for default image
var windowWidth = $(window).width();
if(windowWidth <= 480 ) { //first small width
imgSrc = mobilSrc;
}else if(windowWidth <= 768){ //next larger one
imgSrc = tabletSrc;
} //if else default will there for you which is initialised there.
});
Try this:
$(window).resize(function(){
var realImg = $(".main-carousel img").attr();
var tabletSrc = $(".main-carousel img").data("tablet"); //use .data instead of attr
var mobilSrc = $(".main-carousel img").data("mobil");
if($(this).width() <= 768){
$('img').attr('src',tabletSrc);
}
else if($(this).width() <= 480 ) { // use else if instead of if
$('img').attr('src',mobilSrc);
}
else{
$('img').attr('src',realImg);
}
});

On resize, loading an image using the asset function in laravel

I have a header with an image loaded with the asset laravel function :
<img class="logo" src="{{ asset('images/logo-long.gif') }}" id="logo-navbar"></img>
And in my JS script, i want it to check whenever the size of the window is below 700px, the src atribute of the img tag change
So i implemented this :
$(window).resize(function(){
width = $(window).width();
if(width <= 700){
$('#logo-navbar').attr('src', '??');
}else{
$('#logo-navbar').attr('src', '??');
}
});
but i don't know how can i tell my script to generate a path like the asset function of laravel..
Any ideas ?
When you're using JS to change image URL you should't use PHP at all. It's bad practice. Just create image URL manually:
var imageBig = '/images/logo-long.gif';
var imageSmall = '/images/logo-sm.gif';
This is generally not the best approach to do this, but you can do something like:
JavaScript:
$(window).resize(function(){
width = $(window).width();
if(width <= 700){
$('#logo-navbar').attr('src', '/getAsset/images/logo-long.gif');
}else{
$('#logo-navbar').attr('src', '/getAsset/images/logo-long.gif');
}
});
Routes.php
Route::get("/getAsset/{any}", function ($asset) {
return redirect(asset($asset));
})->where('any', '.*');
I do this one of two ways.
I either have some global container
var myApp = {};
where I then can assign various values via a view, I assign the value inline
myApp.url = {{ asset('/') }}
or, if the javascript is in the view
$(window).resize(function(){
var assetUrl = "{{ asset('/') }}";
width = $(window).width();
if(width <= 700){
$('#logo-navbar').attr('src', assetURL +'/images/logo-long.gif');
}else{
$('#logo-navbar').attr('src', assetURL + '/images/logo-long.gif');
}
});
Should note that I generally do this with url(), rather than asset() - I'm not sure if it will work the same exact same way.

changing part of src name with jquery, keeps repeating when window resized

I have code written to find the src of all images inside a particular div and change the src name when the window is less than 900 wide. It works fine upon page refresh, but when I resize the window it continuously runs the code and I get this error
GET
file://macintosh%20hd/Users/jessicamele/Desktop/tom%20mendicino/images/boys3_small_small_small_small.jpg
net::ERR_FILE_NOT_FOUND
It just keeps adding the "_small" over and over again. Here is my code:
<div class="threePicsBoys group">
<img src="images/boys3.jpg" alt="street signs" class="boysPics1">
<img src="images/boys2.jpg" alt="city house" class="boysPics2">
<img src="images/boys1.jpg" alt="2 boys" class="boysPics1">
<img src="images/boys4.jpg" alt="philly signs" class="boysPics2">
<img src="images/boys5.jpg" alt="religious statue" class="boysPics1">
</div>
$(function() {
if (windowWidth <= 900) {
var img = $(".threePicsBoys.group").find("img").map(function() {
var src = $(this).attr("src");
var newName = src.replace(".jpg","_small.jpg");
$(this).attr("src",newName);
});
}
});
}
I could really use some help.
This script will check if the window is so thin that it has to change the src, but will also revert the changes when it have become wider than 900.
I slightly changed the mechanics to make it work. windowWidth, for example, wasn't a declared variable, and the rest didn't seem to do that much either.
var thinWindow = false;
$(window).on('load resize', function(){
if($(window).width() <= 900){
if(!thinWindow){
$('.threePicsBoys.group img').each(function(){
var src = $(this).attr("src");
var newSrc = src.replace(".jpg","_small.jpg");
$(this).attr("src", newSrc);
})
thinWindow = true
}
}else{
if(thinWindow){
$('.threePicsBoys.group img').each(function(){
var src = $(this).attr("src");
var newSrc = src.replace("_small.jpg",".jpg");
$(this).attr("src", newSrc);
})
thinWindow = false
}
}
})
Hope this helps
This code will loop forever when window is less than 900 width. If you wish to you only run on window change width you must add the correct event binding
$(window).resize(function() {
if (windowWidth <= 900)
{
var img = $(".threePicsBoys.group").find("img")
var src = img.attr("src");
if (!(src.indexOf("_small.jpg") > -1))
{
var newName = src.replace(".jpg","_small.jpg");
img.attr("src",newName);
}
}
});

Pre-load Next Image jQuery

I am creating a slideshow using nested li's:
<ul id="ss_images_set">
<li>
<img link="images/koala_1.jpg" />
<p class="img_caption">©Copyright</p>
<p class="img_author">John Merriam</p>
<p class="img_href">http://www.twitter.com</p>
<p class="img_hashtag">JohnMerriam</p>
</li>
I will be uploading new images daily to this slideshow, so there will be many images in the set (hundreds). There are so many pre-loaders out there that I am confused as to what to use to load only the next image.
The slideshow has an image pre-loader, but I don't think it works properly because the next images are clearly not cached (content below slideshow jumps up and down when going to next image).
Here is the pre-loader script:
function preload_images(){
var pre_image = curr_img - 1;
if(pre_image < 0) pre_image = (tot_elements-1);
var curr_obj = 0;
if(!$('#img_preloaded_'+pre_image).length > 0){
curr_obj = slideshow[pre_image];
$('body').append('<img src="'+curr_obj["img_url"]+'" id="img_preloaded_'+pre_image+'" class="preload_box" />');
}
var pre_image = curr_img + 1;
if(tot_elements==pre_image) pre_image = 0;
if(!$('#img_preloaded_'+pre_image).length > 0){
curr_obj = slideshow[pre_image];
$('body').append('<img src="'+curr_obj["img_url"]+'" id="img_preloaded_'+pre_image+'" class="preload_box" />');
}
I don't know why it's not caching. Is it written wrong? Is it in the wrong spot in the following fiddle?
Fiddle with JS: http://jsfiddle.net/doobada/9m9eq/
Current ex. of slideshow (content below jumps up and down): https://www.assembla.com/code/cfrepo/subversion/node/blob/trunk/index.html#image=JohnMerriam
Ok, jQuery is not my strong suite (taking the tuts+ courses now), but this shouldn't be taking me 3 weeks to figure out.
Thanks for your help.
var newImageUrl = 'someimage.png';
/* preload an image using jQuery: */
$('<img>').attr( {
src: newImageUrl
} ).load(function() {
/* image is loaded and could be used */
} );

jQuery find height of an image even if it is not set in the HTML

I have, what I think is, a strange issue. I am running a simple query that finds the largest image on a page. Here is some test data - all images are 32x32 but one is sized to 300x300.
<img src="app/assets/images/icons/blue.png" />
<img src="app/assets/images/icons/error.png"/>
<img src="app/assets/images/icons/info.png" height="300" width="300"/>
If I run a simple query like this:
$('img').each(function(){
console.log($(this).height());
});
I will get 0,0,300 — and not 32,32,300.
Can anyone point me to a better method of finding the size the image is being rendered at?
Thanks.
If the image is "natively" sized, i.e. no width or height are present in the HTML, you'll need to wait for the image to load before you know its size. I use this:
jQuery("img").each(function(){
var img = jQuery(this);
if (img.attr("complete")) {
console.log(img.height());
} else {
img.load(function(){
console.log(img.height());
});
}
});
Make sure you do it after the image is ready in $(img).load(), then it will work. Try JavaScript to verify:
function iLoad(isrc) {
var oImg = new Image();
oImg.src = isrc;
if (oImg.complete) {
window.alert(oImg.src + ' ' + oImg.width + ' x ' + oImg.height);

Categories