vendredi 4 décembre 2020

JavaScript - My checkbox (which is checked by default) doesn't run it's script on page load

I apologize if this is something really simple, but I'm relatively new to JavaScript. I've scoured the web to find a solution but haven't found anything!

So I'm building a sort of "settings" UI for a Google Chrome extension popup and I'm using checkboxes to enable/disable options. I want one of the checkboxes to be checked by default, so I have the checked attribute defined in its HTML like so;

<input type="checkbox" id="option1" style="margin-left: 20px;" checked>
                                                        <!-- ^ Right here ^ -->
<script src="script.js"></script>

I implemented a script here so that if the checkbox is checked, a certain script will be programmatically injected. If it isn't checked, it will inject a different script. Code:

document.getElementById("option1").addEventListener("click", toggleOption1);

function toggleOption1() {

  var option1 = document.getElementById("option1");

  // if option1 is checked, run first script
  if (option1.checked === true) {
    chrome.tabs.executeScript({
          file: 'optionEnabled.js'
        });
  // otherwise, run script 2
  } else {
    chrome.tabs.executeScript({
          file: 'optionDisabled.js'
        });
    }
}

Now, this has worked great for me so far, it does exactly what it intends to do except for one thing: I want the code to be run automatically because, duh, the checkbox is checked by default. The code only recognizes when the box is unchecked or checked by the user.

Note: I am aware that this line of code

document.getElementById("option1").addEventListener("click", toggleOption1);

means that the function is run on click and I should just use onclick="toggleOption1()" instead, but because I am making a chrome extension, inline scripts are not allowed.

Note 2: I would appreciate it if the solution could avoid JQuery or other external libraries, but if nothing else is available, I guess it's okay!

Note 3: I would provide a JSFiddle, but I don't believe there's a way to implement the chrome extension environment.

Anyone out there know a way to fix this? I've been confuzzled for several days and I'd really like to fix this issue.
Thanks in advance!




Aucun commentaire:

Enregistrer un commentaire