0

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")     
 }
 }
 });
 });
3
  • You can push that into a common function and call that method. By the way, the window ready is a strange event, never seen it in use. Use window load(). Also you haven't calculated the new window size on resize() Commented Jun 29, 2015 at 2:45
  • @Shaunak: Unless you know you need load, you usually want ready. ready will be fired once all of the page’s HTML has loaded and the DOM is complete; load waits until after all images, stylesheets, etc. have loaded as well, which could be significantly longer. Commented Jun 29, 2015 at 2:47
  • I know. But I have never seen a ready() event attached to window. It is usually related to the document. There seems no connection of DOM and the window. Commented Jun 29, 2015 at 2:50

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.