Reputation: 47
Im writing an extension for google chrome.
I have an options.html that contains this:
<html>
<head>
<title>Test Options Menu</title>
<script src="chromeoptions.js"></script>
</head>
<body>
<div id="options">
<div id="form">
<input type="checkbox" id="test">
<div id ="testEvents" style="display:'none'">
blabla
</div>
</div>
</div>
</body>
</html>
Chromeoptions.js has this in it:
function clicked(string) {
console.log('clicked');
if (document.getElementById(string).checked == true) {
document.getElementById(string + 'Events').style.display = '';
}
else document.getElementById(string + 'Events').style.display = 'none';
}
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('test').addEventListener('click', clicked('test'));
});
What happens is: on the first load the 'click' eventhandler fires, causing the div 'testEvents' to disappear. Afterwards, nothing happens when I toggle the checkbox. The eventhandler doesnt fire. It doesnt matter if I use 'click' or 'onchange'.
I also tried moving the scripttag to the bottom of the html and putting the 'click' eventhandlers outside the 'DOMContentLoaded' eventHandler, but that also didnt change anything.
So how do I get the eventhandler to fire when I toggle the checkbox?
Upvotes: 0
Views: 833
Reputation: 4618
or if you wanted it to use jquery:
add:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
and use:
$.fn.toggleDiv = function () {
$(this).each(function () {
var target = $(this);
$(target).on('click', function () {
$('#' + $(target).attr('id') + 'Events').toggle($(target).is(':checked'));
});
});
};
$('input[type=checkbox]').toggleDiv();
Which works with multiple events checkboxes:
<div id="options">
<div id="form">
<input type="checkbox" id="test">
<div id ="testEvents" style="display:none">
blabla1
</div>
<input type="checkbox" id="test2">
<div id ="test2Events" style="display:none">
blabla2
</div>
</div>
</div>
Upvotes: 0
Reputation: 4618
You have
<div id ="testEvents" style="display:'none'">
maybe try:
<div id ="testEvents" style="display:none">
Upvotes: 0
Reputation: 781503
The second argument to addEventListener
must be a function. You're calling clicked()
immediately, not passing a function that calls it.
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('test').addEventListener('click', function() {clicked('test')});
});
Upvotes: 2