0

I'm not quite sure what I am doing wrong, I looked up a way to see if an element has focus. I found the document.hasFocus() method. So I tried and I debugged on Chrome and got "Uncaught TypeError: Object # has no method 'hasFocus'.". Here is my JavaScript:

var e = document.getElementById("editor").contentWindow;
e.document.designMode="on";
e.document.open();
e.document.write("<head><style>body{font-family:arial,helvetica,sans-serif;font-size:12px;}</style></head>");
e.document.close();
function def() {
   document.getElementById("fonts").selectedIndex = 0;
   document.getElementById("size").selectedIndex = 1;
   document.getElementById("color").selectedIndex = 0;
}
function edit(x, y) {
   e.document.execCommand(x, false, y);
   e.focus();
}
setInterval(function() {
    if (document.getElementById("editor").contentWindow.hasFocus()) {
        document.getElementById("html").value = document.getElementById("editor").contentWindow.document.body.innerHTML;
    }
    else if (document.getElementById("html").hasFocus()) {
        document.getElementById("editor").contentWindow.document.body.innerHTML = document.getElementById("html").value;
    }
}, 100);
Solo
  • 726
  • 1
  • 9
  • 18

2 Answers2

1

The method "hasFocus" only exists on the document object, not on individual nodes. See - https://developer.mozilla.org/en-US/docs/DOM/document.hasFocus

If you want to check whether or not an input is focused, you can do so by updating a variable on the "onfocus" event of your inputs, and than check that variable for the focused element. See - In Javascript find if a checkbox is focused

Community
  • 1
  • 1
levi
  • 23,693
  • 18
  • 59
  • 73
  • Will this work on checking if the iframe has focus? Because this is for a WYSIWYG editor. – Solo Oct 04 '12 at 21:10
  • Possibly. Depends on how the WYSIWYG editor is implemented. Try it. Also, see - http://www.sitepoint.com/forums/showthread.php?273772-How-to-detect-iframe-onfocus-event-in-Firefox and http://robsanheim.com/2006/05/23/browser-bugs-onblur-and-onfocus-with-iframes/ – levi Oct 04 '12 at 22:48
0

Try document.activeElement instead. It's part of the HTML5 spec and supported by the latest Chrome, Opera, Firefox and IE.

You can also use this script for browsers that don't support it. http://ajaxandxml.blogspot.com/2007/11/emulating-activeelement-property-with.html

Thinking Sites
  • 3,494
  • 17
  • 30