Somebody
Somebody

Reputation: 9645

jQuery: Clone event(s) from one element to another

Is it possible to clone event from one element, to another.

For example:

$('.somelink').click({data:data},somefunc);

I need event in another place in document for element with different class.

Upvotes: 0

Views: 2090

Answers (4)

Billy Moon
Billy Moon

Reputation: 58531

To copy it, you can do:

$('.somelink').click( $('.otherlink').attr('onclick') );

Upvotes: 0

gen_Eric
gen_Eric

Reputation: 227270

Extending on @moe's answer. Use .live() to bind events to elements even if they are not in the DOM. They will be bound as soon as they exist.

$('.somelink, .some-otherlink, #third-id').live('click',{data:data},somefunc);

Upvotes: 0

moe
moe

Reputation: 29704

You can pass multiple selectors to $(), separating them by comma. Like this:

$('.somelink, .some-otherlink, #third-id').live('click', {data:data}, somefunc);

Now they all share the same click event

Upvotes: 3

beeglebug
beeglebug

Reputation: 3542

The jQuery .clone() function has an optional withDataAndEvents argument which will copy the node itself, all attached events and any inline data.

See http://api.jquery.com/clone/ for more details.

Upvotes: 0

Related Questions