jQuery – DOM, events and effects. Part 2.


Level: intermediate

Here we go with the second part of jQuery basics, in which we describe the visual effects, DOM operations and events handling using this library.

Getting deeper in jQuery

Let’s start with the basics of visual effects.

There are main methods for elements visibility:

show() – causes dynamic showing of hidden element. As arguments can take a speed and the callback function:

show( speed, callback )

hide() – hiding an element:

hide( speed, callback )

toggle() – toggle the visibility of the element: show – if hidden, hide – when visible:

toggle( switch )

Example – use the toggle() method on the button element:

var flip = 0;
$("button").click(function () {
    $("p").toggle( flip++ % 2 == 0 );

Folding and unfolding the element

These methods are able to change the visibility of an item, and they do it with animation (winding / unwinding):

slideDown( speed, callback )

slideUp( speed, callback )

Fading – transitions

In this case there is an animation of appearance / disappearance:

fadeIn( speed, callback )

fadeOut( speed, callback )

Change the style of element

We can dynamically set the element’s style, using methods: css(), addClass() and removeClass().


$(this).css('color', 'yellow'); // set the color property
$(this).addClass('inny'); // add the CSS class
$(this).removeClass('inny'); // remove class 

Example #2 – iteration:

    // every li element will be blue 
    $('li').css('color', 'blue');


We know this already from other frameworks. Many methods can be linked together in a chain.


$('li').css('color', 'yellow').append('- read more')
    .css('background', 'black');
// of course we can call this as 3 separate instructions

Events and jQuery

Another very strong point of jQuery is the event handler.

Example – shwo and alter after clicking on a paragraph:

$(document).ready(function() {
    $('p').click(function() {

Handling of double click we obtain by:



jQuery also has handling of mouse. Methods such as .mouseout(), .mouseOver(), and much more, are described in documentation.

Removing event handler we execute by unbind():

$('#switcher-narrow, #switcher-large').click(function() {


Keyboard support with jQuery is completely painless.


$(document).ready(function() {
    $(document).keyup(function(event) {
        switch (String.fromCharCode(event.keyCode)) {
            case 'D':
            case 'N':
            case 'L':

Animations – examples

Basically, animation support in jQuery looks like this:

.animate({property1: 'value1', property2: 'value2'},
    speed, easing, function() {
        alert('The animation is finished.');

For example – growing item:

$('#grow').animate({ height: 500, width: 500 }, "slow", 
    function() {
    alert('Element has grown!');

Animation speed is defined in the second parameter, in this case it’s “slow”.

Example – positioning the elements with animation effect:

$(document).ready(function() {
    $('div.label').click(function() {
        var paraWidth = $('div.speech p').outerWidth();
        var $switcher = $(this).parent();
        var switcherWidth = $switcher.outerWidth();

            .animate({left: paraWidth - switcherWidth},'slow')
            .animate({height: '+=20px'}, 'slow')
            .animate({borderWidth: '5px'}, 'slow');

DOM and jQuery

How can we expect, jQuery provides us powerful tools to work the DOM.

Example – when the DOM is ready, the second paragraph of the document (index 1) will be hidden:

$(document).ready(function() {

Example – dynamic content:

$(document).ready(function() {
    $('a.more').click(function() {

        return false;

Example – accessing DOM elements:

var myTag = $('#my-element')[0].tagName;

Example – DOM and manipulation of form:

// hide all labels having the 'optional' CSS class

// add red frame for input elements of type 'password'
.find('input:password').css('border', '1px solid red').end()

// handle submit action
.submit(function() {
    return confirm('Are you sure you want to submit?');

Inserting a new element to the DOM – insertXXX() methods

Example – insert a link at the end of the article:

$(document).ready(function() {
    $('<a href="#top">back to top</a>')
        .insertAfter('div.article p');
    $('<a id="top"></a>');

The insertAfter() method – inserts after the element. To insert before we will use the insertBefore() method.

There is another approach – adding to the element: prependXXX.


$('<a id="top" name="top"></a>').prependTo('body');

Wrapping elements, so embedding an element within a specific HTML code


.wrap('<li id="foot-note-' + (index+1) + '"></li>');

Copying items we can perform by the method clone(), e.g.:

// this code will create a copy of the first paragraph in
// the DIV with "chapter" CSS class
$('div.chapter p:eq(0)').clone();

// Example #2
$('div.chapter p:eq(0)').clone().insertBefore('div.chapter');

Methods to manipulate the DOM – summary

1. Create a new element in the structure:

the $() method

2. Inserting elements inside the element:

.append(), .appendTo(), .prepend(), .prependTo()

3. Inserting new elements next to the element:

.after(), .insertAfter(), .before(), .insertBefore()

4. Insert new HTML elements around the indicated elements – wrapping:

.wrap(), .wrapAll(), .wrapInner()

5. Changing the elements or text contained therein:

.html(), .text(), .replaceAll(), .replaceWith()

6. Remove items from the interior of the specified element:


7. Deleting a particular element and its descendants from the document:



We described how to do the deal with event handling, effects and animations. And with short summary of DOM methods, we finish the 2nd part of basic jQuery course.

Thank you.

Web and Mobile Software Developer, with years of experience. My biggest passions are programming, new technologies, e-commerce, as well sports, cars, and of course my family.

Facebook Twitter LinkedIn Google+ Skype Xing 

Share: Share on Facebook2Tweet about this on TwitterShare on Google+1Share on LinkedIn0Share on Tumblr0Digg thisEmail this to someonePin on Pinterest1
Both comments and pings are currently closed.

Comments are closed.