0

I am looking for a way to differentiate between pressing Enter in a input[type="search"] event (search-event), and clearing the query by clicking X.

I have tried looking for variables in e and e.target

The only thing I can think of is:

search.addEventListener("search", (e) => {
 e.addEventListener("keypress", event => {
   if (event.key === "Enter") {
     ....
   }
 });

});

But I don't like this at all, and there is no way to specifically detect the clicking X. Normally I use handler functions, so the code readability will suffer from this event nesting I think.

Is there a built in way or better way to achieve this? All help & thoughts are welcome!

nicedev666
  • 56
  • 5
  • 2
    `search` is a non-standard event, so you are probably better looking for key events on the input element. From there you can easily check if it was X or any other key and react accordingly. – Gavin May 03 '22 at 12:04
  • 1
    be careful when adding events inside of events, because every time you trigger the search event you are adding a keypress event – Dumitru Birsan May 03 '22 at 12:14
  • @Gavin I have made edits to my post now, because the phrasing of pressing X was wrong. In the search element you can press Enter, and click X. That's what's throwing me off I think. – nicedev666 May 03 '22 at 12:15
  • @DivineSoul yes, thank you for explaining this. I didn't specifically know why, but I had a red hot feeling that I didn't like the event nesting at all. – nicedev666 May 03 '22 at 12:16
  • 1
    Just listen for `keyup`/`change` instead. `search` is strange to use. – mstephen19 May 03 '22 at 14:33

1 Answers1

1

From my experience, there is no way to differentiate between these two, unless you use specific function with onClick event handler.
This can also help. How do you detect the clearing of a "search" HTML5 input?