9

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?

5
  • 2
    Read the docs: api.jquery.com/focus Commented Apr 21, 2016 at 16:01
  • did you try document.activeElement Commented Apr 21, 2016 at 16:01
  • 1
    After edit: it gets called only once...that is when the document is ready Commented Apr 21, 2016 at 16:11
  • Ok @SamGhatak how can I improve it? Commented Apr 21, 2016 at 16:13
  • I'm trying first the trial code that I've added in the end. How do I display alert? Commented Apr 21, 2016 at 16:17

9 Answers 9

6

I think you need this type of a checking:

var hasFocus = $('#idOfTheInputElement').is(':focus');
if(hasFocus){
    //logic here
}
Sign up to request clarification or add additional context in comments.

1 Comment

I think you should put the checking inside the anewFunc().....you can remove the document.ready part from inside...and bind the function with the event that supposed to trigger the call
6

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

1 Comment

Concise, works (tested on Android 4.4.2) and pure JS, just what I was looking for, thank you Marat.
3

With Jquery 1.6+ :

$("..").is(":focus")

Comments

2

Here is an example showing a few different options:

CodePen Example

HTML

<input type='text' class="is-focus">

<input type="text" class="isActiveElement">

<input type="text" class="focused">

JS

$('input').on('click', function() {

  if ($('.is-focus').is(':focus')) {
    alert('focused')
  }

  if ($(document.activeElement).is('.isActiveElement')) {
    alert('isActiveAlement')
  }

  if($('.focused:focus').length) {
    alert(':focus')
  }
});

3 Comments

As you currently have it, you're not calling the function until the document is ready. So no, you do not need to include it in that function.
@VikasKumar : you will need it to set the interval, second use of document.ready inside the function newFunc is not required...instead, put a check there
Got it @SamGhatak I just din't define when should the if condition start. I put the :focus code inside a new setInterval and it worked when I clicked inside input! Thank you.
2

First, take the $(document).ready out of your function. You only need to call it once, not on interval.

var myInterval= null;  // in case you decide to clear it later.

function anewFunc() {

        var chatattr = $(".chatwindow").css("visibility");
        var chattitle = $("#hideid").text();
        var chatinput = $("#inputid");
        var chatText = chatinput.val();
        if (chatattr == "visible") {
            if (chatinput.is(":focus")) {
                $.ajax({
                    url: 'seen1.php',
                    type: 'post',
                    // if you're posting data, it should be as a json object
                    data: {"ctitle" : chattitle, "text":chatText}, 
                    success: function(result9) {},
                    error: function() {}
                });
            }
        } else {
            $.post("seendefault.php");
        }
}

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

This change calls your ready function ONCE, sets the interval, and gets the input field's value when it is focused.

Comments

1

The javascript event listener focus would only get fired once you focus the input box which is not ideal if you're doing multiple conditional statements .
I find having the expression document.activeElement == document.getElementById("input-box-id") more convenient in this regard .

Comments

0

You can use "is":

if ($("input").is(":focus")) {

....
...
}

Comments

0

Try to use even odd method

var i = 0;

$('.chatwindow').on('focus blur', function () {

  i += 1;

  var tog = function (someNum) {

     if ((someNum % 2) === 1) {
        return true;
     } else {
        return false;
     }
  };


  if (tog(i) === true) {
     // make ajax function

  } else {
    // do something else
  }
});

Comments

-2

You don't have to type a bunch of scripts, just add some simple css:

#yourInputOrWhatever:focus {
    /* Your New Code Here */
}

1 Comment

OP wants to send an Ajax request on focus, not change the appearance of focus

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.