CSS-Plus
CSS-Plus
Play with web technologies

Save time - Define a function

August 11, 2010
Attention: This article is old and the content is outdated. I've left the article here for historical purposes.

Functions save you time - And if you didn't know that, you should probably get on the function band wagon.

Functions are shortcuts. They:

  • Save you time
  • Save you the hassle of rewriting code you have already typed
  • Make it easier to read the code
  • Make it easier to manage and update the code
  • Reduce errors and trouble-shooting

It is, however, a time waster to create a function for something when it is not needed. As developers, we should think ahead and decide when it would be appropriate to create our own jQuery functions. Recently, I created a piece of javascript which I needed and found useful. I needed to use that same snippet with slight modifications. I copied and pasted the code, which suddenly started filling up my screen, but I thought nothing of it... Until... I had to copy and paste it again. I decided that it was far from acceptable to do this so I turned it into a simple function which I now use in almost every project.

We'll start off by going over HOW to define our own functions and then into creating a function that could benefit us in future.

The HTML

<form action=""> <fieldset> <legend>Example Form</legend> <input type="text" /> <input
type="submit" value="Submit"/> </fieldset> </form>

It's a pretty simple form. This HTML isn't very important right now, what is important is the javascript! - Because of this I'm not going to style it and jump right into the javascript instead.

The jQuery/Javascript

// Declare function 'bgColor'
jQuery.fn.bgColor = function(yourColor) {
    return this.css("background", yourColor);
};

// When the DOM is ready
$(document).ready(function() {
    $("input").bgColor("green");
});

What we've done is declare the function bgColor. You can obviously call it anything you want, but you should try and make sure your functions have a unique (to avoid conflicts) and descriptive name. I've called it bgColor because, as you have guessed, it changes the background color of the targeted element. jQuery.fn.bgColor = function(yourColor) { - If you haven't created a jQuery function before, this line is probably the most tricky. What it is saying is: The function bgColor is equal to whatever is within the function. The variable 'yourColor' is defined by the user by typing a value within the defined-function's brackets. In this case .bgColor("green")

Any value that would be a valid in this situation: .css("background", yourColor); would now be valid in this situation: .bgColor(yourColor)

But turning something already very short into something slightly shorter doesn't really help anyone too much. So let's put this newly learnt skill to use.

I'm not sure what you call this "trick", but it's when there is text within an input-field, and it disappears when you focus on the field, and comes back when it loses focus if there is no value in the field. Anyway, let's get started with the jQuery.

Also, on a side note, it is important to use $(this) a lot because it will be affecting the element you choose, as opposed to a preset element.

// Define the function - In this case, "inputValue"
// We will use the variable "value" - Defined by the user - throughout the function
jQuery.fn.inputValue = function(value) {
    // Target this value and replace it with the variable 'value' defined by the user
    return this.val(value)
        .focus(function() {
            // If this value is equal to the variable
            if ($(this).val() == value) {
                // Remove the text
                $(this).val("");
            }
            // When the focus is lost
        })
        .blur(function() {
            // If there is no value
            if ($(this).val() == "") {
                // Replace this with the variable
                $(this).val(value);
            }
            // Else do nothing
        });
};

That's it, we have a defined variable. Now all we need to do is actually test it.

$(document).ready(function() {
    $('form input[type="text"]').inputValue("Example Value!");
});

And there you have it. A simple and useful function you will probably use over and over... I know I do.

If you don't already create your own functions, I hope this inspires you to start!

Demo