Posts Tagged ‘jquery’

JQuery Plugin: Simple Textbox Watermark

In a previous post, I’ve written about creating a simple JQuery watermark. The code I wrote in that post is simple, and breaks down how a watermark really works. I expanded on that simplicity with this plugin, but not too far. Most watermark plugins I’ve seen are overly complex, attempting to account for all usage scenarios, when a majority of people only need to handle a small subset of those scenarios. So, I built a light plugin (under 1.3KB) that handles those basic scenarios well and implements easily. Here’s how it works:

Here’s how to implement it:

  1. Add in the most recent version of JQuery and the plugin code.
  2. In a document ready function, bind the plugin to any inputs and textareas you want with a single line of JQuery.
  3. Add the watermark text you want into the title property of the appropriate inputs and textareas.
  4. Apply any CSS you want to style your watermark text (suggested), and that’s it!
  5. Dependent on your usage scenario, call the function to clear out the watermarks before submitting the form.

The javascript:

$(document).ready(function(){
     $('.watermark').watermark();
});

The plugin applies a class of ‘marked’ to inputs and textareas when the watermark is active:

input.watermark, textarea.watermark { color: #000; }
input.marked, textarea.marked { color: #999; }

You’ve got to include your title property and the watermark class for the plugin to bind to the form item:

<input type="text" title="WATERMARK_TEXT class="watermark" />
<input type="text" title="WATERMARK TEXT" class="watermark" val="PREPOPULATED_VALUE" />
<input type="password" title="WATERMARK_TEXT" class="watermark" />
<input type="email" title="WATERMARK_TEXT" class="watermark" />
<textarea title="WATERMARK_TEXT" class="watermark"></textarea>

Here’s the javascript function to call if you want to clear out the watermarks before a form submission (just make sure to use the same JQuery targeting you used to bind the plugin to your form elements so you don’t miss anything):

$('.watermark').watermark('clearWatermarks');

It is as simple as that. Did I sell you on it? If so, download the plugin and enjoy! Here are links to both the unminimified and minified versions.

Download Full (1.66KB)Download Minified (1.26KB)

This plugin has been tested in the following browsers:

Chrome Firefox Internet Explorer Safari Opera

If you have any questions or comments on the plugin, please share. I may release more versions if there are specific feature requests that can be implemented without using a heavy amount of code. I want to keep this light, so if you want really advanced features, then this isn’t the plugin for you. But who knows, maybe I’ll write a more advanced one later…

JQuery Plugin: Hide And Show “N” List Items

My previous post was on using JQuery to hide and show part of a list. The javascript was simple and clean, but it was also a little hacky, because it required a hard-coded height to collapse your lists to. I felt it would be a little more appropriate to go further in depth and actually take a parameter for the number of list items you want to show by default. Notice in my sidebar, I automatically hide list items in my categories and popular post lists. I used the first version with a hard-coded height, to handle those. Here’s a really simple plugin that takes an optional number of list items to show, on page load, collapses lists to that number, and appends a link to toggle the list display.

Here’s an example of how it looks after you’ve applied it to multiple lists. You can apply it to both ordered and unordered lists. You can apply a different collapse number to individual lists, or the same number to them all. You can also change the text of the toggle link. As you can see below, there are two completely different implementations, using default settings on the left, and custom settings on the right.

  • item number 1
  • item number 2
  • item number 3
  • item number 4
  • item number 5
  • item number 6
  • item number 7
  • item number 1
  • item number 2
  • item number 3
  • item number 4
  • item number 5
  • item number 6
  • item number 7

To implement the JQuery plugin, just bind the collapseList function to any ordered or unordered list. To stick with the default settings, use the first line of code in a document ready function. To customize the collapse number, and the toggle link text, use the second example.

$('ul.collapse').collapseList();
$('ul.collapse').collapseList({
	'collapseNum' : 4,
	'moreLinkText' : 'custom show text',
	'lessLinkText' : 'custom hide text'
});

Now to the goodies. Download the plugin! Here are links to both the unminimified and minified versions.

Download Full (1.39KB)Download Minified (790B)

This plugin has been tested in the following browsers:

Chrome Firefox Internet Explorer Safari Opera

I’m thinking a more robust version 2 could be in the works, but I don’t know what kind of customization would be needed. There are a lot of possibilities, and I’m just trying to decide what would help more. Feel free to put in requests so I can start working on putting something out.

JQuery: Hiding And Showing Part Of A List

I’ve encountered many situations where I don’t have quite enough space to show all the items in a list, but I still want them to be available. The best example I can give of that is actually in my sidebar to the right! You’ll notice my popular posts and blog categories show less than half of the full list. I definitely wanted it to be easy to access all the categories and my most popular posts, so I didn’t want to have to limit the list. I also didn’t want to make my sidebar overwhelmingly long, causing my skyscraper ad to get pushed to the bottom of the page and below the main content entirely. The best solution was to use JQuery to automatically hide some of the list items, and then toggle them on hover.

This tutorial is a little bit different, but not by much. Instead of using the hover, we’ll actually use a link that needs to be clicked. The hover introduces an extra layer because you have to handle the hover on the list and the hover on the "view more" text added underneath. With a link, you can avoid that extra layer. Here’s an example of what we are making:

  • item number 1
  • item number 2
  • item number 3
  • item number 4
  • item number 5
  • item number 6
  • item number 7
  • item number 1
  • item number 2
  • item number 3
  • item number 4
  • item number 5
  • item number 6
  • item number 7

And more importantly, here’s how it works. First you’ve got to start with some HTML, a list in particular, either ordered or unordered. It is important to have the full list show by default without javascript. We’ll make sure that only if a user has javascript enabled on their browser will we hide any list items (because they wouldn’t be able to show them without javascript).

The HTML:

<ul class="collapse">
     <li>item number 1</li>
     <li>item number 2</li>
     <li>item number 3</li>
     <li>item number 4</li>
     <li>item number 5</li>
     <li>item number 6</li>
     <li>item number 7</li>
     <li>item number 8</li>
     <li>item number 9</li>
     <li>item number 10</li>
</ul>

Next, we move on to the javascript. Just to clarify for anyone that missed the post title, this requires the JQuery library, so make sure to include that! After that, this code is really quite simple actually. The first thing we’ll do is add a wrapper div which we’ll be using to manipulate the visible height of the list. Then, when the document has finished loading, we’ll immediately collapse the list to the desired height (in this case 45px), and add a link to show the hidden items. By using this method, we’ve made sure that the list is still accessible to those without javascript.

After that, we’ll write a function to get run on the click event of that link we inserted. It’ll check, if the link has the class “expanded”, then collapse the list to the given height, change the link text, and remove the “expanded” class. Otherwise, the list will get expanded to its full height, the link text will be changed, and the “expanded” class will be added.

The Javascript:

$(document).ready(function () {
	$('ul.collapse').wrap('<div class="collapseWrapper" />');
	$('div.collapseWrapper').css({ 'height' : '45px' }).after('<a href="#" class="collapseMore">view details . . .</a>');
	
	$('a.collapseMore').click(function () {
		if ($(this).hasClass('expanded')) {
			$(this).prev().animate({ height: '45px' }, 500);
			$(this).text('view details . . .').removeClass('expanded');
		}
		else {
			$(this).prev().animate({ height: $(this).prev().find( 'ul.collapse' ).outerHeight(true) }, 500);
			$(this).text('hide details . . .').addClass('expanded');
		}
		return false;
	});
});

And finally, you’ll need some CSS to define the wrapper div, and basic styling of the list and link.

The CSS:

ul.collapse{  }
ul.collapse li {  }
div.collapseWrapper { overflow: hidden; }
a.collapseMore {  }
a.collapseMore:hover {  }

It really isn’t that bad is it? Now if you want to expand on this, you can. I actually wrote a JQuery plugin to collapse lists to a given number of list items because I felt the hard-coded height was a little bit hacky. It is free, and very easy to implement with just a single line of code! Questions and comments are welcome.

JQuery: Creating a Text Watermark

Update: Read about my JQuery plugin which handles inputs, textareas, and even passwords! It is super easy to implement and very lightweight.

My post on creating a text watermark with javascript has been pretty popular. One comment had to do with being able to implement that watermark without being able to edit the HTML (only having access to CSS and Javascript). The easy solution to that is using JQuery. So as a follow up to that post, I wrote a quick tutorial on a text watermark using JQuery instead of plain old Javascript. Here is an example in action:


To do this, you’ll need the following code:

The HTML:

<input id="inputTextboxId" type="text" />

The Javascript:

$(document).ready(function() {
 var watermark = 'textbox watermark text';
 $('#inputTextboxId').blur(function(){
  if ($(this).val().length == 0)
    $(this).val(watermark).addClass('watermark');
 }).focus(function(){
  if ($(this).val() == watermark)
    $(this).val('').removeClass('watermark');
 }).val(watermark).addClass('watermark');
});

This javascript binds an event to both the blur and focus events of the input field. When the field gains focus (someone clicks in), the JS checks to see if the value of the input field is equivalent to the watermark, in which case it will clear it. When the field loses focus (someone clicks out), the JS checks to see if the field is empty, and if it is, places the watermark back in. The javascript also sets the default value of the textbox to the watermark so that you don’t have to edit the HTML at all. All of the “addClass” and “removeClass” events are only necessary if you wish to style the watermark differently than regular text input. To use this, you’ll need some CSS too.

Lastly, the CSS if you are feeling fancy:

input.watermark { color: #999; }

That’s it! A simple text watermark using JQuery that doesn’t require touching HTML at all.

AJAX: Loading External Content

Asynchronous Javascript and XML, is a method used to communicate with the server and load new content in a website without having to reload the page. You’ve probably seen it all over the web, and now you are going to learn how to implement it yourself!

Step 1: Install JQuery: Not sure what jquery is? It is basically a bunch a prebuilt javascript to make your life a whole lot easier. Go to http://jquery.com/ for the most recent version.

Step 2: Install JQuery UI For Better Animations (optional): I highly advise using some animations to spice up the interaction of your AJAX. When a user clicks something that fires your AJAX, they want to know something is happening. If it happens too quickly, they won’t know, so we’ll actually have to slow it down a bit for them. Visit http://jqueryui.com/download to download the UI components if you’d like these better animations. I advise the “core”, the “effects core”, and the “effects blind”. You can try other effects as well such as “fold” if you want a different visual.

Step 3: Make Two Different Pages: The concept of AJAX relies on the existence of two files. The first file is a normal webpage that will contain whatever you want to reload. The second file should use HTML, but not be contained within any html or body tags. The reason for this is your the javascript you are about to create will be loading the entire second document literally within the first document. You can’t have two html or body tags, so don’t use them! Having trouble understanding, well how about an example.  Say you are creating a search feature on your site. The first document is the actual search page that contains the search bar and submit button (say http://samplesite.com/search.html). The second document will hold the results of the search that was submitted on the first page and usually takes some sort of arguments, variables, query strings, or whatever else you’d like to call them (in the case of this example, probably the search terms entered in the search bar).

The HTML for the first document (front-facing):

<img id="loadImg" src="animatedGifLocation" alt="Loading..." />
<div id="opacityWrap"><div id="fillBox"></div></div>
<input id="queryField" type="text" value="" />
<input id="submitQueryButton" type="button" value="Submit Query" />

The PHP for the second document (hidden from users):

<?php
  $textBoxContent = $_GET['data'];
  echo ("<p>".$textBoxContent."</p>");
?>

Step 4: Write Some Javascript: Using some preexisting jquery functions, all we have to do is throw together a simple function that is called on the button click (or whatever else works for your particular situation). This particular javascript below uses an animated gif to indicate loading and a div two grey out the loading content box.

$("#submitQueryButton").click(function() {
  $("#opacityWrap").animate({ opacity: .15 }, 100);
  $("#loadImg").show();
  $("#fillBox").load("secondPageURLhere?query=" + $("#queryField").val(),function() {
    $("#loadImg").hide();
    $("#opacityWrap").animate({ opacity: 1.0 }, 100);
  });
});

Step 5: See It In Action:


Loading...

Dependent on whether you enter a number or a word into the text box, different content will load here. The button calls an AJAX function that loads another page. This page, dependent on the request sent by the AJAX, outputs the page’s determination of what you entered.

The most useful time for this implementation of AJAX is when you want to communicate with your database to load content that your already rendered page doesn’t have. This particular example does not actually use any information from a database, but it should get the point across. So now that you know how to implement this, go and do it! Ask questions if you got ’em.

AJAX: Wait Here Just A Minute

The best thing about Ajax is you can get brand new content on a page without having to reload it. The worst thing about ajax is people aren’t entirely used to waiting for content if they don’t see a page reload. Well, there is a quick and easy solution for that problem: animated gifs! In the beginnings of the web, animated gifs were used to make flashing titles that somehow everyone thought were the bee’s knees. Now that those are thankfully out of fashion, we can use animated gifs as an indicator that the website is “thinking”. The average web user won’t understand what all this AJAX stuff is doing in the background, all they need is something to tell them to wait just a little bit. Here are a few examples that I created using an awesome AJAX loading gif generator:

Oooh, that’s pretty. But maybe something more simple?

I like the simplicity, but it is too circly. Fix it designer!

And here’s a bar that could be used to indicate more of a “progress” concept instead of a “loading” concept:

I can guarantee that you’ve seen these types of images all over the web, and now you know why. It is possible people will implement these animated gifs for other purposes, but mostly, you’ll just experience them because of AJAX. Now go have fun making your own!

AJAX: What The Heck Is It?

Ajax is the new web 2.0 fad, and it is probably here to stay for quite some time. AJAX, or Asynchronous Javascript and XML, is a method used to communicate with the server and load new content in a website without having to reload the page. You’ve probably seen it all over the web, but possibly without necessarily thinking about what it is. The minor difference makes a huge positive impact on users, and a pretty negative impact on page impressions.

So what type of things would AJAX come in handy for? Well a very common implementation is for search tools. Say you are on a site looking for houses and there are tons of criteria you can enter in to narrow down your search. It is really helpful to see how each change in your criteria affects your results. To offer constant feedback, web developers need to use AJAX to bring back search results each time you change criteria. If they didn’t use AJAX, you’d be staring at a page reload every time, and that’d be mindbogglingly annoying…

So now maybe you understand the benefits of AJAX. It makes for a much more fun and usable experience for users as they traverse your website. The serious downside is a decrease in your pageviews. Every time you make an AJAX call, you lose what would have been a new page load and thus a new pageview. With each pageview (if you know what’s good for you AND have a highly trafficked website), you gain ad income. Now you could argue that with the improved user experience, you’ll make up for the lost pageviews in your AJAX tool with more devoted users (an argument I agree with), but that doesn’t cut it for everyone.

So make the choice to go with AJAX. In an upcoming post, I’ll write about the basics of AJAX and how to implement it.
Cheerio!

Javascript: Opportunities Abound

Javascript is a useful coding language that creates “client-side” changes to a website. It is really a great tool for simple and yet amazing interactivity on your website. Now for those of you who are used to only coding with HTML and CSS, Javascript will be quite a jump for you. Where HTML and CSS apply simply to content and layout, javascript can be very heavy on logic, something that typical computer programming is founded on. So be aware that JS could be a very big change for you.

So what can you do with JS? You can automatically rotate through images, or let users rollover thumbnails to enlarge a main photo. You can change text or even the styles that apply to text or other layouts. You can apply a simple watermark to a text box to indicate what users should do with it. You can sort tables or have fantastic animation effects to coincide with user actions. Have you ever encountered a popup window that greys out the background? Yep, that’s javascript (often combined with a few other fancy things such as AJAX, but no need to worry about that). There are really an endless number of options, many of which are pre-written to make your life easier! Here are some great resources for pre-written JS:

1. JQuery and JQuery UI are fantastic libraries of pre-written javascript. JQuery is an open-source (free for the masses) series of core JS files.The public then uses this open source base to build plugins that can do everything you could possibly imagine for client-side scripting. I’ve used jquery plugins on my fulltime employer’s website for a content slider and table sorting just to name a few items. JQuery UI is a subset of JQuery that focuses on very cool animation effects. I’ve used this to implement an accordion (multiple items where only one is visible at a time), sliding content boxes open and closed, and selection sliders, again to name a few. Great tools, and incredibly easy to implement! Be aware though, because it is open source, a lot of the plugins you end up using can be very finicky on your site…

2. Carousels and Content Sliders are a great way of exposing users to a lot of content without overpowering them with options. A lot of people choose Flash for the same purpose, but flash is awful for SEO purposes, is limited because not all of your users will have it installed on their computer, and is more difficult to update. I’ve found two great carousels that can be applied to either photos or content, and have a lot of customization abilities. Check out jcarousel by Jan Sorgalla, or for a slightly lighter version (the one I ended up using) take a look at jcarousellite. Another one I’ve found out there is at cssglobe.com, which seems pretty sweet as well.

3. Popup Boxes are one of the best javascript tools you’ll ever find. They also are one of the only ones you’ll ever find yourself contemplating paying for. Even though most web users hate the idea of popup windows, popup boxes are entirely different. When used in response to a user action, the popup box offers great opportunities for what you can provide your users with, without navigating them away from a page. They can login to a site that requires registration, they can fill out forms without being forced to have the form take up space on the regular page, or they can view slideshows of images, all without feeling like they’ve left the page that they felt comfortable enough on to click a link. The two best implementations of popup boxes (or shadow boxes or lite boxes as I’ve also heard them called) are Highslide and Lightview. I have more experience using Highslide, but I think Lightview is very well made and looks gorgeous. I had found Lightview by accident some time ago, and when trying to relocate it for this post, I found a listing of all the JS popups out there here. Careful, I haven’t tested any of them.

Those are just a handful of examples of pre-written JS that you can use. In upcoming posts I’ll write a little bit about simple JS that you can implement easy peasy on your own without any coding background.