1

I have this HTML

<div class="picture"></div>

and depending on the viewport width, I'd like to add either a small or a large image to the div, so that it will look like this:

<div class="picture"><img src="small.jpg></div>

Here's some jQuery I found somewhere on the web which seems to do exactly what I want. The only part where I'm stuck now is the img src="....jpg" thing. How can I translate this into jQuery?

jQuery(document).ready(function() {
    $(window).resize(function() {
        var window_width = $(document).width();
        if (window_width <= 1024) {

            img src = "small.jpg"

        } else {

            img src = "large.jpg"

        }
    });
});

Thanks!

4
  • Is The <img> tag is already present you just want to chage the source? Commented Jun 23, 2015 at 18:25
  • 4
    try $('.picture').prepend('<img src="small.png" />') Commented Jun 23, 2015 at 18:26
  • 1
    @Varun No, the img tag is not present. Just the empty div Commented Jun 23, 2015 at 18:30
  • Just check my answer below, i have answered for both cases to be safe @Groen91 Commented Jun 23, 2015 at 18:31

7 Answers 7

2

If you are creating a <img>

$(window).resize(function() {
    var window_width = $(document).width();
    if (window_width <= 1024) {
        $(".picture").html("<img src='small.jpg'>");
    } else {
        $(".picture").html("<img src='large.jpg'>");
    }
});

or if you just want to assign a source,

$(window).resize(function() {
    var window_width = $(document).width();
    if (window_width <= 1024) {
        $(".picture").find("img").attr("src", "small.jpg");
    } else {
        $(".picture").find("img").attr("src", "large.jpg");
    }
});
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, I think the first one is what I'm looking for. Will test it now and report :)
Ok, this works fine, thanks again! The only strange thing now is when I load the page, both images don't show up, only when I change my browser size. Is there a simple way to fix it, so that they show up on default?
@Groen91 You want both the images on load or any specific one?
Yes, the specific one, not both.
@Groen91 I guess it would be the same code,but in $(document).ready() ,better put it inside a function and call it on load as well as on scroll.
2

You can check if div has img element updated its src else create new img element and append it.

jQuery(document).ready(function() {
    $(window).resize(function() {
        var window_width = $(document).width();
        var imgsrc = "large.jpg"
        if (window_width <= 1024) {
            imgsrc = "small.jpg"
        }
        //Picture element
        var picture = $('.picture');

        //Picture has img element update its src else append new img tag
        if (picture.find('img').length) {
            picture.find('img').attr('src', imgsrc );
        } else {
            picture.append('<img src="' + imgsrc + '" />')
        }
    });
});

Comments

1

Try this code snippet:

jQuery(document).ready(function () {
    $(window).resize(function () {
        var window_width = $(document).width();
        var src = (window_width <= 1024) ? "small.jpg" : "large.jpg";
        $('.image').remove(); //Remove in order to avoid multiple images to be added.
        $('.picture').prepend($('<img />', {src: src, class: 'image'}));
    });
});

Comments

0

Like this :

$('.picture').find('img').attr('src','small.jpg');

Comments

0

You'll need to update the attributes.

In jQuery, you'll do something like this to update the src:

$('<img>') // create a new img node
  .attr('src', 'newsrc')  // set the src to your desired source
  .load(function(){
     this.appendTo('.picture');  // once the source has finished loading, append it to the <div>
   });

For more information on this, check out this other Stack Overflow post:

Changing the image source using jQuery

1 Comment

there is no <img> tag. he needs to add it to the div dynamically
0

Cache both images up front in jQuery objects constructed with image elements pointing to their source.

Then, use your conditional statement to store the string for source and reference it to place the cached image element on the page.

jQuery(document).ready(function() {
    //cache images
    var imgSet = {
        "small.jpg" : $('<img src="small.jpg" />'),
        "large.jpg" : $('<img src="large.jpg" />')
    };
    $(window).resize(function() {
        var window_width = $(document).width();
        var imgsrc;
        if (window_width <= 1024) {
            imgsrc="small.jpg";
        }else {
            imgsrc="large.jpg"
        }
        //use cached image element
        $('.picture').empty().append(imgSet[imgsrc]);
   });
});

Comments

0

In jquery you can use append

$('.picture').append('<img src="small.png"/>'); 

2 Comments

Thought it had img tag too! Updated the answer now
great. you also need to add single quotes inside append.

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.