javascript help

Discussion in 'Computer Games and General Discussion' started by Cyan, Mar 4, 2010.

Mar 4, 2010

javascript help by Cyan at 11:28 PM (563 Views / 0 Likes) 0 replies

  1. Cyan
    OP

    Global Moderator Cyan GBATemp's lurking knight

    Joined:
    Oct 27, 2002
    Messages:
    16,433
    Location:
    Engine room, learning
    Country:
    France
    I made a forum, and created the script to add smiley, bold, italic, etc.
    http://asf.mangaheart.org (I borrowed the icons for the test)

    I created the script in order to add the element at the current cursor position, but when the textarea is greater and the scrollbar appear, the scrollbar position go back to top.
    I would like the scrollbar to stay at the same position like on gbatemp, or like when previewing the Wiki.


    Maybe it's related to the way I made my script ?
    data = textarea content
    position = current cursor position in data
    new textarea data = everything from start to current position + smiley + everything from cursor position to end, replacing completely the content of the textarea.

    Maybe I can insert text without replacing the textarea content ?

    Here is my script if you could check it :
    (it's currently only working on firefox, I'll try to make it compatible with everything later)


    Code:
    ÂÂÂÂinsert_text: function (bbstart,bbend)
    ÂÂÂÂ{
    ÂÂÂÂÂÂÂÂvar input = document.getElementById('message');
    ÂÂÂÂÂÂÂÂinput.focus();
    
    ÂÂÂÂÂÂÂÂif(typeof input.selectionStart != 'undefined')
    ÂÂÂÂÂÂÂÂ{
    ÂÂÂÂÂÂÂÂÂÂÂÂvar start = input.selectionStart;
    ÂÂÂÂÂÂÂÂÂÂÂÂvar end = input.selectionEnd;
    ÂÂÂÂÂÂÂÂÂÂÂÂvar sel = input.value.substring(start, end);
    ÂÂÂÂÂÂÂÂÂÂÂÂ
    ÂÂÂÂÂÂÂÂÂÂÂÂvar pos;
    ÂÂÂÂÂÂÂÂÂÂÂÂif (typeof bbend == 'undefined') // add text at position, or replace if selected
    ÂÂÂÂÂÂÂÂÂÂÂÂ{
    ÂÂÂÂÂÂÂÂÂÂÂÂÂÂÂÂinput.value = input.value.substr(0, start) + bbstart + input.value.substr(end);
    ÂÂÂÂÂÂÂÂÂÂÂÂÂÂÂÂpos = start + bbstart.length;
    ÂÂÂÂÂÂÂÂÂÂÂÂ}
    ÂÂÂÂÂÂÂÂÂÂÂÂelse // put bbstart at the beginning of the selection, and bbend at the end
    ÂÂÂÂÂÂÂÂÂÂÂÂ{
    ÂÂÂÂÂÂÂÂÂÂÂÂÂÂÂÂinput.value = input.value.substr(0, start) + bbstart + sel + bbend + input.value.substr(end);
    ÂÂÂÂÂÂÂÂÂÂÂÂÂÂÂÂpos = start + bbstart.length + sel.length + bbend.length;
    ÂÂÂÂÂÂÂÂÂÂÂÂ}
    ÂÂÂÂÂÂÂÂÂÂÂÂinput.selectionStart = pos;
    ÂÂÂÂÂÂÂÂÂÂÂÂinput.selectionEnd = pos;
    ÂÂÂÂÂÂÂÂ}
    ÂÂÂÂ},
    message is the textarea ID in the webpage.

    insert_text([ b],[ /b])
    if a text is selected, it returns [ b]text[ /b]
    if no text is selected, it returns [ b][ /b]

    bbend is optional :
    insert_text(smiley) returns the smiley at the current position, or replace the selection.
     

Share This Page