Archive for the ‘Javascript Tutorials’ Category

Simple JQuery Tooltip

Tuesday, December 6th, 2011

There are some great JQuery tooltip plugins out there, such as qTip2. In fact, I use qTip2 on this site, and on my fulltime employer’s site, College Prowler 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

Wednesday, October 5th, 2011

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 = '<span>textbox watermark text</span>';
  $('#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.

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

Friday, January 7th, 2011

UPDATE: Read about the JQuery version of this text watermark.

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

Wednesday, September 29th, 2010

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://code.google.com/p/jqueryjs/downloads/detail?name=jquery-1.3.2.min.js to download the most stable version of JQuery as of this post publishing date (1.3.2) or http://jquery.com/ for the most recent version (1.4.2).

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

Sunday, September 12th, 2010

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!