Archive for the ‘Javascript’ Category

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.

Javascript debugging with MS Visual Web Developer 2010 Express

Monday, October 4th, 2010

A colleague of mine let me in on a pretty cool tip today. I think we’ve all been in a position where we needed to debug javascript for IE, but of course IE 6 and 7 do not have built in debuggers. As it turns out the Microsoft Visual Web Developer IDE has a built in javascript debugger for IE7 and 8 (unfortunately I couldn’t get the errors in IE6 to translate to the debugger). To get the debugger you will first need to download the free Visual Web Developer 2010 Express from here.

Once you have the IDE, open the version of IE you will be debugging in and choose Tools > Internet Options. Click the Advanced tab. Make sure that debugging in (Internet Explorer) is unchecked and the Always display errors is checked. Also make sure that you set it as your default browser.

Now open the VWD and create a new empty asp.net website. You don’t need to actually create any files since this site will only be used for debugging. So click the green arrow in the top toolbar to begin debugging. Confirm the prompt and it should open IE and throw a 404 error because you have no files for your empty website. But now you can simply navigate to the site you wish to debug. If any javascript errors are thrown on the page they will translate into the VWD debugger. Here you can now add break points and watches. Refresh the page and begin stepping through the script.

Converting a JSON string into a javascript object

Monday, September 27th, 2010

I’ve been working on a side-project recently that is utilizing the extJs library. At one point I am populating an extJs grid with a set of JSON data built in a Coldfusion function. 99% of the time I would simply return my JSON as ‘JSON’ using the ‘returnFormat’ attribute of the cffunction tag. But because I’m building this to work with CF7 as well as above and beyond I am having to return the JSON from the function to the calling page as a string that is built manually. It is retrieved using AJAX.

As far as javascript is concerned the JSON string is just a string. It needs to be deserialized into a javascript object whose name/value pairs become readily available for use. One way to do this is to use the javascript eval() function. I’ve illustrated an example below.

Will not work as a string

var jsonDataString = '{docs: [{Component: "cfcs.buildPizza", Name: "Function 1", DisplayName: "Function One"}]}';

//construct data store
var store = new Ext.data.GroupingStore(
{
	data: jsonDataString,
	reader: reader,
	autoDestroy: true,
	storeId: 'docs_store',
	groupOnSort: true,
	remoteGroup: true
});

Will work as an object

var jsonDataString = '{docs: [{Component: "cfcs.buildPizza", Name: "Function 1", DisplayName: "Function One"}]}';
var jsonDataObject = eval('(' + jsonString + ')');

//construct data store
var store = new Ext.data.GroupingStore(
{
	data: jsonDataObject,
	reader: reader,
	autoDestroy: true,
	storeId: 'docs_store',
	groupOnSort: true,
	remoteGroup: true
});

Will also work if writing JSON in javascript as an object

var jsonDataObject = {docs: [{Component: "cfcs.buildPizza", Name: "Function 1", DisplayName: "Function One"}]};

//construct data store
var store = new Ext.data.GroupingStore(
{
	data: jsonDataObject,
	reader: reader,
	autoDestroy: true,
	storeId: 'docs_store',
	groupOnSort: true,
	remoteGroup: true
});

In the first example our JSON data is stored and read as a string. This will not work when it comes time to parse it since it isn’t an object. In the second example, that same string is evaluated as an object using the ‘eval()’ method to type the string as an object.

In the last example I simply wanted to show that if you are writing the JSON within javascript to begin with there is no need to use the eval() method since you can write the JSON without the single-quotes and it will be immediately typed as an object.

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.

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.

Implementing CKEditor

Monday, January 18th, 2010

I’ve been using the FCKEditor rich text editor that can be implemented directly through Coldfusion 8 for some time now, but recently felt it was time to update. FCKEditor has now become CKEditor and appears to have made some pretty cool improvements.  I haven’t really had a chance to dive into the new editor, but thought I’d post a quick getting started kind of thing.  So the first step is, of course, downloading the plugin and copying it into your root folder, or wherever on your server.

Once you’ve got a copy, create a link to it in your header.  In the following example that I give I use jQuery  just because it makes my life ten times easier, but CKEditor is not a jQuery plugin and does not require it to run.  The easiest way to implement the editor is to create a standard HTML textarea and replace it with the rich text editor.  Before continuing to some code you can check out what the code will be creating here.

The HTML

Convert to Rich Text Editor?<span id="convertyes" class="textClick"> Yes</span>&nbsp;<span id="convertno" class="textClick"> No</span><br /><br />
<textarea name="myeditor">This is default text!</textarea><br /><br />
<span id="getvalue" class="textClick">Get Value</span>

We have just a couple things here.  Most important is the textarea with the name ‘myeditor’.  This is the textarea that we will convert to the rich text editor.  Otherwise, are just a couple functionality buttons.  First are a couple ‘yes’/'no’ buttons for converting the textarea to the editor and removing the editor.  And below the textarea is a button that allows us to get the value entered into the rich text area for further processing.

So let’s take a look at the javascript.

(more…)