Modifier key tracking in JavaScript
Using the Event object, you can find out
if the Ctrl, Alt, and Shift
keys were pressed at the time of the event. This
is done using the properties ctrlKey,
altKey and shiftKey - they have
the value true or false depending
on whether this key was pressed at the time of
the event or not.
Let's look at an example. Let's say we have the following button:
<button id="elem">text</button>
By clicking on the button, we will display a
message about whether one of the keys Ctrl,
Alt and Shift was pressed:
let elem = document.querySelector('#elem');
elem.addEventListener('click', function(event) {
if (event.ctrlKey) {
console.log('Ctrl is pressed');
}
if (event.altKey) {
console.log('Alt is pressed');
}
if (event.shiftKey) {
console.log('Shift is pressed');
}
});
Given an element. Make it turn red when clicked,
but only if the Alt key is pressed at
the time of the click.
Let's say you have the list ul
with tags li:
<ul id="elem">
<li>text</li>
<li>text</li>
<li>text</li>
<li>text</li>
<li>text</li>
</ul>
Make it so that when you click on any li,
the number 1 is added to the end of its
text if the Ctrl key is pressed, and the
number 2 if Shift is pressed.