tags:

views:

62

answers:

3

hey all,

what does it mean where there are two id's in the jquery selector using the .live method?

for example:

$('#mybtn', '#mydiv').live('click', function...

thanks, rodchar

+6  A: 

This is using context. It is considered a bad practice to pass in a string as the context, but it works. It's equivalent to this:

$('#mydiv').find('#mybtn').live('click', function...
Alex Sexton
Just a note: this isn't specific to the $.live method. It's just part of jQuery.
Alex Sexton
To add to the above: The click event will be bound to the #mybtn element that is a decendent of the #mydiv element. This include the method above OR a normal selector like $("#mydiv #mybtn");
Kevin Peno
@rod http://docs.jquery.com/Core/jQuery#expressioncontext
Kevin Peno
It's the second parameter in the core jQuery function on the first page of the docs :) - http://docs.jquery.com/Core/jQuery :: See [Context]
Alex Sexton
thank you everyone for the quick feedback and insight,rod.
rod
@Kevin Peno - $('#mydiv').find('#mybtn') is not _exactly_ equal to $('#mydiv #mybtn') when it comes to performance. It will return the same set, but the former is much faster thanks to a shortcut in jQuery that executes single id lookups without ever even hitting the selector engine core. This is obviously secondary to just returning the correct results though...
Alex Sexton
+1  A: 

It means search for an element with id="mybtn" within an element with id="mydiv"

Seems rather pointless to do such a thing when you are looking by ID. Because ID is always supposed to be unique.

Josh Stodola
by id is a bad example, but it would make sense in other cases (such as $( ".clickbtn", "#mydiv" );
Kevin Peno
It's not necessarily pointless. In the case that you were dragging elements from one container to another, if you only wanted an element to have an action _inside_ of a certain container, then you would use a structure like this to indicate that its parent must be a specific container.
Alex Sexton
I understand that, but you'd never have another element with the same ID. A `class` attribute seems much more appropriate.
Josh Stodola
It's not really about having another element with the same id. It's simply only attaching a handler to an element when it is specifically inside of another specific element. Like if I wanted to put an opacity on an element after I dragged it into the trash can: $('#trashcan #elem').css('opacity', '0.6');
Alex Sexton
+1  A: 
$('#mybtn', '#mydiv')

would pass #mydiv as the context parameter to the jQuery $ function (jQuery core documentation)

If you meant

$('#mybtn,#mydiv')

this would bind the live event handler to both matched elements (elements with ID mybtn and mydiv). The comma is standard CSS syntax for matching more than one selector. The $ function would return a jQuery object with length=2 (assuming that one instance of both mybtn and mydiv exist on the page). The 'live' function will bind live events to both elements.

Bart