Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if input field is in focus or not?

I want to send an Ajax request only when my input field is in focus (i.e., cursor is inside it. Here's my code:

function anewFunc() {
    $(document).ready(function(){
        var chatattr = $(".chatwindow").css("visibility");
        var chattitle = $("#hideid").text();
        if (chatattr == "visible") {
            if (MY INPUT FIELD HAS FOCUS) {
                $.ajax({
                    url: 'seen1.php',
                    type: 'post',
                    data: "ctitle="+chattitle,
                    success: function(result9) {},
                    error: function() {}
                });
            }
        } else {
            $.post("seendefault.php");
        }
    });
}

$(document).ready(function(){
    var zzz = setInterval(anewFunc, 2000);
});

Now I don't know how to check every time the input has focus or not. Is there any jQuery solution for it?

EDIT: A few answers has suggested me :focus. So I tried this for trial:

$(document).ready(function(){
                           if($("#msgtypeid").is(":focus")){
                               alert("Hello");
                           }
                           });

HTML:

<form id="chatform" name="form4" method="post" required enctype="multipart/form-data">
          <input id="msgtypeid" type="text" name="cmessage" autocomplete="off" autofocus/>
        </form>

But it's not working. Is there something wrong?

like image 356
Vikas Kumar Avatar asked Apr 21 '16 16:04

Vikas Kumar


3 Answers

I think you need this type of a checking:

var hasFocus = $('#idOfTheInputElement').is(':focus');
if(hasFocus){
    //logic here
}
like image 101
SamGhatak Avatar answered Oct 21 '22 21:10

SamGhatak


Add a focus-event handler to your input element, and your callback function will be called every time the element gets focused.

document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('example').addEventListener('focus', function() {
        alert('The input is focused.');
    });
});

Live demo

like image 32
Marat Tanalin Avatar answered Oct 21 '22 21:10

Marat Tanalin


With Jquery 1.6+ :

$("..").is(":focus")
like image 26
M.K. Wierzba Avatar answered Oct 21 '22 20:10

M.K. Wierzba