kbd handler

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • J. J. Cale

    kbd handler

    Hi
    The code below worked fine in IE5. I changed to IE6 and I can trap the
    'enter' key but I can't add a line feed to the text in the div. Also what
    other browser should I be testing with and where can I download it? I intend
    to write a full blown kbd handler that will also trap the backspace and tab
    etc. I can use all the help I can get. BTW I tried doing this with a
    textarea but I need to write directly to the divide. The intention here is
    to have a letter that can have different borders clipart etc and the ability
    to select text and change the various css properties or use exec Command to
    toggle them. If anyone has this working or knows of someone or a site that
    has I'll be ecstatic.
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <HTML><HEAD><TI TLE>kbd handler</TITLE>
    <script type="text/javascript">
    document.onkeyp ress = function (evt) {
    var el = document.all?le tter:document.g etElementById(' letter');
    var evt = evt || window.event;
    var keyCode = evt.keyCode || evt.which;
    // alert(keyCode);
    if(keyCode == 27) return;
    if(keyCode == 13) {
    el.firstChild.d ata += '\n';
    el.innerText += '\n';
    el.innerHTML += '<br>';
    return;
    }
    var str = String.fromChar Code(keyCode);
    // el.firstChild.d ata += str;
    el.innerText += str;
    }
    </script></HEAD>
    <BODY>
    <div id="letter"
    style="width:30 0px;padding:4px ;margin-left:4px;height :450px;backgrou nd-color
    :#ffffcc;"></div>
    </BODY></HTML>
    TIA
    Jimbo


  • Yann-Erwan Perio

    #2
    Re: kbd handler

    J. J. Cale wrote:
    [color=blue]
    > Also what
    > other browser should I be testing with and where can I download it?[/color]

    There are plenty of browsers to test with, legacy browsers and exotic
    browsers to ensure clean degradation, and modern browsers to ensure your
    script works correctly (check Mozilla and Opera).
    [color=blue]
    > I intend
    > to write a full blown kbd handler that will also trap the backspace and tab
    > etc. I can use all the help I can get. BTW I tried doing this with a
    > textarea but I need to write directly to the divide.[/color]

    Then you'll have to handle key events, which unfortunately haven't been
    much standardised; this means you can expect different behaviors across
    user agents, all the more you'll be dealing with built-in key behaviors,
    like navigation, search etc which will of course differ between the
    browsers you'll test your script in:-)
    [color=blue]
    > If anyone has this working or knows of someone or a site that
    > has I'll be ecstatic.[/color]

    Nope but it's been time since I haven't done some javascript, here's
    some lines for you. Tested IE5, IE6, Mozilla and Opera 7.5. HTH.


    <head>
    <style type="text/css">
    html, body {background:#00 0; color:#9f0;}
    </style>
    </head>

    <body>
    <script type="text/javascript">
    // kbd
    function Screen(screenId ){
    document.write( "<div id=\""+screenId +"\">_<\/div>");
    this.html=docum ent.getElementB yId(screenId);
    }

    Screen.prototyp e.insertLineBre ak=function() {
    this.html.inser tBefore(
    document.create Element("br"),
    this.html.lastC hild
    );
    }

    Screen.prototyp e.insertChar=fu nction(c) {
    this.html.inser tBefore(
    document.create TextNode(c),
    this.html.lastC hild
    );
    }

    Screen.prototyp e.deleteChar=fu nction() {
    var childToRemove=t his.html.lastCh ild &&
    this.html.lastC hild.previousSi bling;
    if(childToRemov e)
    this.html.remov eChild(childToR emove);
    }

    Screen.prototyp e.setDefaultOut put=function() {
    var screenObj=this;
    var doKeyPress=true ;
    var keyPressReturnV alue=false;

    // primary key controller
    // used to manage browsers' default action and secondary controller
    document.onkeyd own=function(ev t){
    var key,returnValue ;

    evt=evt||window .event;
    key=evt.keyCode ||evt.which;

    returnValue=tru e;
    doKeyPress=true ;
    keyPressReturnV alue=false;

    switch(key) {
    case 8: //DEL
    document.onkeyp ress({keyCode:8 }); //special IE!
    doKeyPress=fals e; //already done
    keyPressReturnV alue=false; // prevent default
    returnValue=fal se; // prevent default
    break;

    case 116: //refresh
    doKeyPress=fals e; //don't print anything
    keyPressReturnV alue=true; //permit the refresh
    returnValue=tru e; //permit the refresh
    break;
    }

    return returnValue;
    }

    // secondary key controller
    // used to handle regular keystrokes
    document.onkeyp ress = function(evt) {
    var key;
    evt=evt||window .event;
    key=evt.keyCode ||evt.which;

    if(doKeyPress) {
    switch(key) {
    case 0 : //undefined
    case 16: //SHIFT
    case 17: //CTRL
    case 18: //ALTGR
    break;

    case 13: //ENTER
    screenObj.inser tLineBreak();
    break;

    case 8: //DEL
    screenObj.delet eChar();
    break;

    default:
    screenObj.inser tChar(String.fr omCharCode(key) );
    break;
    }
    }

    return keyPressReturnV alue;
    }
    }

    // main
    if(document.get ElementById &&
    document.create TextNode &&
    document.create Element &&
    document.body &&
    document.body.a ppendChild &&
    document.body.r emoveChild &&
    document.body.i nsertBefore
    ){

    (new Screen("screen" )).setDefaultOu tput();

    } else {
    document.write( "<p>System failure /<\/p>");
    }
    </script>
    <noscript><p>Sy stem failure /</p></noscript>
    </body>

    Comment

    • J. J. Cale

      #3
      Re: kbd handler

      Thank you! Youv'e saved me a lot of work. I can plug this straight into my
      project and tweak it to my needs.

      Actually I was hoping to do this without the DOM. I already did most of this
      with the textarea for input and assignment via the DOM. Your code is tighter
      and much more elegant!!

      In IE5 the appending of the charachter '\n' to the objects data attribute
      (or to innerText) gave me the line feed but this disappeared when I upgraded
      to IE6. I did my homework on the different ways that browsers handle events.
      Can you change my original code to append the '\n' or if necessary '\r\n'
      and have the cursor 'move' to the next line?(no DOM).

      If not I thank you again for your excellent solution and your time. Be
      thrice blessed.

      Jimbo
      "Yann-Erwan Perio" <y-e.perio@em-lyon.com> wrote in message
      news:417eb5fb$0 $23855$626a14ce @news.free.fr.. .[color=blue]
      > J. J. Cale wrote:
      >[color=green]
      > > Also what
      > > other browser should I be testing with and where can I download it?[/color]
      >
      > There are plenty of browsers to test with, legacy browsers and exotic
      > browsers to ensure clean degradation, and modern browsers to ensure your
      > script works correctly (check Mozilla and Opera).
      >[color=green]
      > > I intend
      > > to write a full blown kbd handler that will also trap the backspace and[/color][/color]
      tab[color=blue][color=green]
      > > etc. I can use all the help I can get. BTW I tried doing this with a
      > > textarea but I need to write directly to the divide.[/color]
      >
      > Then you'll have to handle key events, which unfortunately haven't been
      > much standardised; this means you can expect different behaviors across
      > user agents, all the more you'll be dealing with built-in key behaviors,
      > like navigation, search etc which will of course differ between the
      > browsers you'll test your script in:-)
      >[color=green]
      > > If anyone has this working or knows of someone or a site that
      > > has I'll be ecstatic.[/color]
      >
      > Nope but it's been time since I haven't done some javascript, here's
      > some lines for you. Tested IE5, IE6, Mozilla and Opera 7.5. HTH.
      >
      >
      > <head>
      > <style type="text/css">
      > html, body {background:#00 0; color:#9f0;}
      > </style>
      > </head>
      >
      > <body>
      > <script type="text/javascript">
      > // kbd
      > function Screen(screenId ){
      > document.write( "<div id=\""+screenId +"\">_<\/div>");
      > this.html=docum ent.getElementB yId(screenId);
      > }
      >
      > Screen.prototyp e.insertLineBre ak=function() {
      > this.html.inser tBefore(
      > document.create Element("br"),
      > this.html.lastC hild
      > );
      > }
      >
      > Screen.prototyp e.insertChar=fu nction(c) {
      > this.html.inser tBefore(
      > document.create TextNode(c),
      > this.html.lastC hild
      > );
      > }
      >
      > Screen.prototyp e.deleteChar=fu nction() {
      > var childToRemove=t his.html.lastCh ild &&
      > this.html.lastC hild.previousSi bling;
      > if(childToRemov e)
      > this.html.remov eChild(childToR emove);
      > }
      >
      > Screen.prototyp e.setDefaultOut put=function() {
      > var screenObj=this;
      > var doKeyPress=true ;
      > var keyPressReturnV alue=false;
      >
      > // primary key controller
      > // used to manage browsers' default action and secondary controller
      > document.onkeyd own=function(ev t){
      > var key,returnValue ;
      >
      > evt=evt||window .event;
      > key=evt.keyCode ||evt.which;
      >
      > returnValue=tru e;
      > doKeyPress=true ;
      > keyPressReturnV alue=false;
      >
      > switch(key) {
      > case 8: //DEL
      > document.onkeyp ress({keyCode:8 }); //special IE!
      > doKeyPress=fals e; //already done
      > keyPressReturnV alue=false; // prevent default
      > returnValue=fal se; // prevent default
      > break;
      >
      > case 116: //refresh
      > doKeyPress=fals e; //don't print anything
      > keyPressReturnV alue=true; //permit the refresh
      > returnValue=tru e; //permit the refresh
      > break;
      > }
      >
      > return returnValue;
      > }
      >
      > // secondary key controller
      > // used to handle regular keystrokes
      > document.onkeyp ress = function(evt) {
      > var key;
      > evt=evt||window .event;
      > key=evt.keyCode ||evt.which;
      >
      > if(doKeyPress) {
      > switch(key) {
      > case 0 : //undefined
      > case 16: //SHIFT
      > case 17: //CTRL
      > case 18: //ALTGR
      > break;
      >
      > case 13: //ENTER
      > screenObj.inser tLineBreak();
      > break;
      >
      > case 8: //DEL
      > screenObj.delet eChar();
      > break;
      >
      > default:
      > screenObj.inser tChar(String.fr omCharCode(key) );
      > break;
      > }
      > }
      >
      > return keyPressReturnV alue;
      > }
      > }
      >
      > // main
      > if(document.get ElementById &&
      > document.create TextNode &&
      > document.create Element &&
      > document.body &&
      > document.body.a ppendChild &&
      > document.body.r emoveChild &&
      > document.body.i nsertBefore
      > ){
      >
      > (new Screen("screen" )).setDefaultOu tput();
      >
      > } else {
      > document.write( "<p>System failure /<\/p>");
      > }
      > </script>
      > <noscript><p>Sy stem failure /</p></noscript>
      > </body>[/color]


      Comment

      • Yann-Erwan Perio

        #4
        Re: kbd handler

        J. J. Cale wrote:

        Hi Jimbo,
        [color=blue]
        > Thank you! Youv'e saved me a lot of work. I can plug this straight into my
        > project and tweak it to my needs.[/color]

        Glad that helped:-)
        [color=blue]
        > Actually I was hoping to do this without the DOM.[/color]

        I cannot really comment about this, a script conception depends on the
        context, if you can tell us what you're exactly trying to achieve then I
        (or others) might provide you with some more information on how to
        tackle the problem at a global level.
        [color=blue]
        > In IE5 the appending of the charachter '\n' to the objects data attribute
        > (or to innerText) gave me the line feed but this disappeared when I upgraded
        > to IE6.[/color]

        I cannot see this, to me the behavior is the same in IE5 and IE6 - could
        you post a simple test case?
        [color=blue]
        > Can you change my original code to append the '\n' or if necessary '\r\n'
        > and have the cursor 'move' to the next line?(no DOM).[/color]

        I'm afraid not, to me inserting a line break won't work, you have to
        insert a BR element, using DOM methods or innerHTML with some dummy text
        (innerHTML="<br >" does nothing AFAICS).

        Also note that mixing innerHTML and innerText might provide unwanted
        side-effects, since reading a BR via innerText, and writing innerText
        afterwards, transforms the BR into CR/LF, which will render differently
        on the screen.


        Regards,
        Yep.

        Comment

        • Yann-Erwan Perio

          #5
          Re: kbd handler

          Yann-Erwan Perio wrote:
          [color=blue]
          > (innerHTML="<br >" does nothing AFAICS).[/color]

          I've just reviewed my test case, it's faulty - innerHTML works fine of
          course, it's just that I also tested for innerText and got unexpected
          results with it (I'm not used to innerText) - sorry for the confusion!


          <div id="foo">&nbsp; </div>
          <script type="text/javascript">
          function L() {alert(foo.inne rText.length)};

          foo.innerHTML=" <br>"; L(); //0
          foo.innerHTML=" <br>1"; L(); //3
          foo.innerHTML=" <br> <br>"; L(); //0
          foo.innerHTML=" <br>1 "; L(); //4
          foo.innerHTML=" <br> 1"; L(); //3
          foo.innerHTML=" <br>1 <br>"; L(); //4
          foo.innerHTML=" <br> 1<br>"; L(); //3
          </script>

          Comment

          • J. J. Cale

            #6
            Re: kbd handler

            YEP Sorry about the email. Hit the reply instead of group reply. Thanks for
            staying with me.[color=blue]
            > if you can tell us what you're exactly trying to achieve then I
            > (or others) might provide you with some more information on how to
            > tackle the problem at a global level.[/color]

            from original post -
            "The intention here is to have a letter" (letterhead) "that can have
            different borders clipart etc and the ability to select text and change the
            various css properties or use exec Command to toggle them."
            [color=blue]
            > Also note that mixing innerHTML and innerText might provide unwanted
            > side-effects, since reading a BR via innerText, and writing innerText
            > afterwards, transforms the BR into CR/LF, which will render differently
            > on the screen.[/color]

            Definately! I only used innerText to see if I got the same result as
            obj.firstChild. data and didn't use it for assignment. I've been checking
            both the DOM possibilities and innerHTML. Both have their challenges. AFAIK
            innerText is not as widely supported as innerHTML and the DOM is fairly
            safe.

            Does Mozilla have the event object limitations of Netscape's DOM?
            Does it support the createTextRange or createRange or createControlRa nge
            methods?
            Have you any ideas how to emulate IE execCommand in Mozilla?

            Your code has another advantage in that it creates a separate textNode for
            each character. I read that text nodes can be the target/srcElement of the
            event object. Does the DOM have a separate event model? I am confused
            probably about this.

            Here is the basis of my last project. Sorry IE only.
            in my original project changeSelection () is called from a controller with
            options for bold, italic, underline, family, size, justification and color.
            It is passed a parameter: changeSelection ('Bold') which I switch in the
            original function and pass to execCommand or another function.
            e.g.
            <a href="#" onclick = "changeSelectio n('Bold'); return false;"><b>B</b></a>
            <a href="#" onclick = "changeSelectio n('Italic'); return
            false;"><i>I</i></a>

            <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
            <HTML><HEAD> <TITLE>Stationa ry Project Handlers</TITLE>
            <style type=text/css>
            <!--
            #letter {
            position:absolu te;
            top:20px;
            width:45%;
            height:90%;
            background-color:#ffffcc;
            color:navy;
            padding:15px;
            border:1px black solid;
            }
            -->
            </style>
            <script language="JavaS cript">
            function handleKey() {
            if(event.keyCod e == 8) {
            letter.innerHTM L =
            letter.innerHTM L.substring(0,l etter.innerHTML .length-2) + '_';
            event.returnVal ue = false;
            }
            if(event.keyCod e == 13) {
            letter.innerHTM L =
            letter.innerHTM L.substring(0,l etter.innerHTML .length-1);
            letter.innerHTM L += '<br>_';
            event.returnVal ue = false;
            }
            }
            function keyPress(){
            letter.innerHTM L =
            letter.innerHTM L.substring(0,l etter.innerHTML .length-1);
            var a = String.fromChar Code(event.keyC ode);
            if(!a) {alert("NO");re turn;}
            letter.innerHTM L += (a + '_');
            }
            function changeSelection () { // primitive just for example
            // alert(letter.in nerHTML); return; // for debugging
            var range = document.select ion.createRange ();
            var str=range.text;
            range=document. body.createText Range();
            range.findText( str);
            range.execComma nd('Bold');
            document.select ion.empty();
            }
            document.onkeyd own = handleKey;
            document.onkeyp ress = keyPress;
            document.onmous eup=changeSelec tion;
            </script></HEAD>
            <BODY><div id="letter">_</div></BODY></HTML>
            Thanks again Jimbo



            Comment

            • Yann-Erwan Perio

              #7
              Re: kbd handler

              J. J. Cale wrote:
              [color=blue]
              > from original post -
              > "The intention here is to have a letter" (letterhead) "that can have
              > different borders clipart etc and the ability to select text and change the
              > various css properties or use exec Command to toggle them."[/color]

              You're right sorry, I read it too fast. The best cross-browser way is to
              use a textarea and have the content parsed server-side, but if you can
              afford reducing your browsers' range then give a look to
              designMode-based editors.
              [color=blue]
              > Does Mozilla have the event object limitations of Netscape's DOM?[/color]

              Argh. What event object limitation? Mozilla, as Netscape 7+, follows the
              W3C's event model, which is much more powerful than IE's event model
              (event capture, custom events...).

              <URL:http://www.brainjar.co m/dhtml/events/>
              <URL:http://www.w3.org/TR/DOM-Level-3-Events/>

              The tutorial is quite old, but remains instructive; the reference is a
              bit hard, though certainly worth a long study.
              [color=blue]
              > Does it support the createTextRange or createRange or createControlRa nge
              > methods?[/color]

              Not as IE proprietary methods:-) However, Mozilla implements the W3C
              Ranges specification, also adding some proprietary things.

              <URL:http://www.w3.org/TR/2000/REC-DOM-Level-2-Traversal-Range-20001113/ranges.html>
              [color=blue]
              > Have you any ideas how to emulate IE execCommand in Mozilla?[/color]

              It depends on the command being executed. If it's related to style, then
              you can emulate it using DOM ranges and heavy DOM nodes manipulation.
              I've posted a way to emulate the "Bold" command some while ago.

              <URL:http://groups.google.c om/groups?selm=410 2f3f9%240%24293 82%24626a14ce%4 0news.free.fr>

              The approach to emulate italic, underline and forecolor at the same time
              would be a bit different, though. I believe that the best way would be
              to use SPAN elements with multiple CSS classes; not an easy coding task.
              [color=blue]
              > I read that text nodes can be the target/srcElement of the
              > event object.[/color]

              And where did you read that:-) In IE events only go to elements, and in
              Mozilla it depends on the version. Basically don't count on events for
              text nodes.

              However using a textNode per char should prove useful since you can
              design string-like methods (a node is a char).


              Cheers,
              Yep.

              Comment

              Working...