What is missing from this beginner's lesson in this Sitepoint article?

This is about the Sitepoint article posted here:

It gives this improper code:

<button id='button' href='#' onclick='alert("Hello World")'>Click Me</a>

… then gives this proper way of doing it:

<script>
const btn = document.getElementById(’link’)
btn.addEventListener('click', function() {
    alert('Hello World!');
    };
</script>

I assume to make that code work with the prior line, one would have to swap id=‘button’ for id=‘link’, and drop the inline code:

<button id='link' href='#'>Click Me</a>

(The < script> code stays the same.)

But when I insert these bits into HTML between body tags, the alert does not fire. What is missing from the example? Or what is wrong with my change? (I thought a ; after getElementById(’link’) would make a difference, but it does not.)

If you just copied and pasted, did you use ‘link’ or the one here with the curly quotes? You should be using the straight quotes.

Thanks – I saw that earlier and fixed it; even when making it double quotes it did not work.

This works:

<button id='link' href='#'>Click Me</a></button>

<script>
const btn = document.getElementById("link");
	
function popup(){
	alert('Hello World!');
}
btn.addEventListener('click', popup);
</script>

… but that’s not the code in the article.

Doesn’t this line in the original code

const btn = document.getElementById(’link’)

need to end with a semi-colon as it does in your later code?

The code from the article has a typo - the button ID is button but the code is looking for an element with an ID of link.

Edit: actually the code is also missing a closing parenthesis on the addEventListener() call. I’ll make sure the article gets updated.

1 Like

and there’s no href attribute in a button.

Also true! :banghead:

from that original code I can deduce that the button initially was a link and only the start tag name was changed.

Updating the code based on the feedback, I get the following update, and now it works:

<button id='link'>Click Me</button>

<script>
const btn = document.getElementById('link');
btn.addEventListener('click', function() {
    alert('Hello World!');
    } );
</script>

Thanks, everyone!

Note: you should add type="button" in case the button is placed inside a form (the default type is a submit button!)

additionally, always specifying the type helps showing the intention of the button.

That’s new to me. Thanks. I thought < button> indicated the intention. I guess submit is another intention.

there are 3 types of buttons (submit, reset, click button) where only the latter does not have a default action.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.