Sorry if this has already been asked, but all the results I've found use jQuery.
I have the following code:
<script>
var nameBox = document.getElementById('name');
if(nameBox == document.activeElement) {
console.log('name element focused')
}
</script>
But, nothing gets logged to the console when I click on the input. What am I doing wrong? (I would like to do this without jQuery)
Sorry if this has already been asked, but all the results I've found use jQuery.
I have the following code:
<script>
var nameBox = document.getElementById('name');
if(nameBox == document.activeElement) {
console.log('name element focused')
}
</script>
But, nothing gets logged to the console when I click on the input. What am I doing wrong? (I would like to do this without jQuery)
Share Improve this question asked Mar 24, 2017 at 10:33 user7582581user7582581 3- Use element.focus(). – Mistalis Commented Mar 24, 2017 at 10:35
- 1 @Rajesh — The question is not tagged jQuery and clearly indicates in the first line that a jQuery solution is not desired. – Quentin Commented Mar 24, 2017 at 10:37
- My apologies. Missed that. Would find relevant link and share it – Rajesh Commented Mar 24, 2017 at 10:37
3 Answers
Reset to default 3In your case you are detecting if the element is active during the script's run, so you get false. After it you don't have any detectors. So you need to use addEventListener()
function and add handler for focus
event. It will fire when element is focused.
document.getElementById('inp').addEventListener('focus', function(){
console.log('Focused');
});
<input id="inp" />
You are testing if the element is focused now instead setting up an event listener to do something when it gains the focus.
function your_function(event) {
console.log('name element focused')
}
nameBox.addEventListener("focus", your_function);
There are some ways you can do this:
1. onFocus:
function focused(element) {
element.style.background = "gold";
}
<input type="text" onfocus="focused(this)">
<input type="text" onfocus="focused(this)">
2. addEventListener
inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener('focus', function(element){
document.activeElement.style.background="gold"
});
}
<input type="text"/>
<input type="text"/>
3. Jquery focus:
$(function(){
$( "input" ).focus(function(e) {
$(this).css( "background", "gold" );
});
})
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"/>
<input type="text"/>