MultiDev
MultiDev

Reputation: 10649

jQuery: Passing element ID as part of function

Hopefully I am wording this correctly...

I am trying to pass an element id as an option in a jquery function:

        $('.carousel').createcarousel({
        theid: $(this).attr('id'), // this is the part I am trying to get working
        delay: 150,
        fade:300,
        slide: 700,
        effect:'slide',                   
        orientation:'horizontal',
        loop: false,
        autoplay: false     });

Within the function itself, the options are defined as o, so I can do something like:

alert(o.fade);

And it will display an alert showing "300". However, if I do:

alert(o.theid);

It says undefined. Why?

Upvotes: 3

Views: 3434

Answers (2)

Stefan
Stefan

Reputation: 14863

this isn't your object in your contect. I guess your .carousel classes each have an I'd and you want to assign it to the theid argument. However, in the object you are creating the context (this argument) doesn't match to your jQuery element, it matches to your function, where you create the caruses. So the jQUery object you are creating, wrappes an empty HTML element and has no id. Therefor it is set as undefined.

I think this will acomplish what you are trying to do:

$('.carousel').each(function() {
    $(this).createcarousel({
            //theid: $(this).attr('id'),                 
            theid: this.id,  //thanks jtheman
            delay: 150,
            fade:300,
            slide: 700,
            effect:'slide',                   
            orientation:'horizontal',
            loop: false,
            autoplay: false     });
});

This will iterate over all your carousel classes, set the this context correctly and apply the createcarousel function.

Upvotes: 2

Lunfel
Lunfel

Reputation: 2677

theid: $(this).attr('id')

In this context, $(this) refers to the carousel object which is not an html object.

Check out the jquery apply function. You can specify the context of a function call

http://api.jquery.com/Types/?rdfrom=http%3A%2F%2Fdocs.jquery.com%2Fmw%2Findex.php%3Ftitle%3DTypes%26redirect%3Dno#Context.2C_Call_and_Apply

scroll to "Context, Call and Apply"

Hope this helps out


Considering the comment you made on the other answer :

You don't need to pass the id then! try this :

$(".carousel").click(function(event){ 
    alert(event.target.attr("id")); 
}); 

event.target represents the html object which was clicked

This should work out

Upvotes: 0

Related Questions