First time trying to connect JS to HTML

Viewed 50

const btn=document.getElementById("btn");

btn.addEventListener("click", function(){
   alert("You clicked me");
})
    <link rel="stylesheet" href="color.css">
    <script src="color.js"></script>
</head>
<body>
    <!--<h1 class="change"> I change <h1 class="c">C</h1><h1 class="o">O</h1>
        <h1 class="l">L</h1><h1 class="oo">O</h1><h1 class="r">
            R</h1><h1 class="s">S</h1></h1>-->
    <button onclick="getRandomColor()" id="btn">Click Me!</button>
    <script src="color.js">
        
     </script>

</body>
</html>

I'm trying to make a color generator but my button isn't doing anything. I've tried many other copied codes to see if anything would work. Commented out is the code I actually want to work but at this point I'll take anything. TIA

2 Answers

You forgot the ending parentheses at the end of your btn.addEventListener call. Remeber that btn.addEventListener is a function call, so you need to wrap everything in parentheses like any other function call.

const btn = document.getElementById("btn");

btn.addEventListener("click", function() {
   alert("You clicked me");
}); // <- this parenthesis here
    <link rel="stylesheet" href="color.css">
    <script src="color.js"></script>
</head>
<body>
    <!--<h1 class="change"> I change <h1 class="c">C</h1><h1 class="o">O</h1>
        <h1 class="l">L</h1><h1 class="oo">O</h1><h1 class="r">
            R</h1><h1 class="s">S</h1></h1>-->
    <button onclick="getRandomColor()" id="btn">Click Me!</button>
    <script src="color.js">
        
     </script>

</body>
</html>

//in html code you already have given an id="btn" and a onclick event handler.so you dont need to write in js
const btn = document.getElementById("btn");

you can simply write in js :
function getRandomColor(){
alert("you clicked me");
}
Related