0

I am trying to do alert("clicked") when a button is pressed but I can't get it to work on visual studio code, it only works on codepen. I run the index.html in visual studio code using an extension called open in browser.

I tried copying the codes to codepen and it worked

<html>
    <head>       
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <div class="container">
            <h1>Random dog Pictures</h1>
            <img id = "photo" src = "https://i.pinimg.com/originals/68/6d/6f/686d6fc9d01def6b6f63acded53479bc.jpg" alt = "">
            <button id = "btn">Get Random Dog Photo!!!</button>
        </div>
        <script src="randomDogPicture.js"></script>
    </body>
</html>
var btn = document.querySelector("#btn");

btn.addEventListener("click", function() {
    alert("clicked");
});

I expected it to display "clicked" but it doesn't do anything when I click the button.

Dhenz
  • 45
  • 1
  • 8
  • Works fine for me. Where are you including the JavaScript in the document? – JoshG Aug 25 '19 at 12:27
  • What does the console say? – Ted Brownlow Aug 25 '19 at 12:30
  • It is saved all in the same folder, the problem is when I comment all the codes in the javascript and replace it with 'alert("clicked")' it works when I refresh the page, but I want to bind it with a button click – Dhenz Aug 25 '19 at 12:32

2 Answers2

1

Probably your script is running before the DOM is fully loaded. You can either place your code at the bottom of the body or wrap your code with DOMContentLoaded:

<script>
  document.addEventListener('DOMContentLoaded', (event) => {
    var btn = document.querySelector("#btn");
    btn.addEventListener("click", function() {
      alert("clicked");
    });
  });
</script>
<div class="container">
    <h1>Random dog Pictures</h1>
    <img id = "photo" src = "https://i.pinimg.com/originals/68/6d/6f/686d6fc9d01def6b6f63acded53479bc.jpg" alt = "">
    <button id = "btn">Get Random Dog Photo!!!</button>
</div>
Mamun
  • 58,653
  • 9
  • 33
  • 46
  • This works sir, by the way do I have to put all my event listeners in the html file or there's a way to put it in the javascript file? – Dhenz Aug 25 '19 at 12:50
  • @Dhenz, not necessarily all your code has to be inside the event, but it is good practice:) – Mamun Aug 25 '19 at 12:54
  • If the issue is that the element doesn't exist yet, please vote to close as a duplicate of the canonical; this exact question has been asked so many times before, there's no need for yet another answer saying the same thing – CertainPerformance Aug 25 '19 at 13:52
1

I think you should remove the default action (reloading the page) by doing this:

document.addEventListener('DOMContentLoaded', (event) => {
    var btn = document.querySelector("#btn");
    btn.addEventListener("click", function(e) {
      e.preventDefault()
      alert("clicked");
    });
  });

I'm not sure if it helps but give it a try