0

It is working fine on iPhone, iMac, Windows, but when I run it on an Android device, the following error is displayed in the console.

Uncaught syntaxerror unexpected token, pointing "window.onload = () =>{" this line of code.

/*
* Simple DOM test that collects the value from a textbox,
* and applies it to the header element by changing its color.
*/

window.onload= () =>{
    const myheading = document.getElementById('header');
    const myButton = document.getElementById('myButton');
    const bgColor = document.getElementById('bgColor');
    const textColor = document.getElementById('textColor');

    myButton.addEventListener('click', () => {
        myheading.style.color = 'black';
        bgColor.style.color = bgColor.value;
        textColor.style.color = textColor.value;

        if (bgColor.value === '' || textColor.value === '') {
            alert('Please enter color value');
            myButton.style.backgroundColor= "#f00";
            myButton.style.color = '#fff';
            myButton.innerHTML = 'Enter Color Name';

            setInterval(function() { 
                myButton.innerHTML = 'Change heading color';
                myButton.style.backgroundColor= "#dcdcdc";
                myButton.style.color = "black";
            }, 5000);
        } else {
            myheading.innerHTML = "You changed me into <u>" + textColor.value + "</u> with  a <u>"  + bgColor.value + "</u> background!";

            Object.assign(myheading.style, {
                padding: "10px",
                color: textColor.value,
                backgroundColor: bgColor.value
            });

            myButton.style.backgroundColor= "#fd1";
            myButton.innerHTML = 'Colors applied Success!';    
        }
    });
}
khan
  • 11
  • 1
  • 4

2 Answers2

0

Replace each ()=>{ with function(){. The code will function the same and work on browsers that have not yet implemented arrow functions.

Since you are not using the this keyword in your onload function, there will be no difference in functionality (as arrow functions do not change scope while normal functions do). See this stackoverflow question for more details on the differences between normal functions and arrow functions.

Ulad Kasach
  • 11,558
  • 11
  • 61
  • 87
0

The problem is not about the environment but about the browser supported version of Javascript. Arrows function is a feature available Javascript Ecmascript 6, some browsers don't implement it, depending on their version.

In you case, you can just use Ecmascript 5 (ES5), replacing () =>{} by function(){}.

If you need ES6 functionnality on ES5 browsers, you may consider a compiler / polyfill.

Arrow functions are defined in 2015's version of ECMA-262 norm.

NayoR
  • 702
  • 6
  • 13