How to load images based on browser width
3 answers
You can use this to change the original value:
<img id="demo" src="" />
<script>
var img = document.getElementById("demo");
if (window.innerWidth > 500)
{
img.src="your source";
}
else
{
img.src="your source";
}
</script>
or
$('#demo').src="your path";
if you are using JQuery library use this:
$("#demo").attr('src', '//srcImage.jpg or any path');
0
source to share
Generally, you can switch the image using a media query and CSS, but if you really need JS you can do something like this:
<script>
var resize_image = function(event) {
var img = document.getElementById("demo");
var w = window.innerWidth;
if(w < 2000)
{
img.src = 'LINK1';
}
else if(w < 1024)
{
img.src = 'LINK2';
}
else if(w < 992)
{
img.src = 'LINK3';
}
else if(w < 768)
{
img.src = 'LINK4';
}
else
{
img.src = 'LINK5';
}
};
window.addEventListener('DOMContentLoaded', resize_image); // document loaded
window.addEventListener('resize', resize_image, true); // on resize
</script>
But if you want a responsive image, just give your image simple CSS rules like:
#demo{
display:block;
max-width: 100%;
height: auto;
}
+1
source to share