Events Test
by Emily Humphrey
HTML
<button class="js-click">JavaScript</button>
<button class="jq-click">jQuery</button>
CSS
body{
display: block;
background: #efefef;
margin: 0;
transition: .7s;
}
body.turned-dark{
background: #333;
}
JavaScript
// These things work togeth and apart
javaScriptExample()
jQueryExample()
// In JavaScript
function javaScriptExample(){
var btn = document.querySelector(".js-click"),
body = {
element: document.querySelector("body"),
turnedDark: false
},
theme = new Event('theme');
// Listen for the event.
body.element.addEventListener('theme', function (e){
if(body.turnedDark === true){
body.element.classList.remove("turned-dark");
body.turnedDark = false;
} else{
body.element.classList.add("turned-dark");
body.turnedDark = true;
}
}, false);
// Dispatch the event.
btn.addEventListener("click", function(e){
body.element.dispatchEvent(theme);
});
}
// In jQuery
function jQueryExample(){
var $btn = $(".jq-click"),
$body = $("body");
$btn.on("click", function(){
$body.trigger("theme");
});
$body.on("theme", function(e){
if($body.turnedDark === true){
$body.removeClass("turned-dark");
$body.turnedDark = false;
} else{
$body.addClass("turned-dark");
$body.turnedDark = true;
}
//console.log(e)
});
}