I’m having trouble getting the syntax write for an $.each equivalent using delegates.
All the examples I’ve read just show click or hover but how would I go about writing this with the delegate syntax?
$("ul li a").each(function(){
$(this).addClass("foo");
});
Cheers!!
Edit: Following the multitude of comments (thanks by the way) I thought I’d better post a more explicit example. My apologies for the lack of detail in my prior question.
Say for example I want to bind tooltips to anchors on a page. I’ll have a lot of items that I want to set up as tips and I want to reduce the memory overhead by using delegation.
As I understand this is how I would get started:
$(document).delegate("a.tooltip", "click", function(event){
// run click event
}).delegate("a.tooltip", "hover", function(event){
// run mousenter, mouseleave events.
});
But lets say for each of those anchors I want to remove the title attribute so it doesn’t show up in the browser when I hover. I would imagine (I am guessing here though) that any native events like that would run before my hover event so I want to remove it before I hover over.
Normally I would use something like this:
$("a.tooltip").each(function () {
// Store our title attribute and remove it so we don't get browser
//tooltips showing up.
$.prop(this, "data-old-title", $.attr(this, "title"));
}).removeAttr("title");
Can this be done a better way?
From what I understand in the comments and answers delegate covers events only and I will still have to keep anything like this separate.
You probably have a misconception of what
.delegate()is or how it works. It’s not some kind of magic function which intercepts all DOM manipulations, it just takes advantage of the event bubbling feature of the DOM, hence it can only be used for events.Basically if you have a
<div>element, to which you intend to add a<button>later, you can use.delegate()to bind the click event to the<div>itself.In the future, when you do add your button, clicking it will fire the click event of the button, and it will carry on bubbling up the DOM, calling each parent element’s click event in succession, until it reaches the document root or one of the handlers call
event.stopPropagation(). At one point, it will reach your<div>, where you’ve bound your delegate event. The delegate event will check if the element that originally fired the event matches the original selector (to which you wanted to bind your event in the first place), and if it does, it fires the attached event handler in the context of your button, so within the event handler it will look like the button threw the event.As you see there is no magic, it has nothing to do with monitoring the DOM for changes or anything like that. If you want to add special classes as you add elements to the DOM, you have to make sure you call a function yourself whenever that happens.