The other day I've started a discussion on the jQuery dev list about event delegates and how the live() function can be improved with a few little tweaks from Zach Leatherman Blog - Performance Caveat with jQuery Selectors and Live Events

After reading at Zach's Blog I've was able to create a little plugin that I think will also be useful to those who are looking for an alternative way to bind live events to an element without first querying the document.

Example:


    $('#sidebar').delegate('li :click',callback); 

From my test in FF 3.5 and IE7 I was able to bind an event to a ul element with over 800 li elements with excellent performance!

Here's how to use the plugin:


    $(context).delegate('click',callback)  // same as live()

    $(context).delegate('li:even, li:odd :click',callback)  // supports multiple selectors

    $(context).delegate('li :click.namespace',callback)  // supports event namespace

    $(context).delegate('li:first a :click',callback)  // supports pseudo classes 

    $(context).delegate('li a :click mouseover',callback) // support future multiple event format 

The delegate method will use the same rules as that of the live() method.

Note: jQuery live() only supports single events: Unlike .bind(), only a single event can be bound in each call to the .live() method.

Here's the plugin code:


    <script type="text/javascript">
        jQuery.fn.delegate = function(event,fn) {
            var e,p,s;
            if (event.indexOf(':')) {
                s = event.substr(0,event.lastIndexOf(':'));
                event = event.replace(s+':','');
            }
            if (!s) e = this;
            else {
                p = this.selector + ' ';
                if (!s.indexOf(',')) s = p + s;
                else s = p+(s.split(/,/)).join(','+p);
                e = jQuery(document); e.selector = s
            }
            e.live(event,fn);
            return this;
        }
    </script>        

Working example:


    <script type="text/javascript">
        $(function(){
            $('#sidebar').delegate('li :mouseover',cb);
            $('#sidebar').delegate('li :mouseout',cb);
            //$('#sidebar').delegate('li:first, li:last :click',cb);
        });

        function cb (e){
            var c = (e.type=='mouseout') ? '#fff':'#ffcc00';
            $(e.target).css('background',c);
        }  
    </script>        

    <div id="sidebar">
        <ul>
            <li>item 1</li>
            <li>item 2</li>
            <li>item 3</li>
            <li>item 4</li>
            <!-- copy and paste more li elements here -->
        </ul>
    </div>        
Kevin J Pepperman
Posts: 20
Comment
live()s
Reply #18 on : Wed November 18, 2009, 06:47:24
Very nice. I have been watching that thread a lot and have tried every code sample.

This is definitely a good way to do this.

Hopefully a similar method ends up in the next jQuery core.

Thanks for sharing!
Zach Leatherman
Posts: 20
Comment
Re: jQuery Event Delegation
Reply #17 on : Wed November 25, 2009, 14:18:41
Are you sure this doesn't query the document? You're creating a jQuery object when you call the selector $(content), which by definition queries the document to fetch a result set.
escarpin louboutin pas cher
Posts: 20
Comment
Griff445
Reply #16 on : Fri July 11, 2014, 05:27:04
Rouge est le symbole d'une femme en talons hauts, est la source directe de la supériorité de la femme. Ont entendu parler de femmes avec émotion: ? femmes ne pas portent des talons rouges, c'est que je ne sais pas le concept de mode ?.Il est vrai que veulent les femmes fashion, tu dois porter des chaussures rouges. Donc, la femme dans les chaussures à semelle rouge toujours d'une femme qui n'a pas la personnalité d'une gerbe de pile de se démarquer, il ya une foule définitive se sentent. Cette femme était dilatée, audacieux, qui a surpris Cha son comportement, encore plus obsédé par son charme. Ainsi, une paire de chaussures à semelle rouge, mettant en évidence le comportement global d'une femme, son visage, l'allure et la mains monter en talons rouges mains.
escarpin louboutin pas cher http://www.clairedargaud.com/escarpin-louboutin-pas-cher.html
seo plugin
Posts: 20
Comment
Query529
Reply #15 on : Fri November 14, 2014, 06:16:13
Hello Web Admin, I noticed that your On-Page SEO is is missing a few factors, for one you do not use all three H tags in your post, also I notice that you are not using bold or italics properly in your SEO optimization. On-Page SEO means more now than ever since the new Google update: Panda. No longer are backlinks and simply pinging or sending out a RSS feed the key to getting Google PageRank or Alexa Rankings, You now NEED On-Page SEO. So what is good On-Page SEO?First your keyword must appear in the title.Then it must appear in the URL.You have to optimize your keyword and make sure that it has a nice keyword density of 3-5% in your article with relevant LSI (Latent Semantic Indexing). Then you should spread all H1,H2,H3 tags in your article.Your Keyword should appear in your first paragraph and in the last sentence of the page. You should have relevant usage of Bold and italics of your keyword.There should be one internal link to a page on your blog and you should have one image with an alt tag that has your keyword....wait there's even more Now what if i told you there was a simple Wordpress plugin that does all the On-Page SEO, and automatically for you? That's right AUTOMATICALLY, just watch this 4minute video for more information at. <a href="http://www.2014PandaSeo.com">Seo Plugin</a>
seo plugin http://www.2014PandaSeo.com/
Anonymous
Posts: 20
Comment
Enterprise697
Reply #14 on : Mon December 01, 2014, 12:44:46
oqncns
[url=http://www.seizenkeiyaku.org/watch/34.html][/url]
diablo 3
Posts: 20
Comment
Joystick533
Reply #13 on : Sat March 07, 2015, 07:30:21
THREE-DIMENSIONAL ink jet printers are usually excellent amazing. They""re also one of several worst concepts at any time.
[url=http://www.mmogameitems.com/wow-news]diablo 3[/url]
wildstar gold online
Posts: 20
Comment
Sentinel66
Reply #12 on : Wed April 22, 2015, 14:04:06
This is due to not often obtained skill linear size increases as a result of contributing methods, The particular beneficial properties much easier less quickly in contrast to that a majority of. You almost certainly most desirable than a PS4 will arrive out as being a mad mind blowing brewer after that, However its simply not true however, None does indeed the the evolution nutrition point out this really the problem. Nevertheless, The gospel truth here is always that the as some pole you think that they offer inside it, Aren't misleading the public, But instead are easily filing what understand and never taking a chance extremely when and the majority of fanboys round the interwebs are susceptible to do.
[url=http://www.wildstarplatinums.com/wild-star-product]wildstar gold online[/url]
seo
Posts: 20
Comment
Parser130
Reply #11 on : Wed May 13, 2015, 11:45:01
Hello Web Admin, I noticed that your On-Page SEO is is missing a few factors, for one you do not use all three H tags in your post, also I notice that you are not using bold or italics properly in your SEO optimization. On-Page SEO means more now than ever since the new Google update: Panda. No longer are backlinks and simply pinging or sending out a RSS feed the key to getting Google PageRank or Alexa Rankings, You now NEED On-Page SEO. So what is good On-Page SEO?First your keyword must appear in the title.Then it must appear in the URL.You have to optimize your keyword and make sure that it has a nice keyword density of 3-5% in your article with relevant LSI (Latent Semantic Indexing). Then you should spread all H1,H2,H3 tags in your article.Your Keyword should appear in your first paragraph and in the last sentence of the page. You should have relevant usage of Bold and italics of your keyword.There should be one internal link to a page on your blog and you should have one image with an alt tag that has your keyword....wait there's even more Now what if i told you there was a simple Wordpress plugin that does all the On-Page SEO, and automatically for you? That's right AUTOMATICALLY, just watch this 4minute video for more information at. <a href="http://www.SeoOptimizedRankings.com">Seo Plugin</a>
[url=http://www.SeoOptimizedRankings.com/]seo[/url]
seo plugin
Posts: 20
Comment
Enterprise869
Reply #10 on : Mon July 04, 2016, 14:38:21
Hello Web Admin, I noticed that your On-Page SEO is is missing a few factors, for one you do not use all three H tags in your post, also I notice that you are not using bold or italics properly in your SEO optimization. On-Page SEO means more now than ever since the new Google update: Panda. No longer are backlinks and simply pinging or sending out a RSS feed the key to getting Google PageRank or Alexa Rankings, You now NEED On-Page SEO. So what is good On-Page SEO?First your keyword must appear in the title.Then it must appear in the URL.You have to optimize your keyword and make sure that it has a nice keyword density of 3-5% in your article with relevant LSI (Latent Semantic Indexing). Then you should spread all H1,H2,H3 tags in your article.Your Keyword should appear in your first paragraph and in the last sentence of the page. You should have relevant usage of Bold and italics of your keyword.There should be one internal link to a page on your blog and you should have one image with an alt tag that has your keyword....wait there's even more Now what if i told you there was a simple Wordpress plugin that does all the On-Page SEO, and automatically for you? That's right AUTOMATICALLY, just watch this 4minute video for more information at. <a href="http://www.SEORankingLinks.com">Seo Plugin</a>
[url=http://www.SEORankingLinks.com/]seo plugin[/url]
converse boys street heather canvas high top sneaker
Posts: 20
Comment
BitCode612
Reply #9 on : Sat October 13, 2018, 22:52:18
<a href="http://www.ns2ns3.com/2019_release/team-red-covers-the-nike-air-max-95">team red covers the nike air max 95</a><a href="http://www.ns2ns3.com/available_now/adidas-originals-eqt-support-adv-womens-running-trainers-sneakers">adidas originals eqt support adv womens running trainers sneakers</a><a href="http://www.ns2ns3.com/a_first_look/reebok-womens-ventilator-sneaker-green-footwear-sneakers-6">reebok womens ventilator sneaker green footwear sneakers 6</a><a href="http://www.ns2ns3.com/black_friday_sale/reebok-furylite-slip-on-lux-womens-classics-shoes-black-white">reebok furylite slip on lux womens classics shoes black white</a>
[url=http://www.eyelidtumor.com/Where-to-buy/converse-boys-street-heather-canvas-high-top-sneaker]converse boys street heather canvas high top sneaker[/url]
Showing comments 1 to 10 of 18 | Next | Last

Leave a Comment

Required fields are marked with *.
If you have trouble reading the code, click on the code itself to generate a new random code.