Archive for the ‘Javascript Tutorials’ Category

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.

Simple JQuery Tooltip

There are some great JQuery tooltip plugins out there, such as qTip2. In fact, I use qTip2 on this site because of how robust I think it is. However, sometimes, on smaller sites, you don’t want to load all that excessive code built to work in hundreds of different configurations just for a handful of tooltips. Well have no fear. Here’s how you can build a simple tooltip. Using a little JQuery, and some CSS3 (for the speech bubble discussed in my previous article and the question mark icon) you can make your own tooltips!

Here’s what we’ll be making:

This sentence needs more of an explanation for the user. ?

Now let’s get into the code needed to produce the example. The HTML is actually very simple. We are going to inject the content for the tooltip using JQuery so we won’t even need anything to target except the link that you hover on that triggers it.
Here’s the HTML:

<p>This sentence needs more of an explanation for the user. <span class="question">?</span></p>

The CSS looks pretty long. But in reality, it is built to my own personal liking. The "question" class applied to a span produces the question mark circle icon. You can easily do this with an image if you prefer, or apply it to a simple link with text or a question mark without any styling. Then there are two items for the "tooltip" class. The first item defines what the tooltip will look like (rounded borders, background color, text styling, etc.). The pseudo class of :before (or :after if you like) inserts an item before (or after) the element it is applied to. In this particular instance, the :before statement adds the tip to the tool, which you don’t need to use if you don’t want, or again, you can use an background image if you prefer.
Here’s the CSS:

