Alexis Garcia
Alexis Garcia

Reputation: 472

Know what element is currently focused using focus()

i have read alot of post here using the .focus(), but i cant solve my problem. I need to run an alert or console.log every time an element get focused, i need to keep pressing 'tab' and getting the element that is focused.

my problem is the selector itself, i know how to do the .focus() to a known element like

$('.foo').focus(function(){
  alert('foo is focused');
});

Upvotes: 1

Views: 762

Answers (3)

Kai
Kai

Reputation: 195

for other users who may need only to select specific inputs within a certain class you can use

<!-- set the same class for each input -->
    <label>first text box</label>
    <input type="text" class="myinput">
    <label>second text box</label>
    <input type="text" class ="myinput">

    <script>
    //on document ready add eventListner to all the inputs within your class
    $(document).ready(()=>{
        document.querySelectorAll('.myinput').forEach(item => {
        item.addEventListener('focus', event => {
        //handle focus
        console.log("got focus");
        //or
        alert("got foucs")
        })
        })

        })

    </script>

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

To achieve this you can use a delegated event handler. It will listen for the focus event on all child elements.

Note that this example is listening for the event on any form control, but that selector can be amended to target what is required in your specific use case.

$(document).on('focus', ':input', function() {
  console.log(this.id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="foo" />
<input type="text" id="bar" />
<input type="text" id="fizz" />
<input type="text" id="buzz" />

You could potentially use a wildcard selector (*) for this too, but there may be performance issues from doing that depending on how complex your HTML structure is.

Upvotes: 1

Archie
Archie

Reputation: 911

Use * (which will give you all DOM Nodes), or maybe a concise list of elements.

$("*").on("focus", function(){
  console.log(this.id);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="id1">
<input type="text" id="id2">

Upvotes: 1

Related Questions