isaac weathers
isaac weathers

Reputation: 1472

Change ID reference to this so that the function an be used on another div in jQuery

I have a function that is bound to an ID right now and want to have it be used on different ID's as well without having to rewrite the function for each ID. Would I use 'this' to do that?

Current:

$('#myID .myClass').swipe({
    swipeStatus : swipeStatus,
    allowPageScroll:"vertical"
});

Would this work:

$((this)+'.manage-accounts-account-name').swipe({
    swipeStatus : swipeStatus,
    allowPageScroll:"vertical"
});

Upvotes: 0

Views: 56

Answers (3)

Alexander
Alexander

Reputation: 23537

Set the same class name to all the elements and initialize them from it. For example, using a class name swippable.

<div id="myID" class="swippable">...</div>
<div id="anotherID" class="swippable">...</div>
...

$(".swippable").swipe({
    swipeStatus : swipeStatus,
    allowPageScroll: "vertical"
});

Upvotes: 2

Kevin B
Kevin B

Reputation: 95017

Pass this as the context.

$('.manage-accounts-account-name',this)

the above will select all $('.manage-accounts-account-name') that are contained within $(this)

alternatively, you could also do it like this:

$(this).find('.manage-accounts-account-name')

Upvotes: 0

Mat&#237;as C&#225;nepa
Mat&#237;as C&#225;nepa

Reputation: 5974

Go simple:

function doSomething(selector)
{
    $(selector).swipe({
        swipeStatus : swipeStatus,
        allowPageScroll:"vertical"
    });
}

Then you can do:

doSomething("#myID .myClass");
doSomething(".other_selector");

Upvotes: 0

Related Questions