Reputation: 1792
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
Reputation: 59511
You nearly got it right. A few minor mistakes:
focus
event. onfocus
isn't an event.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
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