Resize text area to fit all text on load jquery - javascript

I understand there has been a lot of discussion on this but I have yet to find a solution to fix my needs. Basically I need to autogrow a text area not when you type but on load. I am pulling in content from a database and dependant on the user's settings an overlay is produced over the text area, but upon doing this the text areas are not scrollable therefore I need to autosize these to show all the text.
I have tried scrollHeight but this is not working great as there are multiple text boxes on the screen
Thanks

Try this
$("textarea").height( $("textarea")[0].scrollHeight );
DEMO
UPDATE
As a hack to make it work in older IE-s just add a really short delay before executing it
window.setTimeout( function() {
$("textarea").height( $("textarea")[0].scrollHeight );
}, 1);​
DEMO
UPDATE FOR MULTIPLE TEXTAREAS
$("textarea").each(function(textarea) {
$(this).height( $(this)[0].scrollHeight );
});

This worked for me; it loops through all "textarea" elements on page Ready, and set their height.
$(function () {
$("textarea").each(function () {
this.style.height = (this.scrollHeight+10)+'px';
});
});
You can also combine it with an auto-expand function, to make it fully dynamic while writing as well:
function autoresize(textarea) {
textarea.style.height = '0px'; //Reset height, so that it not only grows but also shrinks
textarea.style.height = (textarea.scrollHeight+10) + 'px'; //Set new height
}
and call that from an "keyup" event or through jQuery:
$('.autosize').keyup(function () {
autoresize(this);
});
Note how I am adding 10px to the scroll height: here you can adjust the amount of space you would like the bottom of the text area to give the user.
Hope that helps someone. :)
Edit: Changed answer according to #Mariannes comment.

you can use this. It works for me.
$('#content').on('change keyup keydown paste cut', 'textarea', function () {
$(this).height(0).height(this.scrollHeight);
}).find('textarea').change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="content">
<textarea>How about it</textarea><br />
<textarea>111111
222222
333333
444444
555555
666666</textarea>
</div>

You mentioned there are multiple textboxes. This code will set the height of each textarea according to its own contents.
$(document).ready( function( ) {
$("textarea").each( function( i, el ) {
$(el).height( el.scrollHeight );
​});
});
Fiddle here

Alternatively, you could use an editable div in HTML 5.
Reference : http://www.w3.org/TR/2011/WD-html5-20110525/editing.html#contenteditable

This is an workaround.. and maybe an alternative solution:
$('textarea').each(function(){
var height = $('<div style="display:none; white-space:pre" id="my-hidden-div"></div>')
.html($(this).val())
.appendTo('body')
.height();
$(this).css('height',height + 'px');
$('#my-hidden-div').remove();
});
You can see a demo here http://jsfiddle.net/gZ2cC/

The solution of Tormod Haugene worked for me.
But my textareas where in an accordion and apparently it only worked if the textarea was visible on page load. The accordion items are triggered by clicking on elements with the class "title".
So I adapted the code Tormod Haugene to work inside accordion contents, that are set to display: none on page load.
Maybe this is useful for someone else in this situation:
jQuery(document).on('click', '.title', function () {
jQuery("textarea").each(function () {
this.style.height = (this.scrollHeight+10)+'px';
});
});

Related

removing the height attribute when binding to resize

