YLim
YLim

Reputation: 255

How to have javascript code on a different file then html?

I am constructing a calculator and this is my html for the calculator HTML

      <div id=”calculator”>
        <input type="text" name="display" id="display" disabled>
        <div class="first-row">
          <input type="button" name="operator" value="+" action="add">
          <input type="button" name="operator" value="-" action="subtract">
          <input type="button" name="operator" value="*" action="multiple">
          <input type="button" name="operator" value="/" action="divide">
        </div>
        <div class="second-row">
          <input type="button" class="number" value="7">
          <input type="button" class="number" value="8">
          <input type="button" class="number" value="9">
        </div>
        <div class="third-row">
          <input type="button" class="number" value="4">
          <input type="button" class="number" value="5">
          <input type="button" class="number" value="6">
        </div>
        <div class="fourth-row">
          <input type="button" class="number" value="1">
          <input type="button" class="number" value="2">
          <input type="button" class="number" value="3">
        </div>
        <div class="fifth-row">
          <input type="button" class="number" value="0" onclick="numberPress('0')">
          <input type="button" class="operator" value="=">
        </div>
      </div>

     <script type="text/javascript" src="../javascript/calculator.js"></script>

So in my javascript code, it checks if the button clicked is a operator, then if it is, then it prints out "operator" in the console.

Javascript

    const calculator = document.getElementById("calculator")
    calculator.addEventListener("click", e => {
        if (e.target.matches("input")) {
            key = e.target
            name = e.target.name
            if(name == "operator") {
                console.log("operator")     
            }
        }
    })

The problem is that for the first line, it does not find the calculator id and it stores null in calculator. So, I tried putting the javascript in the same file, but still it does not work. Any help will be very appreciated

Upvotes: 1

Views: 50

Answers (1)

edu
edu

Reputation: 153

You are not using this character "

You are using this character

So you are writing ”calculator” instead of "calculator" in your HTML

You must use plain quote marks in HTML

Upvotes: 3

Related Questions