Delegate Function in JavaScript

There is only a single listener for all of the above buttons. It is a delegate(), called on the parent element.

When the event occurs, 'this' refers to the object on which the event occurred.

In Head Section

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

    <script type="application/x-javascript">
        $(function(){

    $("#container").delegate("button", "click", function(index){

        paneToShow = "#" + $(this).text();
       
        $(".content-pane").hide();

        $(paneToShow).show();

    });

});

    </script
>

    <style type
="text/css">

        .content-pane {

    display: none;

        padding: 5px;

            border: 2px solid #000;

}

</
style>

In body Section

<div id="container">

    <h1>Click any button below...</h1>
    <button id="first">First</button
>

    <button id="second" >Second</button
>

    <button id="third">Third</button
>

    <button id="fourth">Fourth</button
>

    <div id="First" class
="content-pane">

        <h1>You clicked First Pane...</h1
>

</div
>

    <div id="Second" class
="content-pane">

        <h1>You clicked Second Pane...</h1
>

</div
>

    <div id="Third" class
="content-pane">

        <h1>You clicked Third Pane...</h1
>

  </div
>

    <div id="Fourth" class
="content-pane">

        <h1>You clicked Fourth Pane...</h1
>

   </div
>

</
div>

Description

When the event occurs, 'this' refers to the object on which the event occurred. The advantage of this approach is that there is a single listener, which means less memory being consumed. I can still add listeners to the individual buttons, should the need arise. The downside is figuring how to get information on the clicked element. Fortunately, jQuery assigns 'this' to the clicked element, so we can use $(this) and treat it as a normal DOM element.

Ebook Download
View all
Learn
View all