Writing styles in CSS is kind of like having a representation of what styling should be active in different states within your HTML document. Because events happen inside the browser which are good triggers for styling changes, CSS already responds to some mouse and keyboard events through pseudo-classes like :hover
, :focus
, and :active
.
Other ways CSS responds to events by allowing authors to represent the styling of elements based on state responding to events are things like media queries, which would correspond to the resize events that happen when the browser resizes after it has loaded. In order to continue to style the site well the browser exposes limited information about the browser (the changing innerWidth
and innerHeight
) to CSS for the purpose of toggling styles.
There are a number of ways that JavaScript and CSS can interact, and that means JavaScript can be used to extend the expressive styling power of CSS. Some ways are more ideal than others, so let's think briefly about some common ones and their implications:
If you want a general-purpose CSS reprocessor, for most applications the following global events will suffice:
window.load
window.resize
window.input
window.click
However, it may make more sense to assign event listeners for other events, or to add event listeners to individual elements instead of recalculating on global events. Just keep in mind it's always ideal to limit the total number of recalculations requested, so consider performance and be very conservative when assigning event listeners.
element.scroll
element.change
element.blur
Note: When a web page is taller than the browser viewport and scrolled, some browsers report this as the
<html>
element being scrolled, and some browsers report this as the<body>
element being scrolled. When listening to scroll events for individual elements it’s simple to add one event listener and use the result, but listening for the page itself to scroll requires monitoring both<html>
and<body>
scroll position for a truly cross-browser effect.