2

I have a backtick in my javascript to make my website render correctly on mobile chrome. The problem is that the backtick, while not needed in IE, causes everything in the javascript for IE to error and stop working.

I tried simply replacing it with a double quote, but that didn't work. I also thought about making a separate javascript page that will only run in IE or on desktops, but that seems less than optimal. Preferably, the line of code can be altered so that it has the same effect and works in all browsers.

The problematic line of code is:

document.documentElement.style.setProperty('--vh', `${vh}px`);

// First we get the viewport height and we multiple it by 1% to get a value for a vh unit
let vh = window.innerHeight * 0.01;
// Then we set the value in the --vh custom property to the root of the document
document.documentElement.style.setProperty('--vh', `${vh}px`);
body {
  background-color: #333;
}

.module {
  height: 100vh; /* Use vh as a fallback for browsers that do not support Custom Properties */
  height: calc(var(--vh, 1vh) * 100);
  margin: 0 auto;
  max-width: 30%;
}

.module__item {
  align-items: center;
  display: flex;
  height: 20%;
  justify-content: center;
}

.module__item:nth-child(odd) {
  background-color: #fff;
  color: #F73859;
}

.module__item:nth-child(even) {
  background-color: #F73859;
  color: #F1D08A;
}
<div class="module">
  <div class="module__item">20%</div>
  <div class="module__item">40%</div>
  <div class="module__item">60%</div>
  <div class="module__item">80%</div>
  <div class="module__item">100%</div>
</div>  

This script is from here: https://css-tricks.com/the-trick-to-viewport-units-on-mobile/

It's a way to set vh so that it's more static in chrome and firefox.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
SideSlaw
  • 39
  • 6

1 Answers1

2

Template literal syntax is an ES6 feature, as is the let keyword. The ES5 way to do it would be to use var and normal string concatenation instead:

// First we get the viewport height and we multiple it by 1% to get a value for a vh unit
var vh = window.innerHeight * 0.01;
// Then we set the value in the --vh custom property to the root of the document
document.documentElement.style.setProperty('--vh', vh + 'px');

But this can get very tedious when you have any significant amount of code, and makes reading the code more difficult. A better general solution would be to run your code through Babel first, which will automatically transpile ES6+ syntax into ES5 syntax. (Note that Babel by default only transpiles syntax - ES6+ objects and methods, such as Array.prototype.includes, will work in ancient browsers like IE only if you use a polyfill as well)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320