Samantha J T Star
Samantha J T Star

Reputation: 32758

Can I attach multiple click events to an element using jQuery?

I have the following in a plug-in script:

$("#menu")
.on('click','a[href^="/Test"]',function(event){

        event.preventDefault();
        var href = $(this).attr('href');

        alert(this);
        // Load content
        $('#content').load(href, '', function (responseText, textStatus, XMLHttpRequest) {
            $(this).applyTemplateSetup().buildTableOfContent();
        });
        window.location.hash = '#' + href;

        // Get nav link
        var a = $('#menu a[href="' + href + '"]');
        if (a.length > 0) {
            // Mark as current
            $('#menu a').removeClass('current');
            a.addClass('current');

            // Update breadcrumb
            var breadcrumb = $('#breadcrumb').empty();
            while (a.length > 0) {
                if (a.get(0).nodeName.toUpperCase() == 'A') {
                    var target = a;
                }
                else {
                    var target = a.parent().find('a:first');
                }
                breadcrumb.prepend('<li><a href="' + target.attr('href') + '">' +
                a.contents().filter(function () {
                    return this.nodeType == 3;
                }).first().text()
                + '</a></li>');

                // Check if opened
                var li = a.parent();
                if (li.hasClass('closed')) {
                    li.removeClass('closed');
                }

                a = li.parent().parent().children('a, span');
            }
        }
    });       

I would like to also set the value of a link when the user clicks. I added this on my page but it seems like it does not get called. Is there a problem when I attach two of the same type of events to an element?

$("#menu")
            .on('click', 'a[href^="/Test"]', function (event) {
                event.preventDefault();
                var href = $(this).attr('href');
                var pk = href.substr(7, 4);
                var rk = href.substr(12, 4);
                var link = "/Admin/Testss/Edit?pk=" + pk + "&rk=" + rk;
                $('#editLink').data('href', link);
            });

Upvotes: 2

Views: 595

Answers (2)

Adam Sweeney
Adam Sweeney

Reputation: 386

Just keep it in the one click event, having it in two is redudant

Upvotes: 0

Basic
Basic

Reputation: 26756

Yes, it should work. Make sure that the code which defines the 2nd handler is actually being executed.

Alternatively, you could always modify the first handler you attach to call your (multiple) other functions.

Personally I'd prefer to get the former working as it allows you to attach/detach handlers independantly.

Do you have the same problem if you use Bind ?

As mentioned in comments on the Q, if any of the functions returns a false, it will prevent the event bubbling.

Upvotes: 1

Related Questions