jQuery: .each()

This entry is part 32 of 33 in the series jQuery Tutorial

The .each(function()) will iterate over a jQuery object, executing a function for each matched element.

Each time the callback or function runs, it is passed the current loop iteration, beginning from 0.

More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element.

<!doctype html>
<html>
<head>
    <title>each demo</title>
    <script src='//code.jquery.com/jquery-1.10.2.js'></script>
    <style>
        ul {
            font-size: 18px;
            margin: 0;
        }

        span {
            color: blue;
            text-decoration: underline;
            cursor: pointer;
        }

        .example {
            font-style: italic;
        }
    </style>
</head>
<body>

To do list: <span>(click here to change)</span>
<ul>
    <li>Eat</li>
    <li>Sleep</li>
    <li>Be merry</li>
</ul>

<script>
    $('span').click(function () {
        $('li').each(function () {
            $(this).toggleClass('example');
        });
    });
</script>

</body>
</html>

Submit Video

In this case, this is referred to the li element.

jQuery: Mouse hover event and callback

This entry is part 10 of 33 in the series jQuery Tutorial

We look at a rather interesting hover event that behaves similarly to the mouseover and mouseout events.

Inside the hover method, there are actually 2 functions.

The .hover() method binds handlers for both mouseenter and mouseleave events. You can use it to simply apply behavior to an element during the time the mouse is within the element.

<!doctype html>
<html>
<head>
    <title>hover demo</title>
    <style>
        h3 {
            color: blue;
        }
    </style>
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script>
        $(function(){
            $('h3').hover(
                    function () {
                        $(this).css('color','red');
                    }, function () {
                        $(this).css('color','blue');
                    }
            )});
    </script>
</head>
<body>
<h3>Milk</h3>
</body>
</html>

Try The Code

Calling $(selector).hover(handlerIn, handlerOut) is shorthand for:

$(selector).mouseenter(handlerIn).mouseleave(handlerOut);

The first function above is for handlerIn and the second function is for handlerOut.

Callback Functions

The 2 functions are actually callback functions in Javascript/jQuery. Callback is a very important concept in jQuery. With callbacks, functions will run one after another or continuously.

In this case, first function will first run and after it’s done, it will come back and run the second function. That is probably how the name callback is derived.

We will comeback to callback in the later posts.