Soumya Roy
Soumya Roy

Reputation: 345

How to change body background-color for only IOS devices using javascript?

Trying to detect IOS device and set a different background color. But my code is not working. How can I do this simply with pure javascript ...?

JAVASCRIPT

var isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
if (isIOS){
  document.body.style.background = "rgba(0,0,0,1)";
  console.log('This is an IOS device');
} else{
  console.log('This is Not an IOS device');
}

Upvotes: 1

Views: 705

Answers (2)

Soumya Roy
Soumya Roy

Reputation: 345

Only iphone detection is working but ipad detection not working. But in my case to change the background the setInterval function worked.

var isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
if (isIOS && window.matchMedia("(max-width: 615px)").matches) {
  console.log("This is an IOS device");
  setInterval(function () {
    document.body.style.background = "rgba(0,0,0,1)";
  }, 5);
}

Upvotes: 1

Mike Irving
Mike Irving

Reputation: 1628

Works for me. I’ve used backgroundColor to make it more specific

var isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
if (isIOS) {
  document.body.style.backgroundColor = "rgba(0,0,0,1)";
  console.log('This is an iOS device');
} else {
  console.log('This is Not an iOS device');
}

You could set a class instead, and in the class specify

.my-class { background-color: rgba(0,0,0,1) ! important; }

! important should make it override other styles.

Upvotes: 0

Related Questions