JavaScript: make it do things
HTML is the skeleton, CSS the skin, JavaScript the muscles.
JavaScript runs in the browser and can react to people: clicks, typing, scrolling. The recipe is always the same: find an element, listen for an event, change something.
const button = document.querySelector('button');
const message = document.querySelector('#message');
button.addEventListener('click', () => {
message.textContent = 'You clicked me!';
});querySelector finds an element, addEventListener waits for a click, textContent changes the words.
Fun fact: Open your browser's developer tools (usually F12 or right-click then Inspect) on any website and you can poke at its HTML, CSS and JavaScript live. It is the best classroom there is.
Quick check
What does addEventListener('click', ...) do?
- Clicks the element for you
- Runs your code every time the element is clicked
- Adds a new element to the page
- Styles the element
Answer: Runs your code every time the element is clicked. It registers a function to run whenever that event happens. The browser does the waiting for you.