0

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>
eNigma
  • 101
  • 4
  • 10
  • How do you define "being used"? When the textarea has focus, or has text, or what? – G-Nugget Sep 14 '12 at 03:04
  • What do you mean by "being used by a user"? – Ilia Frenkel Sep 14 '12 at 03:04
  • sorry yah. Um a user typing in the textarea but no enter keystroke. – eNigma Sep 14 '12 at 03:07
  • 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. – eNigma Sep 14 '12 at 03:09

3 Answers3

2

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>
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • hi jfriend i think the impressive js you submitted would work. I am stuck on implementation. If the var events are met I need the following function not to execute autoRefresh(refreshPeriod) { setTimeout("window.location.reload();",refreshPeriod); } – eNigma Sep 14 '12 at 18:37
  • i tried the following but not sure why it's isn't working: var obj = document.getElementById("adm_update"); if (!(document.activeElement === obj)) { autoRefresh(refreshPeriod) function autoRefresh(refreshPeriod) { setTimeout("window.location.reload();",refreshPeriod); } } – eNigma Sep 14 '12 at 18:43
  • @eNigma - I added a revised version of what you were trying to the end of my answer. My version sets a timer for refreshPeriod and upon that timer checks to see if the focus is in the adm_update field or not. If it is, then no refresh is done. If the focus is not in that field, then a refresh is done. – jfriend00 Sep 14 '12 at 20:01
  • hi @jfriend00 let me try that code. I'm in my localhost right now. – eNigma Sep 14 '12 at 20:22
  • hi @jfriend00 so I tried the code but when typing in the textarea it refreshes so not sure what I'm doing wrong. – eNigma Sep 14 '12 at 20:31
  • @eNigma - I can't help further without seeing your actual page/implementation. The concept of detecting where the focus is works in all browsers in the jsFiddle I posted. – jfriend00 Sep 14 '12 at 20:44
  • that's a piece of the view in the comment I posted. Is the focus wrong? – eNigma Sep 14 '12 at 20:52
  • @eNigma - please do not post multiline code into a comment ever. It is completely unreadable. Use the edit button to add it to the end of your question (where you can properly format it as multiple lines of code/html) and then post a comment to tell people you've added it. When I try to decipher the code from your comment, all I see it HTML, no javascript. I cannot see what you've implemented. – jfriend00 Sep 14 '12 at 20:58
  • sorry I deleted it. I edited my example with the code you provided and showed where I did the onfocus but not sure what's wrong with onfocus i did. – eNigma Sep 14 '12 at 21:04
  • @eNigma. Probably best if you edit your *question*, not someone else's answer. :) – PaulG Sep 14 '12 at 21:10
  • yah i edited my question and the answer. Just trying to desperately communicate here so I can resolve this issue. Point taken though PaulG. :) – eNigma Sep 14 '12 at 21:13
  • @eNigma - If you put the code that I have at the end of my answer now into your page and put that code right before the `

    ` tag in your page, it should work with the HTML you have. You do not need any onfocus handler. This just checks every 2 seconds to see if the focus is in the textarea. If not, it refreshes the page. If the focus is in the textarea, it does nothing. It appears that the textarea in your HTML has an `id="create"` so I changed the code to match that. You must start this code AFTER the page has loaded. That's why I say to put it right before the `` tag.

    – jfriend00 Sep 14 '12 at 21:15
  • yah i'm gonna try what your saying again – eNigma Sep 14 '12 at 21:20
  • i removed the onfocus code in my view file. Just only trying exactly what you have as the answer which I agree should work. – eNigma Sep 14 '12 at 21:21
  • FINALLY GOT IT WORKING. I love you @jfriend00. I had the freakin – eNigma Sep 14 '12 at 21:37
0
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
};
EpsonZhao
  • 51
  • 1
  • 4
  • Misleading. `onfocus` fires when the user *starts* using the textarea, not *while* they are using it. – Niet the Dark Absol Sep 14 '12 at 03:10
  • @Kolink True, but the OP said they are targeting the textarea being "used", but not being typed in...as in, it has focus, but nothing is happening. – Ian Sep 14 '12 at 03:11
  • I never said anything about typing. If I click the textarea and go make a cup of tea, I'm still "using" the textarea but `onfocus` will not tell me that unless I save its state. – Niet the Dark Absol Sep 14 '12 at 03:13
  • What are you talking about? Of course you need to save the state with this solution, and you can toggle the state with `onblur` as well. Just like your solution has to save the state of the currently focused element in the body... – Ian Sep 14 '12 at 03:18
-1

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
}
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • I don't think you know what the onfocus of the body actually is. Try this: http://jsfiddle.net/86rFQ/ . The only time onfocus of the body is called when the window is focused (basically when switching tabs or focusing/blurring the browser window...or in this case, the iframe in the jsFiddle). Even if this did what you expected, it could easily be broken by any element stopping propagation on focus. – Ian Sep 14 '12 at 03:37