简体   繁体   中英

Show newly printed text in textarea in javascript/jQuery

I am working on a project where a web application is printing information to a textarea that is acting like a console.

For simplicities sake, it is declared like this:

<textarea id = "console" readonly></textarea>

I have a function that prints new text to this window when the web application calls it:

function printToConsole(text) {
    $('#console').val($('#console').val() + text);
    // INSERT NEW CODE HERE
}

Currently this function prints to the console just fine, but I have to scroll down every time to see the new information coming back. There has to be some way of using focus, etc to have it automatically scroll to the bottom.

You can use scrollTop() method like following.

 function printToConsole(text) { var newVal = $('#console').val() + text; $('#console').focus().val('').val(newVal); //to focus at the end of text $('#console').scrollTop($('#console')[0].scrollHeight); } var i=0; $('button').click(function(){ printToConsole('Add text '+(++i)+'\\n'); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea id = "console" style="height: 70px;" readonly></textarea> <button>Click</button> 

 function printToConsole(text) { let $console = $("#console"); $console.val($console.val() + text); $console.prop("scrollTop", $console.prop("scrollHeight")); } printToConsole(` print to console print to console print to console print to console this is the line that shows`); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea id = "console" readonly></textarea> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM