Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I add an anonymous jQuery function to many elements is it repeated many times?

Tags:

jquery

I have the following:

$('#menu a[href^="/C"], #menu a[href^="/Test"], #menu a[href^="/T"]')
        .live('click', function (event) {
.....
.....
        });

It looks at each of the menu address links and then adds a function to each. However the function marked by ..... is about twenty lines long and I have up to one hundred address links.

When coded this way does this mean that all of those twenty lines are added to each of the hundred links? Should I change this to use a named function or is that anonymous function created with a system generated name and not stored internally for every link?

like image 605
Samantha J T Star Avatar asked Jan 28 '26 12:01

Samantha J T Star


1 Answers

You are using event delegation, therefore the event is only bound to the document. So, no, those twenty lines are only bound in one place.

Please use either the delegate method or the on method, .live is depreciated in newer versions of jQuery and is inefficient.

$("#menu").delegate('a[href^="/C"], a[href^="/Test"], a[href^="/T"]','click',function(){...});

or

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

If you are using a very old version of jQuery and must use .live, try this syntax instead, it is a little more efficient for your usecase, however must be within a $(document).ready()

$('a[href^="/C"], a[href^="/Test"], a[href^="/T"]','#menu').live('click',function(){...});
like image 168
Kevin B Avatar answered Feb 02 '26 07:02

Kevin B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!