Jump to content

Checkbox toggle in Chrome and Opera


Rain Lover

Recommended Posts

Steps to reproduce the issue:


  1. In your browser Settings select Continue where you/I left off under On startup.
  2. Navigate to the demo.
  3. Check the checkbox.
  4. Edit the text.
  5. Close your browser and reopen it. Or duplicate/clone the tab.

Now as you see the checkbox is checked, but the textarea isn't colored.

I tried it in the latest version of Chrome and Opera in Windows 10. I'm not sure about Safari, but it probably behaves the same way.


Questions:


  • Why does it happen?
  • What's a cross-browser solution?
Link to comment
Share on other sites

It happens because you're only changing the color when the checkbox changes. If the checkbox starts off checked no change has occurred, so the program is not checking whether the textarea should be colored or not.

 

The solution is to use both the change event and the load event. Here's an example:

var checkbox = document.getElementById('colorsToggle');
var textarea = document.getElementById('textField');

checkbox.onchange = toggle;
window.onload = toggle;

function toggle() {
  if(checkbox.checked) {
    textarea.className = "tan";
  } else {
    textarea.className = "";
  }
}
  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...