How to add event listener for checkbox in Chrome extension's popup?
checkbox, google-chrome-extension, javascript
Solution
Had the same problem but reference a very helpful site which list events in Javascript. After doing a quick search (Ctrl+F) for the keyword "check" I found the "change" event listed...supposedly compatible with most browsers. Sure enought it was there, so my assumption is that maybe there is a "change event" for checkboxes. Low and behold just test it and it seems to work. Here is your code revised a little and the link of events (http://help.dottoro.com/larrqqck.php):
Example of html from popup.html
<div class="menu" >
<input type="checkbox" id="showAlert" name="showAlert"/>
<label for="showAlert"><nobr>Show Alert</nobr></label></div>
Example of code snippet from popup.js
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('#showAlert').addEventListener('change', changeHandler);
});
Of course you will need to pass this into a function like:
function changeHandler(){
//Do Something...maybe another function showAlert(), for instance
if(showAlert.checked){
//do something
}
else{
//do something else
}
}
01/06/2018 - EDIT: I just glanced back at this article and it appears this is likely going to become deprecated. Hence forward you may wish to use the MutationObserver (https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver).
Problem
I'm trying to capture changes of `checkbox` in popup of my Chrome Extension. Documentation says: Inline JavaScript will not be executed There is an example provided on the same page, but it for `button`. I don't know how to modify it so it would capture chekbox's state changes. ``` document.addEventListener('DOMContentLoaded', function () { document.querySelector('button').addEventListener('click', clickHandler); }); ```