0

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?

terere
  • 1
  • 1
  • Instead of background1.target.classlist("mobilehome"), can you try using background1.classlist.add("mobilehome"). @terere –  Apr 12 '22 at 18:57
  • thanks, this didn't change the image. I am using chrome, and shrinking the image. Its weird, if I do this, I get the same image .jpg image as apposed to the .webp image that js told it to use. When I put it on the web and use my phone, I get nothing. I just tried this code on chrome. – terere Apr 12 '22 at 19:28

2 Answers2

0

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.

0

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)
})
Gass
  • 7,536
  • 3
  • 37
  • 41