Posts Tagged ‘jQuery’

Loading resizable fonts dynamically based on window size

Monday, June 6th, 2011

A reader asked concerning a post I wrote a while back on Resizing text with jQuery and window resize:

Can the text resize adapt to the window size when the page is loaded and also change when the window gets resized?

Essentially, in my previous post I had hard-coded a font size in the CSS of 30px. It would then resize as the window was resized horizontally. But no matter what size the window was when the page was loaded the text was always set to 30px. So I’ve wrote up a simple code sample below in jQuery illustrating how to set the font-size in a div based on the size of the window that the site is loaded in. The original code was fairly easy to refactor to accomplish this. Essentially I added the following function

getOriginalFontSize = function()
{
	var windowWidth = $(window).width();

	var thisFontSize = windowWidth / 50;

	return thisFontSize;
}

and changed the line

var originalFontSize = 30;

to

var originalFontSize = getOriginalFontSize();

So the final block of javascript looks like

(more…)

Filtering DOM elements with jQuery

Thursday, December 30th, 2010

A few days back I was asked to build a scrolling div full of checkboxes populated via a database query record set that could be filtered. To accomplish this, I’ve often used AJAX in the past to hit a CF component that would run a SELECT statement containing a WHERE clause that looked for a record LIKE my existing value. This would return back the filtered item.

In this case however, I was working with a very large dataset and it was not appropriate to make an AJAX call to filter the dataset, and much less to do so on each key press to simulate live filtering. So I decided to filter on the client side and leave CF and AJAX out of the equation all-together. Naturally, I open the jQuery docs and start looking for something along the lines of a regular expression. As usual jQuery makes things even simpler than I could have imagined.

The jQuery selectors page shows multiple ways of selecting elements. One way is to use the ‘contains’ selector that essentially looks at the value of an attribute and checks if the substring exists in any of the available values. Once we know which elements are like and not like the substring (a.k.a. the filter criteria) we can use the jQuery show() and hide() functions to perform the filter visually for the user.

Let’s look at an example.

(more…)

Resizing text with jQuery and window resize

Friday, October 8th, 2010

The other night my wife brought up the question of being able to resize font dynamically as a user resizes their browser window. Knowing that javascript can do most anything and jQuery makes doing most anything with javascript quick, I immediately responsed – yes, of course. At the time I had an idea of how it could be accomplished, and had never attempted it nor thought about it. So I wrote up a quick example of one way to pull this off.

**A programmers note to designers: This can probably be done with CSS3, and maybe previous versions, and if you can do it with CSS I would definitely recommend it as it will certainly be a safer route and most likely a lighter route as well. I’m not known for my skill with CSS however.

Before looking at any code I’ll give a quick explanation of what it is I’m doing with the code. First, I have a fixed-width div containing a ‘p’ tag with some text. That’s it for the HTML.

The javascript assigns immediately a font-size of 30px to the text and gets the width and height of the window in its original state of page load. Also before any processing is done a ‘ratio of change’ is set. This is the number of pixel change to every one change in pixel font size. So a 10:1 ratio means that the font will decrease one pixel for every ten pixels that the window width decreases from its original size. It also works in the opposite direction for every ten pixels that the screen gets bigger than the original size the font will increase by a single pixel. Of course ten pixels means that in no time the font will be either huge or tiny. A more realistic number is something like 50 or 100. Simply put, the smaller the number the faster the font will change, and the bigger the number the slower the font will change on window resize.

First let’s look at the little bit of HTML.

<body>
	<div id="container">
		<p>
			This is some sample text that I have written for the purpose of watching it resize as I resize my window on my screen. Enjoy!
		</p>
	</div>
</body>

Now let’s take a look at the javascript.

$(document).ready(function()
{
	//set the originals
	var originalWinWidth = $(window).width();

	//set the original font size
	var originalFontSize = 30;

	//set the ratio of change for each size change
	var ratioOfChange = 50;

	//set the font size using jquery
	$("#container").css("font-size", originalFontSize);

	$(window).resize(function()
	{
		//get the width and height as the window resizes
		var winWidth = $(window).width();

		//get the difference in width
		var widthDiff = winWidth - originalWinWidth;

		//check if the window is larger or smaller than the original
		if(widthDiff > 0)
		{
			//our window is larger than the original so increase font size
			var pixelsToIncrease = Math.round(widthDiff / ratioOfChange);

			//calculate the new font size
			var newFontSize = originalFontSize + pixelsToIncrease;

			//set new font size
			$("#container").css("font-size", newFontSize);
		}
		else
		{
			//our window is smaller than the original so decrease font size
			var pixelsToDecrease = Math.round(Math.abs(widthDiff) / ratioOfChange);

			//calculate the new font size
			var newFontSize = originalFontSize - pixelsToDecrease;

			//set the new font size
			$("#container").css("font-size", newFontSize);
		}
	})
});

