Search code examples
jquery

In JQuery, how to pass the element that was clicked to the method that is called on onclick event


I have several of these lines on a page:

<div class="save-button" onclick="Save()">Save</div>

In my Save() method I want to manipulate the div that was clicked to call the Save() method. How do I pass that in (I think $(this) ), without resorting to ids?

Many thanks!


Solution

  • Either remove the save() and use click() to catch the event:

    <div class="save-button">Save</div>
    <script>
    $('.save-button').click(function () {
        // Now the div itself as an object is $(this)
        $(this).text('Saved').css('background', 'yellow');
    });
    </script>
    

    [ View output ]

    Or if you insists on using such function as save():

    <div onClick="save(this)">Save</div>
    <script>
    $(function () {
        save = function (elm) {
            // Now the object is $(elm)
            $(elm).text('Saved').css('background', 'yellow');
        };
    });
    </script>
    

    [ View output ]

    EDIT (2015): .on('click', function)

    <div class="save-button">Save</div>
    <script>
    $('.save-button').on('click', function () {
        // Now the div itself as an object is $(this)
        $(this).text('Saved').css('background', 'yellow');
    });
    </script>