0

Sorry for the subject line, but I wasn't sure how exactly to phrase it. I'd like to automate this to a function $('#progress-row-1 .indicator).css('width', 100); the following way:

setWidth($('#progress-row-1'), 100);

So I only pass the ID of the element to the function. The element has only one child with a class called ".indicator". So...

In the function, I'd like to set the CSS width of the element who has a class named "indicator":

function setWidth(obj, size) {
    $('obj .indicator').css('width', size);
}

I know the $('obj .indicator') syntax is wrong, but I don't know what is the correct one. How would I access the passed object's child who has a class named ".indicator" such way? Can anyone help me out? Thank you!

3 Answers 3

3

Turning it into a plugin method:

$.fn.setIndicatorWidth=function(width){
    return this.each(function(){
        $(this).find('.indicator').width(width);
    });
}

Useage:

$('#progress-row-1').setIndicatorWidth(100);
Sign up to request clarification or add additional context in comments.

6 Comments

bruv ++1 Yes please .width. :)
I like it, however, for the sake of argument, isn't this functionality a bit narrow in scope for a plugin? Genuinely curious about people's opinions on that.
@BLSully why too narrow, it keep's code readable in jQuery syntax and is chainable
@charlietfl: Admittedly I don't know what the OP is trying to achieve, but this seems like something that either should be packaged at a higher level as a widget (theory is the end result here is a progress bar based on the id/class names), or is too infrequently used to hardcode things like the class-name inside the function.
@BLSully really not sure what you are suggesting. OP wants a function separated from the call, so likely plans on reusing it so plugin makes as much sense as regular function
|
2

The most concise syntax (and I believe fastest) solution for that would be:

$('.indicator', obj).css('width', size);

Comments

1

Use .find()

obj.find(".indicator").css('width', size);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.