Home > OS >  First time trying to connect JS to HTML
First time trying to connect JS to HTML

Time:09-15

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 > I change <h1 >C</h1><h1 >O</h1>
        <h1 >L</h1><h1 >O</h1><h1 >
            R</h1><h1 >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

CodePudding user response:

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 > I change <h1 >C</h1><h1 >O</h1>
        <h1 >L</h1><h1 >O</h1><h1 >
            R</h1><h1 >S</h1></h1>-->
    <button onclick="getRandomColor()" id="btn">Click Me!</button>
    <script src="color.js">
        
     </script>

</body>
</html>

CodePudding user response:

//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