1/** 2 * Scroll a textarea to a given line 3 * 4 * 5 * Based upon: 6 * * http://stackoverflow.com/questions/5458655/jquery-scroll-textarea-to-given-position (question and answer) 7 * * http://wiki.sheep.art.pl/Textarea%20Scrolling 8 * * https://github.com/splitbrain/dokuwiki/blob/9ae98fa5862ce523ff8d8f97bd249bc67313dbbc/lib/scripts/edit.js#L385 9 * by @splitbrain 10 * * The jQuery plugin-template of @JayDeeDee 11 */ 12 13(function($) { 14 'use strict'; 15 16 $.fn.scrollToLine = function (linenumber) { 17 18 return this.each(function() { 19 20 var $this = $(this); 21 try{ 22 // getting given textarea contents 23 var text = $this.text().split("\n").slice(0,linenumber).join('<br>'); 24 25 // creating a DIV that is an exact copy of textarea 26 var $copyDiv = $('<div></div>') 27 .append(text) // making newlines look the same 28 .css('width', $this.width() + 'px') // width with scrollbar, but close enough 29 .css('font-size', $this.css('font-size')) 30 .css('font-family', $this.css('font-family')) 31 .css('padding', $this.css('padding')) 32 .css('line-height', $this.css('line-height')); 33 // inserting new div at the end of the document 34 $copyDiv.appendTo('body'); 35 // The height of the new element is close to the position of the line in the textarea 36 var pos = $copyDiv[0].scrollHeight; 37 // now, we know where to scroll! 38 $this.scrollTop(pos); 39 // no need for DIV anymore 40 $copyDiv.remove(); 41 42 }catch(err){ 43 console.dir(err); 44 } 45 }); 46 47 }; 48 49})(jQuery); 50