Reputation: 277
Hi I'm trying to change an image as the window width changes without refreshing the page.
$(document).ready(function(){
if($(window).width() <= 600) {
$('#img').attr('src','images/image.png');
$('#img').css({"width": "50px"});
};
});
This is the Jquery code that I've written but it only works when I refresh the page. how do I change the image when the width of window reaches 600px responsively? I'm not sure if I should use css, ajax or jquery. thank you
Upvotes: 2
Views: 4271
Reputation:
The @media
rule can be used for the desired effect.
Although I would add that unless you are using different images, it's better to let CSS
resize the image. It does it very well.
Open snippet in full-screen mode and resize your window from very small to big to see the effect
body {
background: #111;
margin: auto
}
@media screen and (max-width: 599px) {
.simages {
display: block
}
.bimages {
display: none
}
}
@media screen and (min-width: 600px) {
.simages {
display: none
}
.bimages {
display: block
}
}
<body>
<img class="simages" src="https://files.graphiq.com/stories/t2/The_16_Dogs_That_Won8217t_Make_You_Sneeze_2060_2848.jpg">
<img class="bimages" src="https://s-media-cache-ak0.pinimg.com/736x/f0/26/05/f0260599e1251c67eefca31c02a19a81.jpg">
</body>
Upvotes: 1
Reputation: 2241
This will work..
function adjustImage(){
if($(window).width() <= 600) {
$('#img').attr('src','images/image.png');
$('#img').css({"width": "50px"});
};
}
$(document).ready(function(){
adjustImage();
});
$( window ).resize(function() {
adjustImage();
});
But we can do with CSS also as follow..
@media screen and (max-width: 600px) {
#img{
width:50px;
}
}
Upvotes: 5
Reputation: 952
you can use css to do this. Give max-width
: xxx px; to set maximum width of image and width
in percent. so it will automatically resize according to screen size.
img
{
max-width : 550px;
width : 75%;
}
refer : http://www.w3schools.com/css/css_rwd_images.asp
Upvotes: 0