schenker
schenker

Reputation: 953

How can i avoid writing the conditional statement twice for this jquery code?

i have a piece of jquery code that first checks device size when loading and for every subsequent windows resize it will put in the correct image. I found myself having to write the conditional statement twice. Is there a better way to achieve this? Thanks.

$(window).ready(function() {
var wi=$(window).width();
//upon loading for first time, show correct image size
if (wi <=420)
{
$("#main").find("img").attr("src","images/main_image_xs.jpg")
 } 
else
{
   $("#main").find("img").attr("src","images/main_image_default.jpg")     
}
}

$(window).resize(function() {
// When resizing windows, show corect image size
if (wi <=420)
{
 $("#main").find("img").attr("src","images/main_image_xs.jpg")
 } 
 else
 {
   $("#main").find("img").attr("src","images/main_image_default.jpg")     
 }
 }
 });
 });

Upvotes: 0

Views: 24

Answers (1)

icktoofay
icktoofay

Reputation: 129001

Use a named function, not an anonymous function.

function adjustImageSize() {
    var imageURL;
    if($(window).width() <= 420) {
        imageURL = "images/main_image_xs.jpg";
    }else{
        imageURL = "images/main_image_default.jpg";
    }
    $("#main img").attr("src", imageURL);
}

$(window).ready(adjustImageSize).resize(adjustImageSize);

Better yet, see if you can use media queries—then your website can adapt without needing JavaScript.

Upvotes: 2

Related Questions