简体   繁体   中英

detect whether a text area is being used with javascript

MAJOR THANKS TO EVERYONE WHO POSTED TO TRY TO HELP. YOU GUYS ARE AWESOME! :)

I used @jsfriend00 solution and it accomplished the functionality I needed for client browser cache problem.

Hi I have a question regarding javascript:

Wondering if there is a way to detect whether a textarea is being used by a user meaning the user is messaging another user but there isn't yet an enter keystroke?

I've been thinking I can solve my cache issue with my private networking stream if I can get the client browser cache to refresh only if the user is not attempting to message another user because then obviously they loose what they're typing because of automatic refresh.

Say for example the following textarea:

 <html>
 <title></title>
 <head>
 <script>
 function autoRefresh(refreshPeriod) {
 var obj = document.getElementById("create"); 

     function refreshIfSafe() {
     if (document.activeElement !== obj) { 
        window.location.reload();
      } else {
        setTimeout(refreshIfSafe, refreshPeriod);
      }
   }
       setTimeout(refreshIfSafe, refreshPeriod);
 }

       autoRefresh(2 * 1000);

  </script>

  <?php echo smiley_js(); ?>

 </head>
 <body>


<?php echo form_open('controller/function') ?>
<p><label for="create">chat here:<span class="optional"></span></label>                                
<textarea name="create" id="create" onfocus="autoRefresh(this.id)" rows="3" cols="20"></textarea> 
<?php echo form_error('create'); ?>
</p>
<?php echo form_submit('submit','chat');?>
 <?php echo form_close();?>
 </body>
 </html>

If what you want to know is whether the focus is currently in your textarea, then you can just check that by checking to see if document.activeElement is your textarea object or not.

var obj = document.getElementById("myTextArea");
if (document.activeElement === obj) {
    // focus is currently in my textarea
}

You can see a working demo: http://jsfiddle.net/jfriend00/NCSed/


If what you want to know is when your textarea is being modified, here is some code that will install a change handler on your textarea and call your event handler anytime the text in the textarea is changed. This code works with either textarea objects or input objects. Unlike other methods, this captures changes done by typing, by mouse editing, cut, copy, paste and drag/drop. You can then tell when the user is typing or when any text has been typed. Here's a working test engine for this code: http://jsfiddle.net/jfriend00/xxCkm/ .

And, here's the code:

// add event cross browser
function addEvent(elem, event, fn) {
    if (elem.addEventListener) {
        elem.addEventListener(event, fn, false);
    } else {
        elem.attachEvent("on" + event, function() {
            // set the this pointer same as addEventListener when fn is called
            return(fn.call(elem, window.event));   
        });
    }
}

function onChange(elem, fn, data) {
    var priorValue = elem.value;

    function checkNotify(e, delay) {
        // log('checkNotify - ' + e.type);
        if (elem.value != priorValue) {
            priorValue = elem.value;
            fn.call(this, e, data);
        } else if (delay) {
            // the actual data change happens aftersome events
            // so we queue a check for after
            setTimeout(function() {checkNotify(e, false)}, 1);
        }
    }

    // Which events to monitor
    // the boolean value is whether we have to 
    // re-check after the event with a setTimeout()
    var events = [
       "keyup", false,
       "blur", false,
       "focus", false,
       "drop", true,
       "change", false,
       "input", false,
       "paste", true,
       "cut", true,
       "copy", true
    ];
    for (var i = 0; i < events.length; i+=2) {
        (function(i) {
            addEvent(elem, events[i], function(e) {
                checkNotify(e, events[i+1]);
            });
        })(i);
    }
}

Then, sample usage is like this:

var obj = document.getElementById("test");    
onChange(obj, function(e) {
    // your code goes here for whatever you want to do 
    // when the change handler is called
    console.log("change - " + e.type);
});

Looking at the code in your comment, I would suggest this:

<script>
function autoRefresh(refreshPeriod) {
    var obj = document.getElementById("create"); 

    function refreshIfSafe() {
        if (document.activeElement !== obj) { 
            window.location.reload();
        } else {
            setTimeout(refreshIfSafe, refreshPeriod);
        }
    }

    setTimeout(refreshIfSafe, refreshPeriod);
}

autoRefresh(2 * 1000);
</script>
var textarea = document.getElementById("create") ;
textarea.onfocus = function() {
    // Do something while the textarea being used by a user
};

textarea.onblur = function() {
    // Do something while the textarea not being used by a user
};

this link is may be the thing you want look at Tim Down's answer.

Javascript OnChange detection for textarea

This is actually one of the very rare cases where I'm going to say jQuery makes it easier.

if($("#create").is(":focus")) {
    // element is in use
}

The alternative would be something like:

document.body.onfocus = function(e) {
    e = e || window.event;
    window.elementWithFocus = e.target || e.srcElement;
}
...
if( document.getElementById('create') == window.elementWithFocus) {
    // element is in use
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM