Posts Tagged ‘Javascript’

Creating a Twitter style character counter with jQuery

Thursday, April 22nd, 2010

I’m not really sure why I decided to write the javascript to handle a text area with a limited character count as well as a character counter like that used on Twitter. Reason or not, it turned out to be fairly simple to pull off. By far the hardest part was finding a way to only run the onkeyup event when the appropriate text area field was focused. The idea being that every time the user presses a key typing in their name there isn’t a bunch of javascript running unnecessarily in the background. Somewhere on the web I found an activeElement javascript method that returns the focused form element. Just a fair warning that I’ve never used this outside of this example and have no idea if it works in IE or not. I did check though in Chrome, Firefox, and Safari however.

I came up with two scenarios for using a limited character text area with a character counter. First is a text area that allows x number of characters. The counter counts up to this number and then increases no more. The string itself is trimmed to the max character on each keypress beyond the max characters allowed. Second is a text area much truer to the Twitter ‘What’s Happening’ text area. This text area will allow the user to type as much as they wish, while the counter begins at the max and counts down to 0. At zero the counter begins counting down through negative numbers. I’ve also added a class at this point that changes the color of negative numbers to red.

Let’s take a look at some code.

The HTML

<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<title>Character Counter</title>

		<!-- JQUERY LINK -->
		<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script>

		<!-- CHARACTER COUNTER JS FILE -->
		<script src="js/character_counter.js" type="text/javascript"></script>
	</head>

	<body>
		<form name="text_input" method="post" action="#">
			<textarea name="my_text" id="my_text" cols="50" rows="10"></textarea>
		</form>

		Characters: <em><span id="counter"></span></em>
	</body>
</html>

Pretty simple stuff we have here. First is a link to the jQuery library hosted by Google. Next is a link to the character_counter.js file that I will get into next. As far as HTML is concerned we have a text area with an id of ‘my_text’ and a span with an id of ‘counter’. The span is empty because it will serve as a container for us to dynamically insert the character count as the user types into the text area.

I will list first the javascript that counts up to the max number of characters and then trims the string to the max character count so that the user can literally on enter the allowed number of characters. Afterwards, I will show the code that will allow the user to type as much as they wish and count into negative numbers.

character_counter.js (Counts up with character limit)

$(document).ready(function()
{
	var max_length = 10;

	//run listen key press
	whenkeydown(max_length);
});

whenkeydown = function(max_length)
{
	$("#my_text").unbind().keyup(function()
	{
		//check if the appropriate text area is being typed into
		if(document.activeElement.id === "my_text")
		{
			//get the data in the field
			var text = $(this).val();

			//set number of characters
			var numofchars = text.length;

			if(numofchars <= max_length)
			{
				//set the length of the text into the counter span
				$("#counter").html("").html(text.length);
			}
			else
			{
				//make sure string gets trimmed to max character length
				$(this).val(text.substring(0, max_length));
			}
		}
	});
}

character_counter.js (Counts down without a character limit)

$(document).ready(function()
{
	//set max length
	var max_length = 10;

	//load in max characters when page loads
	$("#counter").html(max_length);

	//run listen key press
	whenkeydown(max_length);
});

whenkeydown = function(max_length)
{
	$("#my_text").unbind().keyup(function()
	{
		//check if the appropriate text area is being typed into
		if(document.activeElement.id === "my_text")
		{
			//get the data in the field
			var text = $(this).val();

			//set number of characters
			var numofchars = text.length;

			//set the chars left
			var chars_left = max_length - numofchars;

			//check if we are still within our maximum number of characters or not
			if(numofchars <= max_length)
			{
				//set the length of the text into the counter span
				$("#counter").html("").html(chars_left).css("color", "#000000");
			}
			else
			{
				//style numbers in red
				$("#counter").html("").html(chars_left).css("color", "#FF0000");
			}
		}
	});
}

Gist of both is that we need to set a max character count for the text area and then listen for the keyup event to fire. When this happens we then check if the text area with the id of ‘my_text’ is focused. If not there is no need to continue running code. If so we get the value of the text area and get the length which is the number of characters. If we are increasing our counter by one we just need to use jQuery to write to the span tag the current length of the value of the text area. If counting down we do the opposite. We subtract the length of the value of the text area from the max number of characters allowed. Next, if we are trimming the string so that it can never actually get longer than the number of allowed characters we check if the length has exceeded the max characters. If so we use the ’subString()’ method to make sure that the value is trimmed off each time the user tries to add a character. If running the counter into negative numbers we don’t really need to run any conditionals unless changing the color so that negative numbers show up different than positive numbers. In this case I just check if the length of the value exceeds the max length. If so I use the jQuery css() method to change the color of the text to red.

That’s really it. Not pretty, but functional and simple.

Creating a simple sliding navigation with jQuery

Friday, October 30th, 2009

As we know, jQuery not only makes things once considered impossible on the web possible, but makes those things pretty easy to do. I just built a sliding navigation for pukkared.com portfolio and thought I’d share here. Pulling this off requires both CSS and javascript knowledge. I’ll do my best to explain the CSS involved, but maybe Adri can follow up on this post with some more detail on why it works. I’ll also note that practically this navigation would be dynamically driven, but for the sake of simplicity I’m going to hard code the navigation. Maybe I’ll follow this up with a post on outputting your navigation from your database.

(more…)

Setting form field focus inside a cfwindow

Friday, October 23rd, 2009

Coldfusion makes creating a virtual window very easy.  A source file can be attached to the window so that when the window loads it loads the contents of a separate file.  So for  example, on your main page you can create a window by inserting the following.

Basic cfwindow:

<cfwindow name=“myWindow” initshow=“true”>

Content inside of window

</cfwindow>

(more…)