Crash Course On jQuery - JavaScript Example
Changing the body's background color using vanilla JavaScript.
by Tony Le
HTML
<!-- OUR BUTTONS FOR CHANGING THE BACKGROUND COLOR -->
<button type="button" id="btn-red-bg">Red</button>
<button type="button" id="btn-blue-bg">Blue</button>
<button type="button" id="btn-reset-bg">Reset</button>
CSS
/* OUR INITIAL CSS RULES */
body {
background-color: #fff;
}
JavaScript
// get the button with the id of btn-red-bg
// and when it is clicked on
document.getElementById('btn-red-bg').onclick = function() {
// change the body's background color to red
document.body.style.backgroundColor = '#ff0000';
}
// get the button with the id of btn-blue-bg
// and when it is clicked on
document.getElementById('btn-blue-bg').onclick = function() {
// change the body's background color to blue
document.body.style.backgroundColor = '#0000ff';
}
// get the button with the id of btn-reset-bg
// and when it is clicked on
document.getElementById('btn-reset-bg').onclick = function() {
// change the body's background color back to white
document.body.style.backgroundColor = '#ffffff';
}