Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript setting style's color, works in Firefox, not in Chrome, Safari etc

I’m using the following code to turn the placeholder text red if the value is missing or invalid

      if (email.value.trim() == '' || !ValidateEmail(email.value)) {
         email.placeholder = "Please enter Email";
         email.style.color = "red";
      }
 

email holds the element and placeholder text setting works. In Firefox the font color goes red, in many other browsers nothing happens.
I’ve tried using all of these

email.style = "color: red"; // invalid but works in Firefox
email.setAttribute('style', 'color:red;');
email.style.setProperty('color', 'red');

and all work in FF, not in others.
console.log(email.style.color);
shows the value has been set.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I guessed that you can’t change the style of the placeholder text in Safari etc, only in Firefox.
But setting the background color works in all browsers! Any suggestions?

>Solution :

Changing the placeholder’s color you’re supposed to use the ::placeholder selector in CSS. What is surprising here is that it actually works on FF.

Anyway, to solve your problem, I would recommand to use specific class to achieve this.

In your CSS:

input.invalid-value::placeholder{
    color: red;
}

Then in your JS:

if (email.value.trim() == '' || !ValidateEmail(email.value)) {
    email.classList.add('invalid-value');
}

Hope it helps !

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading