Home > Software design >  How to make this so the visibility will not change if the event is triggered from a typebox target?
How to make this so the visibility will not change if the event is triggered from a typebox target?

Time:03-20

Say I have a button, like this:

    let btn = document.createElement("button");
    btn.style = "position: fixed; top: 0; left: 0; visibility: visible;";
    btn.innerText = 'Click me!';
    document.body.appendChild(btn);
    btn.onclick = function() {
        btn.innerText = 'Clicked';
    };
    
    document.addEventListener("keydown", function(event) {
        if (event.code === 'KeyU') {
            btn.style.visibility = btn.style.visibility == "hidden" ? "visible" : "hidden";
        }
    });

How could I make it so that the visibility will only change when you're not typing into some sort of textbox or searchbar?

CodePudding user response:

As @Bravo mentioned in the comments of this question, you can read into event.target in order to detect what element was in focus when the user pressed the key.
event.target contains a reference to the element that was in focus. https://developer.mozilla.org/en-US/docs/Web/API/Event/target. Here's an example where it will only change the visibility if the key wasn't being pressed in a textarea.

    let btn = document.createElement("button");
    btn.style = "position: fixed; float: left; top: 0; left: 0; visibility: visible;";
    btn.innerText = 'Click me!';
    document.body.appendChild(btn);
    btn.onclick = function() {
        btn.innerText = 'Clicked';
    };
    
    document.addEventListener("keydown", function(event) {
        if (event.code === 'KeyK' && event.target.tagName !== 'textarea') {
            btn.style.visibility = btn.style.visibility == "hidden" ? "visible" : "hidden";
        }
    });
  • Related