I have done a navigation which goes the full document when mobile view which is done using jquery.
I am trying to cancel the height to be back to auto or just remove the style attribute which was given from the previous jquery.
But for some reason it does not work, I have tried a few things but it simply does not work.
Can you not cancel the style attribute if it is given through jquery?
Here is navigation which opens and closes the navigation in mobile view:
// Mobile Navigation Area
jQuery('.menu-icon-mobile').on('click',function(event){
event.preventDefault();
var currentId = jQuery(this).attr('id');
var mobileHeight = jQuery(document).height();
switch (currentId){
case 'mobile-nav-open':{
jQuery('.navigation').animate({height: mobileHeight + "px"}, 400 );
jQuery(this).attr('id','mobile-nav-close');
}
break;
case 'mobile-nav-close':{
jQuery('.navigation').animate({height: "0px"}, 400 );
jQuery(this).attr('id','mobile-nav-open');
}
break;
}
});
Here is the resize code, ive added the alert to show that its binded and it is :(
//checking if the screen is resized and if it is and the screen is less that 768px wide then cancel the attributes
jQuery(window).resize(function(){
var thescreen = jQuery(window).width();
if(thescreen > 768){
jQuery('.navigaiton').removeAttr('style');
}
alert(thescreen);
});
For what I can see this should work, the only thing I can think of is that the style attribute is not there in real life as its done using jquery so it cant see the style attribute to remove it.
Any idea how to remove the attribute once given?
Here is the jsfiddle link:
http://jsfiddle.net/robertg/kn1scc2f/2/
Thanks
You misspelled your selector.
Change:
jQuery('.navigaiton')
To:
jQuery('.navigation')
You can remove any css attribute completely from the markup using the code below
$('your-selector').css('height', '');
Updated fiddle - http://jsfiddle.net/Aerious/6h30eL8q/

Increase Div height when checkmark is checked

I currently have a fadein/out of a hidden div when a checkmark is checked. I would like to also increase the appropriate div height as well and then remove the same height after the check mark is unchecked. This some snippets of my current code:
<script type="text/javascript">
$('.checkTax').change(function() {
if ($(this).attr("checked")) {
$('.prorateTax').fadeIn();
return;
}
$('.prorateTax').fadeOut();
});
</script>
The div whos height needs to be adjusted is: .article.prorate . I've tried a few suggestions online and so far nothing is working. If other information is needed to provide a adequate response please let me know.
Edit:
After the various answers I modified the code according to a couple of suggestions and ended up with (which worked perfectly):
<script type="text/javascript">
$('.checkTax').change(function() {
if ($(this).attr("checked")) {
$('.prorateTax').fadeIn();
$('article.prorate').css( "height", "+=100px" );
}
else
{
$('.prorateTax').fadeOut();
$('article.prorate').css( "height", "-=100px" );
}
});
</script>
I appreciate everyones help and if I could select more than one green checkmark, I would. Several suggestions given would have worked. I cannot also upvote/downvote as I do not have enough reputation.
To increase height by getting current height of the element you can do this way:
$(selector).css( "height", "+=20px" );
$(selector).height( $(selector).height() + 20 );
You can also use the more simpler jQuery method .height();
<script type="text/javascript">
$('.checkTax').change(function() {
if ($(this).attr("checked")) {
$('.prorateTax').fadeIn().height(20);
return;
}
$('.prorateTax').fadeOut().height(0);
});
I see You are using jQuery . For manipulating height use :
$('selector').css('height', your_value);

.hover not working when used with .html

I am trying to do a simple image rollover with jQuery, but this code is not working:
HTML:
<div class="secondcircle" id="circleone">
<p>
<img src="/../ex/img/group1.png">
</p>
</div>
JS:
$("#circleone").hover(
function () {
$(this).html("<p><img src=\"/../ex/img/group2.png\"></p>");
},
function () {
$(this).html("<p><img src=\"/../ex/img/group1.png\"></p>");
}
);
The mouse enter event fires just fine, but none happens when the mouse leaves.
Moreover, the code works fine with simpler actions - the example in the jQuery docs of appending a span then removing it works just fine.
Why would the html not be working? I've been stuck on this for ages.
Update: Nearly every answer/comment suggests just replacing the image source, and while this works perfectly (thanks!) sometimes I do need to change the HTML (such as to change text). This was just one example. Sorry, I should have better specified that in the question.
Instead of replacing your entire HTML is is a better idea to just change the source of the image.
$("#circleone").hover(function () {
$(this).find('img').attr("src","/../ex/img/group2.png\");
},
function () {
$(this).find('img').attr("src","/../ex/img/group1.png\");
}
);
It works if you adjust it so it just replaces the img, like this:
http://jsfiddle.net/7etUU/
I think the main issue is your div being a block element that spans 100% of the width, then the contents get replaced on hover which removes the content, so it flashes.
Why not do this with CSS?
#circleone {
background-image:url('FirstImageURL');
}
circleone:hover{
background-image:url('SecondImageURL');
}
Totally stole this from this question.
I think your div is taking 100% width. Try adding a "float:left" CSS property. Like this...
.secondcircle{
float : left;
}
I noticed something weird when testing this. His original method does not work until I added a border around the parent div, then it works just fine.
Anyone know why that might be?
jsFiddle
/*UNCOMMENT ME AND I WILL WORK
#circleone
{
border: 1px solid #000;
}*/
You do not need to replace the whole HTML with hover event. If your goal is to change the image on hover, use the attr method instead http://api.jquery.com/attr/:
HTML
<div class="secondcircle" id="circleone">
<p>
<img id="img1" src="http://softwarebyrob.wpengine.netdna-cdn.com/images/football.jpg" />
</p>
</div>
jQuery
$("#circleone").hover(
function () {
$("#img1").attr({ 'src': 'http://softwarebyrob.wpengine.netdna-cdn.com/images/programming.jpg', 'alt':'MyAlt1' });
},
function () {
$("#img1").attr({ 'src': 'http://softwarebyrob.wpengine.netdna-cdn.com/images/football.jpg', 'alt':'MyAlt2' });
}
);
Working JsFiddle here: http://jsfiddle.net/TBMxm/1/
Also, this is better from performance and best practice point of view.
Update1
jQuery Code if you want to use HTML method:
var originalContent = $('#circleone p').html();
$("#circleone").hover(
function () {
$('#circleone p').html('<img src="http://softwarebyrob.wpengine.netdna-cdn.com/images/programming.jpg"/>');
},
function () {
$('#circleone p').html(originalContent);
}
);
Working sample using HTML: http://jsfiddle.net/TBMxm/3/

Adjusting height of scrolling div

I am combining two scripts together: a scroller and a content fader. When I swap the content (fading), div's with a lot of content make the scrolling div super long. I was reading on the plugin demo for content scrolling (http://manos.malihu.gr/jquery-custom-content-scroller) that you can use $(selector).mCustomScrollbar("update"); when loading different content to make the div adjust accordingly.
I know that code needs to go in my fading script somewhere, but where? Here is the fading script, where would it go?
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
(function($) {
$.fn.Fader = function() {
this.each(function() {
$('.clickme').bind('click', function(e) {
e.preventDefault();
$( "#mediaswap div" ).fadeOut();
$( "#mediaswap div" + $(this).attr('name') ).fadeIn();
})
});
}
})(jQuery);
$(function() {
$('#mediaswap').Fader();
});
});//]]>
</script>
I've answered your comment on the post but I'm writing it here too.
Since you fade in/out divs, you have to call the update method as a callback to the .fadeIn() function, so it updates the scrollbar after the animation is completed:
$( "#mediaswap div" + $(this).attr('name') ).fadeIn(function(){
$(this).mCustomScrollbar("update");
});
Additionally, there's an extra option parameter you can use when you initially call the plugin, that checks content size and updates the scrollbar automatically if it changes:
$("#mediaswap div").mCustomScrollbar({
advanced:{ updateOnContentResize:true }
});
Using the updateOnContentResize option, depends on the rest of your code (where you call the plugin), so I recommend using the first method.
I recommend checking the div to see if it's animated using something like this:
var wait = setInterval(function() {
if( !$("#mediaswap div").is(":animated"))
{
clearInterval(wait);
//put the code in here because it checks
for whether the DIV is currently animated.
}
}, 200);
You can change the interval if it takes the animation longer to complete the animation.