First of all, this is around 50 lines of code, about half of which are comments. I say this every time, but seriously hats freakin’ off for jQuery. It really is amazing how much can be accomplished with such a few pleasant lines of code. On that note I do realize that there are better ways of writing this code, and if you so choose to use it for any type of production purpose I would recommend refactoring it into something a little more encapsulated and flexible with what it resizes.

Anyways, I digress. What are we doing here. Initially we need to set up a simple listener that watches for when the user decides to resize the window. When the window changes size we need to do two things initially – get the current window size, and then compare that to the original window size. A simple comparison of that difference to zero reveals whether the window is getting bigger or smaller.

The math behind determining the amount of change for the font size is pretty elementary. We of course want to make sure we come out with a positive integer whether the window is getting bigger or smaller. To make sure we get an integer we can use javascripts Math class function round(). If the window is getting smaller we will have a negative number representing the difference. Here javascripts Math class function abs(), for ‘absolute’ can be used to make that number a positive integer. Having these tools in hand, we simply need to divide the window difference by the ratio of change. The result will be the number of pixels that the font will need to change by. If the window is getting bigger we will using jQuery’s css() function to reset the new font size to the original plus the number returned. If the window is getting smaller we, of course, subtract it from the original font size.

While I’m not sure why this would be used outside of dynamically adapting a page between window sizes for different devices, I can see a lot of ways that this can be expanded upon and made significantly better than what I have presented here. But again, I was very pleased with just how simple this was to pull off.

Animated div scrolling with jQuery

Sunday, September 26th, 2010

A problem recently presented itself as the need to use links to scroll to a given position within a scrollable div on click.  Traditionally anchor tags would have been used to allow the user to move around the page via links, but as is the case with most DOM processing jQuery can not only do it, but can pull it off very easily and much more elegantly.

The code I use here has been adapted from code originally posted by Karl Swedberg here. I’ve essentially just written it so that it is a little more flexible, as well as to once again illustrate the power and simplicity of jQuery. To see what I’m talking about in action check out an example.

To set this up we need a scrollable div with more content than its hard-coded width and height will contain. In my case I have a number of p tags with content. These will essentially be my anchor tags. Let’s first look at the html and the scrollable div html.

<div class="links">
                    <span index="0">Paragraph 1</span><br />
                    <span index="1">Paragraph 2</span><br />
                    <span index="2">Paragraph 3</span><br />
                    <span index="3">Paragraph 4</span><br />
                    <span index="4">Paragraph 5</span><br />
                    <span index="5">Paragraph 6</span><br /><br /><br />
      </div>

                <div class="container">
                    <p>
                        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas malesuada, magna ac laoreet commodo, ipsum arcu cursus diam, sit amet iaculis risus enim vitae leo. Nam condimentum nisl id ante consectetur accumsan. Pellentesque ultrices, orci vitae pellentesque scelerisque, purus ante euismod mauris, sit amet viverra felis massa ac augue. Aenean eget nisl sit amet nulla sollicitudin tincidunt. Etiam quis felis elit. Nam sem sem, semper quis cursus sit amet, egestas sodales quam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus dictum adipiscing justo ac mollis. Suspendisse interdum iaculis diam vitae pulvinar. Cras neque sapien, pulvinar ac pretium et, dictum bibendum odio. Cras et massa vel est vehicula dictum in sit amet est. Pellentesque ut commodo tellus. Pellentesque a nisl sapien. Nunc nec elit imperdiet sapien facilisis viverra a non urna. Integer ligula turpis, tincidunt in malesuada eget, rutrum a dolor. Aliquam erat volutpat. Nulla iaculis faucibus magna et pulvinar.
                    </p>

                    <p>
                        Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Mauris imperdiet neque sed dolor dignissim id rutrum dolor condimentum. Aenean et felis eros, at mattis sapien. Nam sit amet mollis nulla. Vivamus rhoncus hendrerit felis nec hendrerit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi molestie, lacus eu hendrerit egestas, augue dolor rutrum erat, eu sodales neque sapien sit amet eros. Aliquam ac tellus in tortor sollicitudin consectetur ac nec velit. Praesent libero nulla, accumsan a varius sed, aliquet ac metus. Duis sollicitudin, dui eget semper dictum, purus tortor luctus eros, vitae faucibus felis lacus eu ante. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In tempus suscipit tortor, vitae feugiat augue eleifend ut. Cras nec velit dui. Aenean eget viverra massa.
                    </p>

                    <p>
                        Cras laoreet, justo non rutrum cursus, nulla odio vulputate nibh, ut tristique dui neque ut nibh. Nunc augue purus, placerat non mattis sit amet, varius vitae magna. Vivamus cursus augue eleifend orci laoreet volutpat eu id elit. Maecenas pretium augue tortor. Curabitur elementum auctor elit, quis euismod quam hendrerit ac. Etiam quam enim, interdum non elementum at, blandit eget mauris. Nam a nisl magna. Nulla non luctus mauris. In sed tempor eros. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus eleifend porta mi, vel rhoncus orci egestas non. Duis non elit hendrerit magna ullamcorper dapibus. Vivamus et dui eget tellus tristique scelerisque at eu mauris. Proin a lectus vitae ante imperdiet auctor eget a eros.
                    </p>

                    <p>
                        Fusce pharetra porttitor dui eget adipiscing. Donec in purus a dolor lobortis blandit. Quisque quis condimentum dui. Sed nisi eros, vulputate sit amet dapibus sit amet, imperdiet non lacus. Aenean odio dui, hendrerit sit amet aliquet in, consequat sit amet orci. Sed et enim nec nulla egestas molestie vel quis tellus. Aliquam tempus, urna in auctor sodales, justo lacus laoreet enim, non tincidunt ipsum mauris sed nunc. Proin auctor vehicula malesuada. Aenean tempor mattis dignissim. Curabitur tempor faucibus libero eget cursus. Duis elementum imperdiet arcu et vestibulum. Duis in ullamcorper eros. Vivamus pellentesque nunc aliquam mi fringilla dapibus. Proin convallis lacinia cursus. Sed nisl nunc, rhoncus ut commodo a, elementum id nunc. Praesent convallis turpis ac justo congue tristique. Sed faucibus semper sem id semper. Nulla ornare commodo diam, non euismod neque dignissim et.
                    </p>

                    <p>
                        Fusce pharetra porttitor dui eget adipiscing. Donec in purus a dolor lobortis blandit. Quisque quis condimentum dui. Sed nisi eros, vulputate sit amet dapibus sit amet, imperdiet non lacus. Aenean odio dui, hendrerit sit amet aliquet in, consequat sit amet orci. Sed et enim nec nulla egestas molestie vel quis tellus. Aliquam tempus, urna in auctor sodales, justo lacus laoreet enim, non tincidunt ipsum mauris sed nunc. Proin auctor vehicula malesuada. Aenean tempor mattis dignissim. Curabitur tempor faucibus libero eget cursus. Duis elementum imperdiet arcu et vestibulum. Duis in ullamcorper eros. Vivamus pellentesque nunc aliquam mi fringilla dapibus. Proin convallis lacinia cursus. Sed nisl nunc, rhoncus ut commodo a, elementum id nunc. Praesent convallis turpis ac justo congue tristique. Sed faucibus semper sem id semper. Nulla ornare commodo diam, non euismod neque dignissim et.
                    </p>

                    <p>
                        Fusce pharetra porttitor dui eget adipiscing. Donec in purus a dolor lobortis blandit. Quisque quis condimentum dui. Sed nisi eros, vulputate sit amet dapibus sit amet, imperdiet non lacus. Aenean odio dui, hendrerit sit amet aliquet in, consequat sit amet orci. Sed et enim nec nulla egestas molestie vel quis tellus. Aliquam tempus, urna in auctor sodales, justo lacus laoreet enim, non tincidunt ipsum mauris sed nunc. Proin auctor vehicula malesuada. Aenean tempor mattis dignissim. Curabitur tempor faucibus libero eget cursus. Duis elementum imperdiet arcu et vestibulum. Duis in ullamcorper eros. Vivamus pellentesque nunc aliquam mi fringilla dapibus. Proin convallis lacinia cursus. Sed nisl nunc, rhoncus ut commodo a, elementum id nunc. Praesent convallis turpis ac justo congue tristique. Sed faucibus semper sem id semper. Nulla ornare commodo diam, non euismod neque dignissim et.
                    </p>

                </div>

CSS

<style type="text/css">
		.container {
			width: 700px;
			height: 300px;
			overflow: auto;
			border: thin;
			border-color:#CCC;
			border-style:solid;
		}

		.links {
			color: #09F;
			text-decoration: underline;
		}

		.links span {
			cursor: pointer;
		}
	</style>

Now let’s look at the jQuery code that pulls this all together.

The jQuery

$(document).ready(function()
{
	$(".links span").click(function()
	{
		var anchor_index = $(this).attr("index");

		var div_offset = getDivOffset();

		var anchor_offset = $(".container p:eq(" + anchor_index + ")").offset().top;

		scrollThis(anchor_offset, div_offset);
	});
});

getDivOffset = function()
{
	var div_offset = $(".container").offset().top;	

	return div_offset;
}

scrollThis = function(anchor_offset, div_offset)
{
	var to_scroll = anchor_offset - div_offset;

	$(".container").animate({scrollTop: '+=' + to_scroll + ''}, "slow");
}

Amazingly, in less than 50 lines jQuery pulls this off. Simply put each of the html links has an ‘index’ parameter containing the zero-based index to its corresponding paragraph in the scrollable div. Any time one of these links is clicked we get that index so we know where we are scrolling to. Next we get generally where the scroll is located within the div. Now we need the other half of the equation which is the where we need to scroll to. This value is stored in the ‘anchor_offset’ variable. Lastly, we subtract where we need to scroll to from where we are actually located. This returns the difference of which we need to move. Now use jQuery’s cool animate function with the ‘scrollTop’ option and give it a speed. That’s all it takes.

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.

Using jQuery, AJAX, and Coldfusion to filter SQL results

Sunday, March 7th, 2010

The following post will explain the logic behind the ‘live’ search results that are becoming more and more popular on the web.  The idea is that you have a record set at hand ready to be searched as a user types into an input box what they are looking for.  While in traditional software programming this has never been a huge deal, the request/response nature of the web makes our lives as web developers a little more difficult.  To bypass the request/response model we let the searching happen via the client using AJAX.

For this example three files will be needed.  The client file (the file with the filter tool and search results), a javascript file to handle the AJAX and jQuery output, and a Coldfusion component to handle the data processing.  I’ve set up a demo here to check out so you’ll know what we’ll be building.

Let’s take a look at the client file first.

jquery_result_filter.cfm

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<!--- PROXY --->
<cfajaxproxy cfc="path.to.jquery_result_filter" jsclassname="filter">

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

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

		<!-- JQUERY_RESULT_FILTER.JS -->
		<script src="js/jquery_result_filter.js" type="text/javascript"></script>
	</head>

	<body>
		Filter:
		<input type="text" name="filter" id="filter" value="" /><br /><br /><br />

		<p>Data:</p>
		<div id="output"></div>
	</body>
</html>

We have here a a proxy at the top that allows us to make asynchronous AJAX calls to the Coldfusion server. For javascript we load in the jQuery library and our javascript file that handles the AJAX calls and the data output to the DOM. In the body there is an input field which serves as our filter and an empty div which will have data loaded into it dynamically using jQuery.

Let’s take a look at our component to see how the data is being processed as the user types their filter.

(more…)

Filtering on keypress without one character delay

Sunday, February 21st, 2010

If you’re using jQuery to filter SQL data in something like a grid or live search results you may find that the search filters according to the key pressed two times back.  For example if I’m searching for the word blue in an SQL table containing a bunch of colors it may work so that when I type ‘blu’ into the search tool it returns both ‘black’ and ‘blue’.  This is because it has not filtered according to the ‘u’ that was just typed.  This can lead to pretty confusing result listings for the user.  We’re not used to being on a one character delay.

If you’re having this problem luckily it’s a very minor thing.  If you’re jQuery is performing the filter on ‘keypress’ then this is your problem.  ‘keypress’ is pretty much the same as ‘keydown’.  As a result it performs the filter query before it knows what the key press is returning.  If you have a search field with an id of ‘search’ your jQuery may look something like

$("#search").keypress(function()
{
     //do some type of filtering
});

So the search is being performed just before the new character is registered. To fix this just change ‘keypress’ to ‘keyup’. This will make sure that the search is not performed until after the new character has registered.  This way your filter will run with all of the characters in the search field.

The new jQuery would look something like the following:

$("#search").keyup(function()
{
     //do some type of filtering
});

Use CSS: Why using jQuery to add a hover class is just wrong.

Tuesday, January 19th, 2010

I don’t know a ton about CSS, but I recently found myself needing to add a hover class to a fairly complicated ajax driven application.  I fought for several hours trying to use the jQuery .addclass() method on mouseover to add a hover class I created.  While this worked great on existing elements those created via ajax took no effect.  After scrambling through the code and calling my method a dozen times I finally had something that vaguely worked.  And just when I was ready to move on I thought I would torture myself by adding the CSS ‘:hover’ class to my original hover class and see what happened.  It worked perfect.  Freakin perfect.

