I don't know if that is what you want, but often, you want to listen for an event that triggers when the checked state changes:
document.addEventListener('DOMContentLoaded', function () {
var checkbox = document.querySelector('input[type="checkbox"]');
checkbox.addEventListener('change', function () {
if (checkbox.checked) {
// do this
console.log('Checked');
} else {
// do that
console.log('Not checked');
}
});
});
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
.switch input {display:none;}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked + .slider {
background-color: #2196F3;
}
input:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}
input:checked + .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
<h2>Toggle Switch</h2>
<label class="switch">
<input type="checkbox">
<div class="slider"></div>
</label>
When the browser parses your HTML and reaches a <script>
tag, it immediately executes the JavaScript in it. It can however happen, that the rest of the document is not loaded yet.
This means that some of the HTML elements in the page don't exist yet, and you can't access them in JavaScript. You have to wait until the elements are loaded.
Fortunately, the browser fires an event when it is done loading the contents of the page. This event is called DOMContentLoaded
.
When you wait for the browser to first fire the event, you can be sure that you can access all elements in the DOM.