Download image based on browser width

This is my code:

<img class="abc" src="abc.jpg"/>
<img class="xyz" src="xyz.jpg"/>
<script>
  if (window.innerWidth > 500)
    {
        $(".abc").remove();
    }
    else 
    {
        $(".xyz").remove();
    }
</script>

But he only hides the image, I think. Since the network tab shows the total page size in the size of both images.

+4
source share
4 answers

Just to complete this thread, you can also try the HTML tag picture.

<picture class="abcxyz">
     <source srcset="abc.jpg" media="(max-width: 499px)">
     <img src="xyz.jpg" alt="xyz">
</picture>

But be careful. IE does not support this solution.

See MDN for more details .

Update

If you need to add classes to this image element, you can do it like this:

<style>
    .abcxyz {
        outline:2px solid lightblue;
    }

    @media (min-width:500px) {
        .abcxyz {
            outline:2px solid black;
        }
    }
</style>
+2
source

css solution

You do not need js to achieve it, you can use css media requests to do this, as shown below.

img.abc {display:block;}
img.xyz {display:none;}

@media (min-width:500px) {
  img.abc {display:none;}
  img.xyz {display:block;}
}
<img class="abc" src="abc.jpg" alt="abc"/>
<img class="xyz" src="xyz.jpg" alt="xyz"/>

JS

src, data-src JavaScript src, :

var abc = $(".abc").data("src"),
   abc_alt = $(".abc").data("alt"),
   xyz = $(".xyz").data("src"),
   xyz_alt = $(".xyz").data("alt");

if (window.innerWidth > 500) {
    $(".xyz").attr("src",xyz);
    $(".xyz").attr("alt",xyz_alt);
} else {
    $(".abc").attr("src",abc);
    $(".abc").attr("alt",abc_alt);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="abc" data-src="abc.jpg" data-alt="abc">
<img class="xyz" data-src="xyz.jpg" data-alt="xyz">
+2

Use this code:

if (window.innerWidth > 500)
{
    $(".abc").attr("src", "abc.jpg");
}
    
else 
{
    $(".abc").attr("src", "xyz.jpg");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
<img class="abc" src=""/>
Run code
+1
source

If you want to use JS, try

<img class="abc" src="abc.jpg" style="display:none;"/>
<img class="xyz" src="xyz.jpg" style="display:none;"/>
<script>
    if (window.innerWidth > 500){
        $(".abc").hide();
        $(".xyz").show();
    } else {
        $(".abc").show();
        $(".xyz").hide();
    }
</script>
0
source

Source: https://habr.com/ru/post/1682096/


All Articles