How do I load 2 different size images based on viewport?

3 replies
  • WEB DESIGN
  • |
I am trying to figure out how to load two different images, based on the value of viewport.

For example, take two images: "image1.jpg" and "image2.jpg".

If (window.open[this.selectedindex].value > 320)
then I want to load image2.jpg, otherwise I want to
load image1.jpg instead.

Problem is: How do I specify which image to load in the <img> tag?

Any solution or suggestions would be greatly appreciated!

-Ken
#based #images #load #size #viewport
  • Profile picture of the author WPThemeGuru
    i think you can use this approach similar to this
    if(window.width >768) {

    var img = $('<img />',
    { id: 'Myid',
    src: 'MySrc.gif',
    alt:'MyAlt'})
    .appendTo($('#YourDiv'));
    } else {

    var img2 = $('<img />',
    { id: 'Myid',
    src: 'MySrc.gif',
    alt:'MyAlt'})
    .appendTo($('#YourDiv'));

    }

    if you are developer then you can understand this approach.
    {{ DiscussionBoard.errors[10041728].message }}
    • Profile picture of the author rhinocl
      Just wondering why you can't load these as background images and change them with media queries in the css?
      {{ DiscussionBoard.errors[10041966].message }}
    • Profile picture of the author kenetrix
      Originally Posted by WPThemeGuru View Post

      i think you can use this approach similar to this
      if(window.width >768) {

      var img = $('<img />',
      { id: 'Myid',
      src: 'MySrc.gif',
      alt:'MyAlt'})
      .appendTo($('#YourDiv'));
      } else {

      var img2 = $('<img />',
      { id: 'Myid',
      src: 'MySrc.gif',
      alt:'MyAlt'})
      .appendTo($('#YourDiv'));

      }

      if you are developer then you can understand this approach.
      OK, I get what you are doing here, but the question remains:

      How do I specify the image to load using a variable in the
      HTML <img> tag, which calls for a URL as the target for
      the "SRC=" attribute?

      For example, <img src=img1> won't work, since it is seen as an
      invalid HTML statement.

      I have searched all over, but have found no way to accomplish this.

      Any ideas?

      Thanks,
      Ken
      {{ DiscussionBoard.errors[10042149].message }}

Trending Topics