Preview: the events listed on this site are sample content while we add real ones.

Your first JavaScript

Make your page respond when someone clicks a button.

JavaScript makes pages interactive. It can change text, react to clicks and much more.

Add a button

In index.html, just before </body>, add:

<button id="greet">Say hola</button>
<p id="message"></p>
<script src="script.js"></script>

Write the script

Create script.js in the same folder:

const button = document.querySelector('#greet');
const message = document.querySelector('#message');

button.addEventListener('click', () => {
  const hour = new Date().getHours();
  const greeting = hour < 12 ? 'Buenos días' : 'Buenas tardes';
  message.textContent = `${greeting}! Thanks for visiting.`;
});

Save, refresh, and click the button.

What just happened

  • const creates a variable, a name that holds a value.
  • document.querySelector('#greet') finds the element with id="greet". The page’s structure that JavaScript can read and change is called the DOM (Document Object Model).
  • addEventListener('click', ...) runs a function every time the button is clicked.
  • hour < 12 ? 'Buenos días' : 'Buenas tardes' is a short way to choose between two values.

Your turn

Add a second button that switches the page’s background color. Hint: document.body.style.background = '#1d3fb8';