ckportfolio.com - Web Development: jQuery Essentials

Web Development: jQuery Essentials

Syntax

Similar to CSS, each line of jQuery code exists to manipulate an existing object in the document. Its syntax may be quite different than HTML and CSS, but it ultimately adheres to a specific design pattern.

$("#hello").show();

$("p").css("color", "red");

$("#item").click(function(){
    alert("clicked!");
});

Note that each line of code, along with a series of many braces and brackets, contains three common elements: a dollar sign ($), a CSS-like selector, and some sort of a command. The complete list of jQuery commands are available in its documentation.

Note that jQuery selectors behave in an identical fashion as CSS counterparts. One is always expected (except for a few exceptions) to start with a selector. Without HTML, jQuery would cease to exist.

jQuery Commands

There are plenty of human-readable commands available as part of jQuery, but they are organized into two parts: effects and events. Effects can directly influence HTML elements, while events can detect changes in HTML elements and perform a task.

Below are some of the examples of jQuery effects and events:

Effects


$("#item").show();
$("#item").slideUp();
$("#item").html("hello world");
$("#item").css("margin-top", "30px");

As one can guess, jQuery commands are straightforward and allow the novices to easily guess or identify what each line is responsible for.

Events


$(“#item2”).click(
    function(){
        alert(“clicked!”);
    }
);

$(“#item2”).hover(
    function(){
        $(“#hover”).fadeIn();
    }, function(){
        $(“#hover”).fadeOut();
    }
);

Note that the two parentheses after click and hover are expanded with extra lines of code. These extra lines of code dictate what will happen when the user performs a specific task (ex click on #item2), usually resulting in some sort of an animation or a user prompt. jQuery allows the developer to identify and respond to various browser events, including click, mouseover, browser resize, and even page scroll.

Fin