Search code examples
javascriptcssresponsive-designparallaximage-preloader

background image using js befor HTML it loads for responsive design


I have created horizontal scrolling parallax web site for that web site I want to add a background images based on the browsing device

for example

from normal pc <img src="bg.png">
from tablet <img src="bg-500px.png">
from smaller mobiles <img src="bg-small.png">

How can i get a solution for this I tried <body onload="fun()">

in

fun(){
    var bg=d.getEBI("img id");
    if(window.innerwidth=referenceWidth)
    {
        bg.src=respective-img.png
    }
}

Solution

  • One approach could be doing it through CSS using media query CSS Media Queries. Instead of the <img> use a <div> with background image

    <div class="background"></div>
    
    /*For mobile*/
    @media (max-width: 480px) {
      .background {
        background-image: bg-small.png;
      }
    }
    
    /*For Tablet*/
    @media (max-width: 1024px) {
      .background {
        background-image: bg-500.png;
      }
    }
    
    /*For Desktop*/
    @media (min-width: 1024px) {
      .background {
        background-image: bg.png;
      }
    }
    

    If you want to do it through JavaScript as you have mentioned in the question then it is a bit tricky. You need to do it in the following steps

    Step 1. Use some external library to detect device type (e.g. Device detection in JS)

    Step 2. Use a custom HTML tag say <myimg> (HTML custom element) instead of <Img> tag

    Step 3. Register an event listener for this custom HTML tag and within this event listener change the image src type based on the device type detected in Step 1.