Thi...">

How to load images based on browser width

 <img id="demo" src="" />    

<script>
    if (window.innerWidth > 500)
    {

    }
    else 
    {

    }
</script>

      

This is my code. How do I change the src value depending on the browser width?

+3


source to share


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


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


If you want to solve this problem with CSS, you can use the CSS Media query. You can change the image according to the media query using JQuery. I think you understand my point of view.

+1


source







All Articles