sam dravitzki
sam dravitzki

Reputation: 1

I need to change the img depending on the windows width

What I want is to make an image change when the window is smaller.

For example when the window is <900px it will be one image. but when the widow is >900 it will be a different image.

I can't figure out how to do this with different window size?

Upvotes: 0

Views: 61

Answers (7)

Adnan
Adnan

Reputation: 1

You can do it by jQuery

$(window).resize(function() { 
  if($(window).width() > 900){
   $('Your target div').html('<img src="Ur Image" />');
  } 
  else { 
  $('Your target div').html('<img src="Ur Different Image" />'); 
  } 
});

Upvotes: 0

sqsinger
sqsinger

Reputation: 510

What you need is an event listener. Every time the window resizes, have jQuery check the width. If it is above/below a certain threshold, adjust the image. Something like this:

$(window).resize(function() {
    var width = $(window).width();
    $("#width-num").html(width);

    if(width > 500) {
        $("#img-change").attr("src", img2);
    } else {
        $("#img-change").attr("src", img1);
    }   
});

See fiddle for example

Upvotes: 0

Sunny Techo
Sunny Techo

Reputation: 68

You will also use jquery to do this:-

var width = $(window).width();

if(width > 900){
     $('#img-id').attr('src','path/to/image');
}else{
    $('#img-id').attr('src','path/to/image');
}

Upvotes: 0

varad mayee
varad mayee

Reputation: 619

You can do it by CSS as below

 @media screen and (max-width: 900px) {
 #id{/*Your CSS here */} }

Upvotes: 0

Musa
Musa

Reputation: 65

You can use media query, and set a display:none for the desired width.

<img src="http://*" class="image1"></img>

@media (max-width:900px) { .image1 { display:none } }

Upvotes: 0

Abhay Naik
Abhay Naik

Reputation: 405

You can try this jquery:

var width = $(window).width(); 
if (width >= 900) {
    //do something
} else {
    //do something else
}

Upvotes: 0

kapantzak
kapantzak

Reputation: 11750

You can use css media queries like this:

@media (max-width:900px) {
   #targetElement { background-image: url('...') }
}

@media (min-width:901px) {
   #targetElement { background-image: url('...') }
}

@media

Upvotes: 2

Related Questions