Ntoni
Ntoni

Reputation: 51

Problem with this "Windows and Safari function"

I'd like to run some js code only if I'm on Safari on Windows. 'Alert' works but any other code (like body.classList ... etc) doesn't work. Why? Thank you very much for any help

var safari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
var windows = (navigator.userAgent.indexOf("Win")!=-1);
var body = document.body;

if (safari && windows) {
  alert('this is safari on windows'); //This works
  body.classList.add("safwin"); //This not works
}

Upvotes: 0

Views: 163

Answers (1)

Nick Parsons
Nick Parsons

Reputation: 50694

Your issue is that the document isn't ready yet when your javascript fires, and so document.body will give you null. In order to access the document you'll need to execute your code when the document object model (DOM) has loaded. You can do this by adding an event listener to your window such that you run your code when the DOM has loaded (using "DOMContentLoaded"):

window.addEventListener('DOMContentLoaded', function() {  
  var safari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  var windows = (navigator.userAgent.indexOf("Win")!=-1);
  var body = document.body; // you can now safely access document.body

  if (safari && windows) {
    alert('this is safari on windows'); // This works
    body.classList.add("safwin"); // This will now work
  }
});

Upvotes: 1

Related Questions