WordPress Code Snippets

A fresh mix of code snippets and tutorials

jQuery Auto Resize Multiple Textareas

269

The User Notes Widget that’s included in my Dashboard Widgets Suite plugin enables users to edit notes right on the WP Dashboard. To make things extra awesome, each note automatically expands as the user types more lines of text. This post explains how I achieved this trick, aka multiple auto-resize textareas.

HTML/PHP

Let’s say that you’re generating a series of HTML textareas via PHP loop. Along with each textarea, include a hidden input field like so:

<textarea name="dws-notes-user[note]" class="dws-note-id-<?php echo $key; ?>" rows="3" data-min-rows="3"></textarea>
<input name="dws-notes-user[count]" type="hidden" value="<?php echo intval($key); ?>">

Note that $key is an index marker as would be generated via foreach() loop (e.g., $key => $value). So when included in a foreach() or while() loop, this code would generate multiple pairs of textarea/input fields, as many as desired.

jQuery

Once the page includes multiple pairs of the textarea/input fields, we can finish the technique with the following slab of jQuery:

$('input[name="dws-notes-user[count]"]').each(function(index, value) {
	
	window.$dws_note_ids = { note_id: '.dws-note-id-'+ index };
	
	var note_id = window.$dws_note_ids.note_id;
	
	jQuery(document).one('focus.textarea', note_id, function() {
		
		var savedValue = this.value;
		this.value = '';
		this.baseScrollHeight = this.scrollHeight;
		this.value = savedValue;
		
	}).on('input.textarea', note_id, function() {
		
		var minRows = this.getAttribute('data-min-rows') | 0, rows;
		this.rows = minRows;
		
		// console.log(this.scrollHeight, this.baseScrollHeight);
		
		rows = Math.ceil((this.scrollHeight - this.baseScrollHeight) / 17);
		this.rows = minRows + rows;
		
	});
	
});

That’s the magic right there. This snippet loops through the hidden inputs and resizes each associated textarea as the user types. To see this snippet in action, check out the User Notes Widget in my plugin, Dashboard Widgets Suite.

CSS (Optional)

Once you get the auto-resize height functionality dialed in, you may want to customize the display of the multiple textareas. Here is some CSS to get you going in the right direction.

form textarea {
	width: 100%; min-height: 50px; box-sizing: border-box; margin: 3px 0; padding: 5px; 
	overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; overflow: hidden;
	}

Here, the overflow:hidden removes the vertical scrollbar, so remove that property if vertical scrollbars are desired. Obviously there are many factors to consider when working with multiple auto-resizing textareas, so you’ll want to experiment and customize as needed. The technique provided in this tutorial should give you a good starting point for further development and fine-tuning.


Show Support

Like our new Facebook Page to show support!