Html only appears in edit view

my html:

<body>
<div id="wrapper">
        <button id="btn1" class="btn"></button>
	<button id="btn2" class="btn"></button>
	<button id="btn3" class="btn"></button>
	<button id="btn4" class="btn"></button>
	<button id="btn5" class="btn"></button>
 </div>
<script src="js.js"></script>	
</body>

My js:

(function(){
var btn = document.getElementsByClassName("btn");

	btn.addEventListener('click', function(e) {
		switch (e.target.id){
			case "btn01":
				console.log("button one selected!");
				break;
			case "btn02":
				console.log("button two selected!");
				break;
			case "btn03":
				console.log("button three selected!");
				break;
			case "btn04":
				console.log("button four selected!");
				break;
			default:
				 console.log(e.target.id);
				 //console.log("wtf?");
				}
			})
})

You are not adding the event to the right place.

btn is a nodelist and not an element. You need to add the event listener to the individual elements/nodes, you can’t achieve anything by adding it to the nodelist itself as it will never be triggered there

The following will attach the listener to every element with the class.

(function(){
[].forEach.call(document.getElementsByClassName("btn"), function(btn) {
btn.addEventListener('click', function(e) {
	switch (e.target.id){
		case "btn01":
			console.log("button one selected!");
			break;
		case "btn02":
			console.log("button two selected!");
			break;
		case "btn03":
			console.log("button three selected!");
			break;
		case "btn04":
			console.log("button four selected!");
			break;
		default:
			 console.log(e.target.id);
			 //console.log("wtf?");
			}
		})
})
});

Thanks for the help. Still doing nothing, not even an error. Maybe “e.target.id” isn’t a legit target?

btw were you able to see my html for some reason the only time I can see it is when I’m in edit mode. Strange forum software here.

It’s a combination of HTML tags, bbCode tags and MarkDown

Forum Posting Basics

Try changing the case to match your actual id values.

1 Like

got it, thanks!

I got it working after Felgall it still didn’t do anything that was because I didn’t call it so I added () at the end of the block now it works. Thanks Felgall!

1 Like

I am most surprised because the HTML id names do not have a zero before the numeric but your JavaScript has a zero before the numeric.

It would be beneficial to others if there is a working solution to your problem.

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