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
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
Share Improve this question edited Dec 5, 2016 at 7:34 Divyesh Kanzariya 3,7893 gold badges47 silver badges46 bronze badges asked Dec 5, 2016 at 5:30 H.KimH.Kim 2771 gold badge11 silver badges25 bronze badges 2-
2
use
$( window ).resize(function() {
– Monasha Commented Dec 5, 2016 at 5:31 - What about using media queries in your css instead? – haltersweb Commented Dec 5, 2016 at 5:32
4 Answers
Reset to default 5This 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;
}
}
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./stories/t2/The_16_Dogs_That_Won8217t_Make_You_Sneeze_2060_2848.jpg">
<img class="bimages" src="https://s-media-cache-ak0.pinimg./736x/f0/26/05/f0260599e1251c67eefca31c02a19a81.jpg">
</body>
This is always achieve with css media query
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./css/css_rwd_images.asp