1
function classChanger(path,changeClass,duration){
    $(path).removeClass(changeClass);
    $(this).addClass(changeClass);
)};

$('.flightDetails .option').classChanger('.flightDetails .option','selected',300);

I am trying to create reusable function. Console log: TypeError: $(".flightDetails .option").classChanger is not a function

Appreciate your help and time :)

1 Answer 1

5

You have to declare your classChanger on the jQuery prototype:

$.fn.classChanger = function(path, changeClass, duration) {
    $(path).removeClass(changeClass);
    return this.addClass(changeClass);
};

For more info, read the jQuery Plugin Authoring Guide.


Update: As pointed out in the comments, if you intend for path and the selector to always be identical, you should forgo path completely, and just use this throughout.

Since you haven't specified exactly what it is you're trying to do, I'm assuming you want to remove the class, then wait for the duration specified and then re-add the class. If that's the case, here's some sample code:

$.fn.classChanger = function(changeClass, duration) {
    var $this = this;

    setTimeout(function() {
        $this.addClass(changeClass);
    }, duration);

    return this.removeClass(changeClass);
};

$('.flightDetails .option').classChanger('selected', 300);

Here's the fiddle: http://jsfiddle.net/ur7SN/

Sign up to request clarification or add additional context in comments.

6 Comments

Why not just use remove the path argument entirely and use this instead of rebuilding an identical jQuery object with $(path)? (Admittedly, the OP doesn't say if path should ever differ from the selector, but I've got a strong hunch they're always the same.)
@apsillers - Because the OP has not specified what he's trying to achieve here. In his example, he's using identical selectors, but that might not always be the case.
True enough. Personally, I'd provide it as an addendum to the answer ("if you intend that path and the selector should always be identical...", but I suppose my comment is addendum enough. (In any case, +1.)
@apsillers - If it's always the same, then this piece of code does absolutely nothing. It first removes the class, then adds it back in...
True! I concede that original suspicion is becoming increasingly less likely. Perhaps, though, this is an incomplete implementation, considering the unused duration argument. My advice here is absolutely based on nothing but speculation.
|

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.