Click here to Skip to main content
15,867,453 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a code for adding line numbers inside textarea using javascript and also have a code for highlighting text in textarea using jquery.

Adding line numbers javascript code- Has 2 div,1st div is behind textarea and 2nd div is for line numbers.

Highlighting text using jquery code - Has 3 div.

I want to combine these two features(highlighting text and adding line numbers)inside textarea.I tried a lot using these two codes but none of them worked.I had a problem with these div's. I have pasted below javascript and jquery code. Can anybody pls help me to how to combine these two functions.

C#
var lineObjOffsetTop = 2;

   function createTextAreaWithLines(id)
   {
      var el = document.createElement('DIV');
      var ta = document.getElementById(id);
      ta.parentNode.insertBefore(el,ta);
      el.appendChild(ta);

      el.className='textAreaWithLines';
      el.style.width ='50%';
      ta.style.position = 'absolute';
      ta.style.left = '30px';
      el.style.height = '91%';
      el.style.overflow='hidden';
      el.style.float='left';
      el.style.position = 'relative';
      var lineObj = document.createElement('DIV');
      lineObj.style.position = 'absolute';
      lineObj.style.top = lineObjOffsetTop + 'px';
      lineObj.style.left = '0px';
      lineObj.style.width = '27px';
      el.insertBefore(lineObj,ta);
      lineObj.style.textAlign = 'right';
      lineObj.className='lineObj';
      var string = '';
      for(var no=1;no<10000;no++){
         if(string.length>0)string = string + '<br>';
         string = string + no;
      }

      ta.onkeydown = function() { positionLineObj(lineObj,ta); };
      ta.onmousedown = function() { positionLineObj(lineObj,ta); };
      ta.onscroll = function() { positionLineObj(lineObj,ta); };
      ta.onblur = function() { positionLineObj(lineObj,ta); };
      ta.onfocus = function() { positionLineObj(lineObj,ta); };
      ta.onmouseover = function() { positionLineObj(lineObj,ta); };
      lineObj.innerHTML = string;

   }

   function positionLineObj(obj,ta)
   {
      obj.style.top = (ta.scrollTop * -1 + lineObjOffsetTop) + 'px';

</script>


CSS
<style>
.textAreaWithLines{
      font-family:courier;
      border:1px solid grey;

   }
   .textAreaWithLines textarea,.textAreaWithLines div{
      border:0px;
      line-height:120%;
      font-size:12px;

   }
   .lineObj{
      color:blue;
   }
</style>
//end of adding line numbers inside textarea



jquery code(highlighting text)


script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
    
    <script type="text/javascript">
        $(function() {
            // let's init the plugin, that we called "highlight".
            // We will highlight the words "hello" and "world", 
            // and set the input area to a widht and height of 500 and 250 respectively.
                        $("#container1").highlight({
                words: [["(\\\\)(.+?)(\\})","$1$2$3"]],
                width:  500,
                height: 125,
        count: 1
            });
        });

        // the plugin that would do the trick
        (function($){
            $.fn.extend({
                highlight: function() {
                    // the main class
                    var pluginClass = function() {};
                    // init the class
                    // Bootloader
                    pluginClass.prototype.__init = function (element) {
                        try {
                            this.element = element;
                        } catch (err) {
                            this.error(err);
                        }
                    };
                    // centralized error handler
                    pluginClass.prototype.error = function (e) {
                        // manage error and exceptions here
                        //console.info("error!",e);
                    };
                    // Centralized routing function
                    pluginClass.prototype.execute = function (fn, options) {
                        try {
                            options = $.extend({},options);
                            if (typeof(this[fn]) == "function") {
                                var output = this[fn].apply(this, [options]);
                            } else {
                                this.error("undefined_function");
                            }
                        } catch (err) {
                            this.error(err);
                        }
                    };
                    // **********************
                    // Plugin Class starts here
                    // **********************
                    // init the component
                    pluginClass.prototype.init = function (options) {
                        try {
                            // the element's reference ( $("#container") ) is stored into "this.element"
                            var scope                   = this;
                            this.options                = options;

                            // just find the different elements we'll need

                            this.highlighterContainer   = this.element.find('#highlighterContainer'+this.options.count);
                            this.inputContainer         = this.element.find('#inputContainer'+this.options.count);
                            this.textarea               = this.inputContainer.find('#text');
                            this.highlighter            = this.highlighterContainer.find('#highlighter'+this.options.count);

                            // apply the css
                            this.element.css({'position':'relative',
                'overflow':'auto',
                'background':'none repeat scroll 0 0 #FFFFFF',
                'height':this.options.height+2,
                'width':this.options.width+19,
                'border':'1px solid'
                });

                            // place both the highlight container and the textarea container
                            // on the same coordonate to superpose them.
                            this.highlighterContainer.css({
                                'position':         'absolute',
                                'left':             '0',
                                'top':              '0',
                                'border':           '1px dashed #ff0000', 
                                'width':            this.options.width,
                                'height':           this.options.height,
                                'cursor':           'text',
                'z-index':      '1'
                            });
                            this.inputContainer.css({
                                'position':         'absolute',
                                'left':             '0',
                                'top':              '0',
                                'border':           '0px solid #000000',
                'z-index':      '2',
                'background':   'none repeat scroll 0 0 transparent'
                            });
                            // now let's make sure the highlit div and the textarea will superpose,
                            // by applying the same font size and stuffs.
                            // the highlighter must have a white text so it will be invisible
            var isWebKit = navigator.userAgent.indexOf("WebKit") > -1,
            isOpera = navigator.userAgent.indexOf("Opera") > -1,
isIE /*@cc_on = true @*/,
isIE6 = isIE && !window.XMLHttpRequest; // Despite the variable name, this means if IE lower than v7

if (isIE || isOpera){
var padding = '6px 5px';
}
else {
var padding = '5px 6px';
}
                           this.highlighter.css({
                                'padding':      padding,
                                'color':            '#eeeeee',
                                'background-color': '#ffffff',
                                'margin':           '0px',
                                'font-size':        '11px' ,
                                'line-height':      '12px' ,
                                'font-family':      '"lucida grande",tahoma,verdana,arial,sans-serif'
                            });

                            // the textarea must have a transparent background so we can see the highlight div behind it
                            this.textarea.css({
                                'background-color': 'transparent',
                                'padding':          '5px',
                                'margin':           '0px',
                                'width':            this.options.width,
                                'height':           this.options.height,
                                'font-size':        '11px',
                                'line-height':      '12px' ,
                                'font-family':      '"lucida grande",tahoma,verdana,arial,sans-serif',
                'overflow':     'auto',
                                'border':           '0px solid #000000'
                            });

                            // apply the hooks
                            this.highlighterContainer.bind('click', function() {
                                scope.textarea.focus();
                            });
                            this.textarea.bind('keyup', function() {
                                // when we type in the textarea, 
                                // we want the text to be processed and re-injected into the div behind it.
                                scope.applyText($(this).val());
                            });

            scope.applyText(this.textarea.val());

                        } catch (err) {
            this.error(err)
                        }
                        return true;
                    };
                    pluginClass.prototype.applyText = function (text) {
                        try {
                            var scope                   = this;

                            // parse the text:
                            // replace all the line braks by <br/>, and all the double spaces by the html version &nbsp;
                            text = this.replaceAll(text,'\n','<br/>');
                            text = this.replaceAll(text,'  ','&nbsp;&nbsp;');
                            text = this.replaceAll(text,' ','&nbsp;');

                            // replace the words by a highlighted version of the words
                            for (var i=0;i<this.options.words.length;i++) {
                                text = this.replaceAll(text,this.options.words[i][0],'<span style="background-color:lightblue;">'+this.options.words[i][1]+'</span>');
                                //text = this.replaceAll(text,'(\\[b])(.+?)(\\[/b])','<span style="font-weight:bold;background-color: #D8DFEA;">$1$2$3</span>');
                            }

                            // re-inject the processed text into the div
                            this.highlighter.html(text);
            if (this.highlighter[0].clientHeight > this.options.height) {
                // document.getElementById("highlighter0")
                this.textarea[0].style.height=this.highlighter[0].clientHeight +19+"px";
            }
            else {
                this.textarea[0].style.height=this.options.height;
            }

                        } catch (err) {
                            this.error(err);
                        }
                        return true;
                    };
                    // "replace all" function
                    pluginClass.prototype.replaceAll = function(txt, replace, with_this) {
                        return txt.replace(new RegExp(replace, 'g'),with_this);
                    }

                    // don't worry about this part, it's just the required code for the plugin to hadle the methods and stuffs. Not relevant here.
                    //**********************
                    // process
                    var fn;
                    var options;
                    if (arguments.length == 0) {
                        fn = "init";
                        options = {};
                    } else if (arguments.length == 1 && typeof(arguments[0]) == 'object') {
                        fn = "init";
                        options = $.extend({},arguments[0]);
                    } else {
                        fn = arguments[0];
                        options = $.extend({},arguments[1]);
                    }

                    $.each(this, function(idx, item) {
                        // if the component is not yet existing, create it.
                        if ($(item).data('highlightPlugin') == null) {
                            $(item).data('highlightPlugin', new pluginClass());
                            $(item).data('highlightPlugin').__init($(item));
                        }
                        $(item).data('highlightPlugin').execute(fn, options);
                    });
                    return this;
                }
            });

        })(jQuery);


XML
<body>


    <div id="container1">
        <div id="highlighterContainer1">
            <div id="highlighter1"></div>
        </div>
        <div id="inputContainer1">
            <textarea id='text' rows=30 cols=30 ></textarea>
        </div>
    </div>

<script>createtext('text')</script>
Posted

1 solution

Are you doing this for the fun of it? Or do you really need it?
If so take a look at CodeMirror. This has everything you need..
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900