Height Listener, jQuery

1.4k Views Asked by At

I'm creating a rich text editor.

Basically I have an iframe with design mode enabled. I'd like it to automatically resize when the user get near the bottom of the iframe while typing, or pasting text.

I have the function to change size.

function changeHeight() {

    $(iframe).height($(iframe.contentWindow.document).height());

}

I just need to add a listener. I can't for the life of me find one that works!

Any ideas?

Much appreciated

-Will

1

There are 1 best solutions below

3
On BEST ANSWER

Do this: http://sonspring.com/journal/jquery-iframe-sizing and add an onkeypress listener to check for resize.

Fair warning: if the content is not within the same domain --- it will NOT work due to XSS vulnerability prevention (you cannot trap the keypress event in this case).

This has been tested in IE7 to work, should work across most browsers. You're not actually attaching to the iFrame itself either, so much as the element you're interested in (which could very well be the body).

<script type="text/javascript" language="javascript">
  $(document).ready(function() {
    $('#IFRAME').contents().find('textarea').bind('keypress', function() { 
      //Dostuff    
     })
  });
</script>

<iframe src="/whatever.html" width="800" height="400" id="IFRAME" ></iframe>

Where you have a textarea (or div, or whatever) inside the iframe ... change the filter to your heart's content. Iframe resize code shows up in the sonspring article.

**

Edit again for code that attaches to IFRAME directly

Source [only replaced jQuery functions for native DOM. I'll clean out what I can when I have more time]: http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_25589672.html

**

<script>
  $(document).ready(function() {
    var f = $('#IFRAME')[0];
    var fwin = f.contentWindow || f.contentDocument;
    fwin.document.designMode = 'on';

    var evt_key = function(e) {
      e = e || fwin.event;
      var range = null, ret = null;

      if (fwin.document.selection) {
        range = fwin.document.selection.createRange();
        ret = range.parentElement();
      }
      else if (fwin.window.getSelection) {
        var range = fwin.window.getSelection().getRangeAt(0);
        ret = range.commonAncestorContainer.parentNode || fwin.document;
      }

      fwin.parent.eventCallback();
    };

    if (fwin.document.attachEvent) {
      fwin.document.attachEvent('onkeypress', evt_key);
    }
    else if (fwin.document.addEventListener) {
      fwin.document.addEventListener('keypress', evt_key, false);
    }  
  })

  function eventCallback() {
    alert('Key Pressed');
  }
</script> 

<iframe src="#" width="800" height="400" id="IFRAME" ></iframe>