Kārlis Janisels
Kārlis Janisels

Reputation: 1295

How to stop onfocus event from firing?

I want to catch chatbox input field onfocus event to know that user has read the messages. When onfocus event is trigered I will send ajax to server that messages has been seen.

Whatever appproach I try I always get onfocus event constantly firing.

<input type="text" name="content<?php echo $id; ?>" placeholder="Type message..." onfocus="chatboxInputInFocus(<?php echo $id; ?>)"/>

and JS:

function chatboxInputInFocus(swap_id){
    alert(swap_id);
    return;
}

What I get is constant alert. How to catch only the moment when input comes to focus? JS or Jquery.

Upvotes: 2

Views: 1829

Answers (3)

Ganesh Madhu
Ganesh Madhu

Reputation: 1

Need here to pass the event object in the onfocus function param and do the preventdefault. function chatboxInputInFocus(swap_id){ alert(swap_id); ev.preventDefault(); return; } onfocus="chatboxInputInFocus(event,id)" `

Upvotes: 0

Serg Chernata
Serg Chernata

Reputation: 12400

You can use the handy .one method of jQuery.

$(document).ready(function(){
    $("input").one('focus', function(){
        alert('Just once!');
    });
});

https://api.jquery.com/one/

Upvotes: 2

Alexey Soshin
Alexey Soshin

Reputation: 17701

Don't use alert() for debugging, as it triggers your focus.
Use console.log() instead, and your code will work.

function chatboxInputInFocus(swap_id){
        console.log(swap_id);
        return;
    }
<input type="text" name="content123" placeholder="Type message..." onfocus="chatboxInputInFocus(123)"/>

Upvotes: 5

Related Questions