span.question {
  cursor: pointer;
  display: inline-block;
  width: 16px;
  height: 16px;
  background-color: #89A4CC;
  line-height: 16px;
  color: White;
  font-size: 13px;
  font-weight: bold;
  border-radius: 8px;
  text-align: center;
  position: relative;
}
span.question:hover { background-color: #3D6199; }
div.tooltip {
  background-color: #3D6199;
  color: White;
  position: absolute;
  left: 25px;
  top: -25px;
  z-index: 1000000;
  width: 250px;
  border-radius: 5px;
}
div.tooltip:before {
  border-color: transparent #3D6199 transparent transparent;
  border-right: 6px solid #3D6199;
  border-style: solid;
  border-width: 6px 6px 6px 0px;
  content: "";
  display: block;
  height: 0;
  width: 0;
  line-height: 0;
  position: absolute;
  top: 40%;
  left: -6px;
}
div.tooltip p {
  margin: 10px;
  color: White;
}

And lastly the Javascript is actually quite simple. You use the hover toggle event (hover, then unhover) to create it. On hover, we simply append the actual tooltip div and it’s content to the question mark icon. Then on unhover, we remove the tooltip element.
And finally, here’s the Javascript:

$(document).ready(function () {
  $("span.question").hover(function () {
    $(this).append('<div class="tooltip"><p>This is a tooltip. It is typically used to explain something to a user without taking up space on the page.</p></div>');
  }, function () {
    $("div.tooltip").remove();
  });
});

It really isn’t that bad, and it can easily be adjusted to work for several tooltips instead of just one. Got any questions? Comments? Just ask!

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.

Javascript: Creating a Text Watermark

Update: Read about the JQuery version of this text watermark or better yet, check out my lightweight JQuery plugin which handles inputs, textareas, and even passwords!

This post is in response to a request to see how to create a textbox watermark using only text instead of an image. In a previous post, I explained how to use an image for a textbox watermark. Textbox watermarks are fantastic tools you can use to improve the usability of a website, as they give the user guidance on what to enter into the textbox. If you don’t want to use an image as my other post describes, here is how to create a simple watermark using javascript. Before we begin though, see exactly what you are making:


So either in an external Javascript file (which is called the same way as an external CSS file), or in the head of your HTML inside a <script> tag, include the following javascript:

The Javascript:

function watermark(inputId,text){
  var inputBox = document.getElementById(inputId);
    if (inputBox.value.length > 0){
      if (inputBox.value == text)
        inputBox.value = '';
    }
    else
      inputBox.value = text;
}

This javascript function checks if the textbox text isn’t empty, and then determines whether to clear the text or not. It also will put the watermark text back in if the user deletes what they entered or doesn’t enter anything. The function needs to be called in both the onblur and onfocus events of the textbox, which is explained below.

Here is the HTML that goes with the JS:

<input id="inputTextboxId" type="text" value="type here" onfocus="watermark('inputTextboxId','type here');" onblur="watermark('inputTextboxId','type here');" />

That’s all you need! And if you have any questions, don’t hesitate to ask! A question on my image watermark post lead to this post, so you never know!

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: Rollover Dropdown Menus

Up until recently I’d never implemented a rollover dropdown menu. Then I just decided to build one from scratch for my fulltime employer to improve upper-level navigation. Basically, with some simple javascript to hide/show the menu and some CSS to style and position it, you’ve got yourself a simple javascript rollover dropdown menu! The code follows the example implementation below.

The Javascript:

function rolloverMenu(showHide, menu)
{
    var linkObj = document.getElementById('mainLink');
    var menuObj = document.getElementById(menu);
    if (showHide == 0)
    {
        menuObj.style.display = 'none';
        linkObj.setAttribute('class', 'mainNav');
        linkObj.setAttribute('className', 'mainNav');
    }
    else
    {
        menuObj.style.display = 'block';
        linkObj.setAttribute('class', 'selectedRollover');
        linkObj.setAttribute('className', 'selectedRollover');
    }
}

This javascript will either hide or show the menu depending on the location of the cursor. The HTML that calls the javascript has a delay on it as well, but you’ll see that later. This javascript also changes the class name of the link so that even though your mouse isn’t technically hovering over that link it will look like it is being hovered over.

The CSS:

#container{
    position: absolute;
    z-index: 1001;
}
a.mainNav{
    color: White;
    font-weight: bold;
    font-size: 12px;
    height: 40px;
    padding: 0px 10px;
    line-height: 40px;
    float: left;
    background-color: #1D3E66;
}
a.mainNav:hover{
    background-color: #3D6199;
    color: #AAAAAA;
}
a.selectedRollover{
    color: White;
    font-weight: bold;
    font-size: 12px;
    height: 40px;
    padding: 0px 10px;
    line-height: 40px;
    float: left;
    background-color: #3D6199;
}
.rolloverMenu{
    float:left;
    padding: 10px 10px 6px 10px;
    position: absolute;
    z-index: 1000;
    background-color: #3D6199;
    width: 100px;
}
.rolloverMenu#mainMenu{
    top: 40px;
}
.rolloverMenu a{
    color: White;
    font-weight: bold;
    font-size: 12px;
    line-height: 20px;
}

Change the CSS to fit your own design. I’ve been very specific in this CSS so that it should be easier for you to identify everything. Note that the #container definition is actually very important for an IE6 bug fix. IE6 has issues with z-index when not combined with absolute positioning. Basically, the parent element of the rollover menu needs to have that specific definition.

Lastly, the HTML:

<div id="container">
  <a class="mainNav" href="#" id="mainLink" onmouseover="rolloverMenu(1, 'mainMenu');" onmouseout="rolloverMenu(0, 'mainMenu');">Rollover Me</a>
  <div class="rolloverMenu" id="mainMenu" style="display: none;" onmouseover="rolloverMenu(1, 'mainMenu');" onmouseout="rolloverMenu(0, 'mainMenu');">
    <a href="#">Link 1</a><br />
    <a href="#">Link 2</a><br />
    <a href="#">Link 3</a><br />
    <a href="#">Link 4</a>
  </div>
</div>

And that’s that! The HTML link calls the javascript which implements a series of CSS rules that will hide or show the menu of your choice! Have fun!