How to have a textarea to keep scrolled to the bottom when updated

My problem is a bit off the cuff here, so I'll try to explain this best I can.
I have a text area, having css of #object{overflow:hidden;resize:none;}. I am trying to prevent it from spawning scroll bar while also resizing itself. This textarea is synced with an external script's console meaning it updates. By default however, it will stay at the top unless you highlight text, dragging off to the bottom of the element. This would be the only way to scroll down other than with arrow keys, naturally.
Programmatically, is there any way to keep the text area down to the bottom upon updating? It would be nice to have it auto-scroll to accommodate its use case.
You can do it by javascript. Set the scrollTop property of text area with scrollHeight property like below:
document.getElementById("textarea").scrollTop = document.getElementById("textarea").scrollHeight
By using jQuery, you can find out when the content of the textarea changes using:
$("#object").change(function() {
scrollToBottom();
});
And scroll to the bottom using:
function scrollToBottom() {
$('#object').scrollTop($('#object')[0].scrollHeight);
}
Scroll code taken from jquerybyexample.blogspot.com.
Using Javascript
var textarea = document.getElementById('textarea_id');
textarea.scrollTop = textarea.scrollHeight;
Using Jquery
$('#textarea_id').scrollTop($('#textarea_id')[0].scrollHeight);​​​
Generic JQuery Plugin
Here a generic jquery plugin for scrollBottom of any element:
$.fn.scrollBottom = function() {
return $(this).scrollTop($(this)[0].scrollHeight);
};
usage:
$("#logfile").val( $("#logfile").val() + "this is new line test\n" ).scrollBottom();
function checkTextareaHeight(){
var textarea = document.getElementById("yourTextArea");
if(textarea.selectionStart == textarea.selectionEnd) {
textarea.scrollTop = textarea.scrollHeight;
}
}
Call this function every time when the contents of the textarea are changed. If you cannot edit the external influence, periodically activate this function using setInterval.

Categories

Resources