skip to Main Content

I am new to dom manipulation , here I am trying to change the colour of the smallest box using the arrow key. I am able to access the same using the click events.

   <body>
        <div class="container">

            <div class="main-box" id="main-box">
                <div class="moving-box" id="moving-box">
                 </div>
            </div>
        </div>
         <script src="script.js"></script>
    </body>
const box = document.getElementById("moving-box");
const mainBox = document.getElementById("main-box");

box.addEventListener("keypress", function (event) {
    if (event.keyCode === 38) {
        box.style.backgroundColor = red;
    }
})

2

Answers


  1. I think the problem is event.keyCode is deprecated, you should try event.key (ArrowRight, ArrowLeft, ArrowUp, ArrowDown)

    Further info: https://www.w3schools.com/jsref/event_key_key.asp

    Login or Signup to reply.
  2. There’s no keypress event for the keyboard arrows because

    The keypress event is fired when a key that produces a character value is pressed down.

    https://developer.mozilla.org/en-US/docs/Web/API/Element/keypress_event

    So we should probably use keydown, also you aren’t clear whether you want to execute the event handler with the box focused or not. If focused you need tabindex="0" so the box could receive focus. Otherwise add the event listener to document.body.

    Also note that the keyboard keys scroll the page. So you should call event.preventDefault() to halt that.

    const box = document.getElementById("moving-box");
    const mainBox = document.getElementById("main-box");
    
    box.addEventListener("keydown", function (event) {
        if (event.keyCode === 38) {
            box.style.backgroundColor = 'red';
            event.preventDefault();
        }
    })
    #moving-box{
      width:100px;
      height:50px;
      border:1px solid gray;
      outline:none;
    }
    
    #moving-box+*{
      display:none;
    }
    #moving-box:focus{
      box-shadow: 0 0 20px rgba(0,0,0,.3);
    }
    #moving-box:focus+*{
      display:block;
    }
    <div class="container">Click the box to focus
        <br/>
        <div class="main-box" id="main-box">
            <div class="moving-box" tabindex="0" id="moving-box">
             </div>
             <div class="info">Press arrow up</div>
        </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search