Various 2

Page section: playground

The Modal

The modal was the first of 10 short JavaScript projects I tried from a video by Florian Pop. The JS is pretty simple, adding event listeners to change the style.display to none and grid respectively.

The CSS was interesting. I hadn’t realised that using display: grid with place-content: center means the child elements only use width values as a max-width.

An alternative to display: grid would be:

#modal {
    display: flex;
    justify-content: center;
    align-items: center;
}

The modal also used:

#modal {
    position: fixed;
    inset: 0;
    display: grid;
    place-content: center;
}

Keyboard events

To make the modal close using the Esc key the following JavaScript was added:

document.addEventListener('keydown', () => {
    if (event.key == 'Escape') {
    modal.style.display = 'none';
    }
    // console.log(event.key + ' ' + event.code);
});

Using this

Here’s a simple use of this used in an HTML onclick attribute:

<button onclick="this.innerHTML = Date()">The time is?</button>

this references the object that is executing the current function.

Mosh

If it’s a regular function, not part of an object, then it references the window object in a browser or the global object in Node.

BEWARE if an anonymous function is used inside an object it may not be considered part of the object and so will reference the window object rather than the object in which it is written.

Mosh has a short vid on `this'.

keydown

Table of Contents