Home > Blockchain >  I want to use JavaScript to change the background image on a website when the device is small
I want to use JavaScript to change the background image on a website when the device is small

Time:04-13

I built a webpage with a Parallax feature. I used javascript to disable the text part on small screens, but there is no picture. I want to use JavaScritp to swap the larger picture (1500pixels) for a smaller one(500px). I copied the class in called home, changed the name to mobilehome and added the smaller image. Here is the code javascript:

/* disable paralax scrolling */
var ismobile = /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera 
Mini/i.test(navigator.userAgent)
if (ismobile){

 // bypass parallax effect
 background()
 }

  //change background pictures
  function background () {
  var background1 = document.getElementById("home");
  background1.target.classlist("mobilehome")};

It doesn't work, any advice?

CodePudding user response:

In this topic they suggest using methods to find out the device size

Get the device width in javascript

It seems like you could use document.documentElement.clientWidth and then use the returned value to decide wether you want to change the background displayed.

CodePudding user response:

So basically you need an event listener that will make a callback to a function that will handle the change of the bg depending on the innerWidth of the window.

window.addEventListener('resize', () => {
  if(window.innerWidth <= 500){
    // change bg to a smaller one
  }
  else{
    // change bg to a bigger one
  }
})

If you run the below code as a full page and resize it you will see how the width of the screen is been updated every time.

window.addEventListener('resize', () => {
  console.log(window.innerWidth)
})

  • Related