I was convinced that ‘:hover’ could only be applied to <a> tags.  I was wrong.  It seems that it works in Firefox, Safari, and at least the later versions of IE.  So let’s let CSS do what it does so well, which is style, and jQuery do what it does so well, which is things other than styling.

New jQuery 1.4 delay() method

Saturday, January 16th, 2010

So the new jQuery 1.4 library was released a couple days ago.  I haven’t really had a chance to check out what all it has to offer.  Looks like a lot of speed enhancements.  Speed is always great, but this is a speed increase on top of jQuery 1.3, which I thought was pretty freakin fast to begin with.

Anyways, scanning the new stuff page on their site I noticed a new delay() method.  I actually just finished a small email list application that runs on jQuery and Coldfusion that I really wished at the time I had a nice easy to implement delay method.  And what do you know, a couple days later here I am with my precious delay.

So I wrote up a quick example of using this little gem.  I’ve just created a div that animates to the right, is delayed for the amount of time specified in a text input, and then animates back to the left.  Click here to see the example.  Otherwise, let’s look at some code.

The HTML

Number of Seconds to Delay:
<input type="text" name="seconds" value="" size="3" maxlength="3" />

<p id="animate">
	Animate
</p>

<div id="animatethis"></div>

Some CSS

<!--
	#animate {
		cursor: pointer;
		color: #3543ff;
	}

	#animatethis {
		width: 100px;
		height: 100px;
		position: absolute;
		top: 200px;
		left: 100px;
		background-color: #ff7780;
	}
-->

Quick summary before moving on. Our html creates an input box for the user to tell how many seconds they want the delay to be. Next is the word animate in a tag. This is what we will click to run the animation. The CSS gives this a pointer cursor to indicate it can be clicked and a blue color. Next is an empty div that we make 100 pixels by 100 pixels with a redish background and an absolute positioning at 200 pixels from the top and 100 pixels from the left.

So, moving on.

jQuery

$(document).ready(function()
{
	//listen for our animate click
	$("#animate").unbind().click(function()
	{
		//get the value of the seconds input
		var numofseconds = $("input[name='seconds']").val();

		if(numofseconds === "" || isNaN(numofseconds) === true)
		{
			alert("Please enter a valid number.");
		}
		else
		{
			//turn our seconds number into milliseconds
			var numofmilliseconds = numofseconds * 1000;

			//get the left position of our animated div
			var pos = $("#animatethis").position();
			var leftpos = pos.left;

			//animate the box
			$("#animatethis").animate({left: "+=100"}, 1000, function()
			{
				//show delayed message
				$(this).html("

delayed for " + numofseconds + " seconds!

");

				$(this).delay(numofmilliseconds).animate({left: "-=100"}, 1000, function()
				{
					$(this).html("");
				});
			});
		}
	});
});

When the animate button is clicked we get the value the user has specified for the number of seconds. If the user has not specified a number of seconds or specified something other than a number we throw an alert to let them know that they need to enter a valid number. If they did enter a valid number then we can proceed. The delay() method accepts its delay in milliseconds. So we need to convert the number the user entered into milliseconds. We can do this by simply multiplying the number of seconds by 1000. Next we need to get the left position of the div. Once we have this we can begin the animation. We animate it to the right 100 pixels. Once the animation is complete we run our callback function. Here we get to use our nifty delay to pause the animation back to the left. Since we’re already dealing with the div being animated we can use $(this).delay() where ‘this’ represents the box being animated. We pass in to the method the millisecond version of our seconds and proceed to animate back to the left. Much much simpler than using a timer in javascript.

Selecting input text with jQuery

Wednesday, January 13th, 2010

When you have a form, browsers usually highlight the text value of the selected input field when tabbing through. However, if the user clicks the field the text is not highlighted and the cursor is placed appropriately. This is certainly not a bad thing, and in most cases is what it should do. But if you do want the value of the input field to highlight when a user clicks into the field as opposing to tabbing into the field it can be done with jQuery. I typed up a quick example.

Create a Form

<form name="myform" method="post" action="##">
	<input type="text" name="input1" value="input one" />
	<input type="text" name="input2" value="input two" />
	<input type="text" name="input3" value="input three" />
	<input type="text" name="input4" value="input four" />
</form>

Now let’s look at the jQuery. Remember to first link to the jQuery library.

The jQuery

$(document).ready(function()
{
	$("form[name='myform'] input").unbind().click(function()
	{
		$(this).select();
	});
});

Fairly simple.  We just use jQuery to listen for a click on any input fields inside our form named ‘myform’.  When it is clicked we use jQuery’s select() method to highlight the text in the input field.