self.window.self.window.top.self…
// :P
console.log(this.self.window.self.top.window.self.top.window.self.self.self.top);
😉
// :P
console.log(this.self.window.self.top.window.self.top.window.self.self.self.top);
😉
document.body.innerHTML += 'click to randomize background color';
document.addEventListener('click', () => {
const hue = Math.random() * 360;
document.body.style.background = `hsl(${hue}deg, 50%, 50%)`;
});
One way to generate a random color is to randomize the hue
argument of the css hsl
. This value is in degrees 0-360 (colorwheel). The other arguments can be randomized as well if you need random saturation and lightness… like this:
document.body.innerHTML += 'click to randomize background color';
document.addEventListener('click', () => {
const hue = Math.random() * 360;
const saturation = Math.random() * 100;
const lightness = Math.random() * 100;
document.body.style.background = `hsl(${hue}deg, ${saturation}%, ${lightness}%)`;
});
const ui = document.body.appendChild(
document.createElement('div')
);
ui.innerHTML = `
<button class="blue circle redBorder moveDown">click</button>
<button class="red circle sayHi">click</button>
<button class="green circle noBorder moveDown sayHi randomBgColor">click</button>
<style>
* { -webkit-user-select: none; user-select: none; }
body, html {
width: 100%; height: 100%;
}
button {
position: relative;
top: 0;
margin: .5em;
cursor: pointer;
color: white;
transition: all 200ms ease-out;
text-shadow: 1px 2px 1px black;
}
.circle {
width: 50px;
height: 50px;
border-radius: 500px;
}
.blue {
background: #275ba1;
}
.red {
background: red;
}
.green {
background: green;
}
.redBorder {
border: 2px solid red;
}
.noBorder {
border: none;
}
</style>
`;
const actions = {
moveDown(e) {
e.target.style.top = `${parseFloat(e.target.style.top || 0) + 30}px`;
},
sayHi(e) {
e.target.innerHTML = [
'hi', 'hello', 'hey', 'aloha', 'what\'s up'
][
Math.floor(Math.random() * 5)
];
e.target.style.transform = `
rotate(${Math.random() * 40 - 20}deg)
scale(${Math.random() * .3 + 1})`
},
randomBgColor(e) {
const col = `hsl(${Math.random() * 360}deg, 50%, 50%)`
e.target.style.background = col;
}
};
document.body.addEventListener('click', e => {
// combine as many actions as we want
[...e.target.classList].forEach(cls => {
const action = actions[cls];
if (action != null) action(e);
});
});
This snippet takes the ideas from yesterdays post and goes one level further. This associates behavior with class names, so the class names can be combined to mix and match behavior.
In this case, combining classes like this green circle noBorder moveDown sayHi randomBgColor
will cause the element in question to “move down”, “say hi” and randomize its background color when it is clicked. Click the “Try it out” to get a better idea.
const ui = document.body.appendChild(
document.createElement('div')
);
ui.innerHTML = `
<button class="hello">say hello</button>
<button class="make-box">make a box</button>
<button class="remove-boxes">remove boxes</button>
<button class="consoleLog red">log in console</button>
<style>
button { margin: .5em; cursor: pointer; }
.red { background: red; color: white; }
.box {
position: relative;
float: left;
width: 30px;
height: 30px;
margin: 1em;
background: blue;
}
</style>
`;
const actions = {
hello(e) {
alert(e.target.className);
},
['make-box']() {
const box = document.body.appendChild(
document.createElement('div')
);
box.classList.add('box');
},
['remove-boxes']() {
const boxes = [...document.querySelectorAll('.box')];
const num = boxes.length;
boxes.forEach((el) => el.parentNode.removeChild(el));
alert(
num === 0
? 'no boxes to remove'
: `removing ${num} box${num > 1 ? 'es' : ''}`
);
},
consoleLog(e) {
console.log('camelCase instead of kebab-case :D');
},
};
document.addEventListener('mousedown', (e) => {
const action = actions[e.target.classList[0]];
if (action != null) action(e);
});
This is a powerful little pattern for managing mouse/touch events. Rather than assigning many listeners, this snippet has one listener on the document
. Anytime the page is clicked, we look at the event targets classList
and use its first value as a key in an actions
object.
I have used this or some variation of it many many times over the years. With a little customization it scales well into large projects. I always find myself on the fence about class naming conventions… kebab-case vs camelCase – probably because it just doesn’t matter that much. For large projects, each main section of the UI will have its own document.addEventListener
just for organizational purposes.
The choice to use the first class as the key for the action is pretty arbitrary. Depending on how you like to set things up you could use the last value of the classList
, the element id
, the element name
, or a custom data attribute etc… Like this:
// id
const action = actions[e.target.id];
// name
const action = actions[e.target.name];
// data attribute <button data-my-id="test">test</button>
const action = actions[e.target.dataset.myId];
const obj = {
x: 1, y: 2,
data: { test: 'xyz' }
};
console.log(JSON.stringify(obj, null, 2));
JSON.stringify
has two more arguments that allow for pretty printing and processing of the object in question. The second argument is a “replacer” function and the third argument is for indentation. Read more details here.
I am pretty sure I first learned this from this stack overflow post.
I used this technique in yesterdays console hijacking post.