Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery to change image src when browser is resized

I have two different sized images, one if for screens smaller than 759px, the other is for screens larger than 759px.

I have managed to get the source of the images to change when the document loads depending on the window width. But I really would like to be able to do this when the browser is resized as well but for the life of me I can't get it to do that, it only seems to work when the page is initially loaded.

This is my code:

$(document).ready(function() {
    function imageresize() {
        var contentwidth = $(window).width();
        if ((contentwidth) < '700'){
            $('.fluidimage').each(function(){
                var thisImg = $(this);
                var newSrc = thisImg.attr('src').replace('x2', 'x1');
                thisImg.attr('src', newSrc);
            });
        } else {
            $('.fluidimage').each(function(){
                var thisImg = $(this);
                var newSrc = thisImg.attr('src').replace('x1', 'x2');
                thisImg.attr('src', newSrc);
            });
        }
    }

    imageresize();//Triggers when document first loads

    $(window).bind("resize", function(){//Adjusts image when browser resized
        imageresize();
    });
 }); 
like image 400
Daimz Avatar asked Jan 16 '23 13:01

Daimz


2 Answers

Try to use css3 media queries instead of doing it in jQuery or javascript.

http://css-tricks.com/media-queries-sass-3-2-and-codekit/

Consider using "img-src" class on a . Whenever the screen is resized b/w 600px to 900px; x2.jpg will be loaded. By default x1.jpg will be used.

Ex:

.img-src {
   background-image: url("http://imageurlhere.com/x1.jpg");
}


@media (min-device-width:600px) and (max-width:900px) {
  .img-src {
      background-image: url("http://imageurlhere.com/x2.jpg");
   }
}
like image 148
Suriyamoorthy Baskaran Avatar answered Jan 28 '23 08:01

Suriyamoorthy Baskaran


First try this...

change your follwoing line of code

$(window).bind("resize", function(){//Adjusts image when browser resized
        imageresize();
    });

to

// Bind event listener
    $(window).resize(imageresize);

and put alert inside imageresize to see if it works or not...

In case above do not work out...I believe there is one problem probably..

in your code you have

$(document).ready(function() {

 $(window).bind("resize", function(){//Adjusts image when browser resized
        imageresize();
    });
}

So the function for reside inside jquery which may not work well. On top of that try using simple javascript; i had similar problem and solved using plain javascript and jquery did not work in some browsers.

Sound strange enough to stop you try at it but would work...

like image 36
Jigar Pandya Avatar answered Jan 28 '23 07:01

Jigar Pandya