Use Buttons and click events to run Javascript functions and code blocks

The previous post showed how to select and edit every paragraph element on a page adding a smiley face to each paragraph, but we run the code by entering it directly in the Javascript console. How can we run a section of JavaScript code when something happens? Often we want a section of JavaScript code to run when a button is clicked. Let’s see how that is done.

Note that I am ignoring some best practices for the sake of simplicity.

Let’s add a button to our page using, <button>CLICK ME</button>. When we click the button, nothing happens.

Let’s say you got here and want to follow these instructions, but don’t know how. You can edit, create, and run HTML / Javascript code and html sections at: https://codepen.io/pen/

Well that does nothing and is pretty boring, so let’s make it do something.

Starting simple let make the button trigger an alert. Change the button code to:
<button onclick="alert('You clicked the button')">CLICK ME!</button>
to get this:

If you click on the button, you should get an alert box.

Now let’s make a button to add 🙂 to the end of each paragraph.

From the previous post we have this section of code that appends 🙂 to the end of each paragraph on a website.

allPTags = document.getElementsByTagName('p'); // Gets all our p tags
for (let pTag of allPTags) { // Loops through each p tag
  pTag.append(' :) '); // Add :) to each P tag
}

Let’s take this code block and smash it inside our button.

<button onclick="
  allPTags = document.getElementsByTagName('p'); // Gets all our p tags
  for (let pTag of allPTags) { // Loops through each p tag
    pTag.append(' :) '); // Add :) to each P tag
  }
">CLICK ME FOR SMILES!</button>

OK, I know this is really ugly, but it’s simple and it will work! We can clean this up in a later post.

Here is the result:

Click away! You will see that every click adds more smiles to the page!

Leave a Reply

Your email address will not be published. Required fields are marked *