user7582581
user7582581

Reputation:

Detect when input focuses

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)

Upvotes: 1

Views: 8666

Answers (3)

Mohammad Kermani
Mohammad Kermani

Reputation: 5396

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.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"/>
<input type="text"/>

Upvotes: 1

Suren Srapyan
Suren Srapyan

Reputation: 68645

In 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" />

Upvotes: 3

Quentin
Quentin

Reputation: 943510

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);

Upvotes: 1

Related Questions