Robolisk
Robolisk

Reputation: 1792

Checking if my input box has been click or is 'in focus' pure js

I need to know if my input box is clicked so I can fire a script to do something, except none of the routes I'm attempting seem to do anything.

basic input box

<input type="text" id="search-stuff" placeholder="search"/>

Javascript

var inputBox = document.getElementById("search-stuff");
if (inputBox) {
    inputBox.addEventListener('keyup',function () {
        startSearch();
    })
    inputBox.addEventListener('onfocus',function() {
        console.log('we clicked');
        searchBoxClicked();
    })
}

function searchBoxClicked() { console.log('we clicked it'); }

I need to know if the user clicks so I can clear some classes on previous elements before the user types something.

Upvotes: 1

Views: 4751

Answers (2)

Chris
Chris

Reputation: 59511

You nearly got it right. A few minor mistakes:

  1. to listen to the focus event. onfocus isn't an event.
  2. the keyup event is for listening when a keyboard button is released (following a keydown event). If you want to listen to a mouse click, use the click event.

var inputBox = document.getElementById("search-stuff");
if (inputBox) {
  inputBox.addEventListener('click', function() {
    startSearch();
  });
  inputBox.addEventListener('focus', function() {
    searchBoxClicked();
  });
}

function searchBoxClicked() {
  console.log('focus');
}

function startSearch() {
  console.log('click');
}
<input type="text" id="search-stuff" placeholder="search" />

Upvotes: 2

TheWandererLee
TheWandererLee

Reputation: 1032

Attach the event listener to your input instead of the form. Instead of getElementById you could iterate the children to find it or use a selector. When using event listeners the event is click or focus not onclick or onfocus.

document.getElementById('search-stuff').addEventListener('focus',function() {
    console.log('clicked it');
};

or

document.querySelector('#formName > input[type=text]').addEventListener('focus',function() {
    console.log('clicked it');
});

document.querySelector('#formName > input[type=text]')
.addEventListener('focus',function() {
        console.log('clicked on ' + this.name);
    });
<form id="formName">
  <input name="username" type="text" value="press here">
</form>

Upvotes: 0

Related Questions