Posts Tagged ‘javascript basics’

Javascript: Rollover Dropdown Menus

Tuesday, August 11th, 2009

Up until recently I’d never implemented a rollover dropdown menu. Then I just decided to build one from scratch for my employer College Prowler 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 link = 'mainLink';
    if (showHide == 0)
    {
        document.getElementById(menu).style.display = 'none';
        document.getElementById(link).setAttribute('class', 'mainNav');
        document.getElementById(link).setAttribute('className', 'mainNav');
    }
    else
    {
        document.getElementById(menu).style.display = 'block';
        document.getElementById(link).setAttribute('class', 'selectedRollover');
        document.getElementById(link).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!

Javascript: Creating an Image Watermark

Thursday, June 18th, 2009

Well, this is my last javascript post for a bit, seeing as this is just an offshoot of my last post Javascript: Dynamically Altering CSS Properties. In this post, we’ll go over creating a simple Javascript watermark for a textbox using an image. If you are curious how to create a watermark with just text, read my other post on how to create a textbox text watermark. A textbox watermark can help encourage its use and reduce confusion for your users. I typically employ a watermark for textboxes that exist outside of a form (they only gather one piece of needed information such as a zip code as opposed to an entire address).

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 hideWatermark(theID)
{
    var element = document.getElementById(theID);
    element.style.backgroundImage = 'none';
    element.style.backgroundColor = 'white';
}
function showWatermark(theID)
{
    var element = document.getElementById(theID);
    if (element.value.length == 0)
        element.style.backgroundImage = 'url(\'IMAGE_LOCATION_HERE\')';
    else
        element.style.backgroundColor = 'white';
}

On focus (when the user clicks on the textbox) the hideWatermark function is called. The javascript takes in a string of the textbox ID. It then sets the background image to none, and the background color to white. On blur (when the user clicks away from the textbox, putting focus on any other element), the showWatermark function is called. This javascript also takes in the same ID. It then checks to see if the content of the textbox is empty, if it is, it puts the background image of the watermark back in. If it is not empty, then it keeps the background color as white.

Here is the HTML that goes with the JS:

<input type="text" class="gatherZip" id="theTextBox" onblur="showWatermark('theTextBox')" onfocus="hideWatermark('theTextBox')" />

And the CSS:

.gatherZip{
   background: white url('IMAGE_LOCATION_HERE') no-repeat center center;
}

The image you create can say or imply whatever you want. As an estimate, try to keep the image no more than about 15 pixels high or it won’t fit in standard sized textboxes. And that’s it. A beautiful textbox watermark just for you and your users! Comments? Questions?

Javascript: Dynamically Altering CSS Properties

Tuesday, June 9th, 2009

I’ve been on a string of javascript posts, starting with Javascript: Opportunities Abound and then Javascript: Changing Class Names to Alter CSS. Well now I want to talk about a variant of altering CSS classes, and that is just altering inline style. I use this infinitely more than changing a CSS class. You can do a lot of very easy and simple interactions for the user that are really quite easy. You can show and hide divs, change background colors or images (I’ll use that to create textbox watermarks in my next post), and much more.

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 changeInlineStyle(tagID){
   var theTag = document.getElementById(tagID);
   if (theTag.style.display == 'block')
      theTag.style.display = 'none';
   else
      theTag.style.display = 'block';
}

The javascript first takes in a string with the tag ID that you send to it in the HTML below. Then, it creates an object that represents that ID which is named theTag. Then with a simple if statement, the javascript checks to see if the object is visible. If it is, it hides it, if it is hidden, it shows it. This is great for toggling a div with certain content. You can change different aspects of style though. Try "backgroundImage" or "backgroundColor" to change background characteristics. You can mess around with any aspect of tag’s style that you want. Text color, float, width, height, whatever you want. I have found the most common ones I use are display, backgroundColor, and backgroundImage though.

Here is the HTML that goes with the JS:

<a href="#" onclick="changeInlineStyle(targetTag);">
<div id="targetTag">This div will hide when the link above is clicked</div>

Yep, simple as that! When the link is clicked, it calls the javascript function, sending over the id to identify the tag it should work with. In this case, the link targets the div below it. Simple as that! I’ll talk about textbox watermarks next. Comments? Questions?

Javascript: Changing Class Names to Alter CSS

Tuesday, May 26th, 2009

As I discussed in my previous post, Javascript: Opportunities Abound, javascript is very powerful and can be used for a wide variety of client-side interactions. One of the most useful items I’ve found for it so far (mostly because of how much I love CSS) is to alter CSS classes! And the best part is it is incredibly easy. 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 changeCSS(tagID)
{
   var currentTag = document.getElementById(tagID);
   currentTag.setAttribute("class", "secondClass");
   currentTag.setAttribute("className", "secondClass");
   return;
}

The second setAttribute function is for certain versions of IE that for some odd reason (IE sucks) setting the class through javascript does not always function properly. I personally have not noticed this issue with IE6 or IE7, and IE5 is tops 1% of your users, so you can probably leave it out, I’ve just seen other people using it…

And now the HTML that goes with that JS:

<a href="#" onclick="changeCSS(targetTag);" id="targetTag" class="firstClass">Adjust link CSS</a>

Yep, simple as that! When the link is clicked, it calls the javascript function, sending over the id to identify the tag it should work with. In this case, the link is adjusting it’s own CSS, but it can work on anything else in the page. But what if you want the link to work both ways, to be able to change the CSS class of an object back and forth instead of just one direction? Try this on for size, a simple if statement in your JS function (the same HTML will do)

The New Javascript:

function changeCSS(tagID)
{
   var currentTag = document.getElementById(tagID);
   if (currentTag.className == "firstClass")
   {
      currentTag.setAttribute("class", "secondClass");
      currentTag.setAttribute("className", "secondClass");
   }
   else
   {
      currentTag.setAttribute("class", "firstClass");
      currentTag.setAttribute("className", "firstClass");
   }
   return;
}

And that’s that! Simple right? It is also possible to just change a specific aspect of the CSS instead of the entire class, but I’ll talk about that in a future post. Comments? Questions?

Javascript: Opportunities Abound

Tuesday, May 19th, 2009

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 collegeprowler.com 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 (again at College Prowler) 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.