3

I'm trying to remove a class from a HTML tag along with adding a new one and also doing some other magic.

Right now I just have a procedure style coding going on... which I know there's another way of doing it. Like creating a function within another function? I'm not sure what it's called and sometimes when trying to do it, it never worked so I went down procedure style type but I figured I post on here and maybe someone can explain to me on how jQuery works? Right now I have like

$(this).removeClass("theClass");
$(this).addClass("theClass");
$(this).slideDown();

I think I can do something like

$(this).removeClass("theClass", function(){
  // other goodness?
});

Thanks everyone. Sorry if i don't make sense.

1
  • try this.. $(this).removeClass("yourclassname").addClass("classnametochange"); Commented Jul 5, 2010 at 0:22

3 Answers 3

5

I think what you're looking for is call chaining - since .removeClass returns a jQuery object itself, you can call .addClass directly on the returned object, like so:

$(this).removeClass("classA").addClass("classB").slideDown();

Some animations also take functions called callbacks as arguments; these functions specify actions to take after the animation is complete. For example:

$(this).fadeOut("slow", function() {
    // Callback function - called after fade is done
    alert("fade complete");
});
Sign up to request clarification or add additional context in comments.

Comments

2

You can do this:

$(this).removeClass("theClass").addClass("theNewClass").slideDown();

You can read more about chaining here.

Comments

2

It depends what you want to achieve. If you just want to do these three operations in sequence you can use chaining as mentioned above. In case you want to execute some of operations when slideDown finishes its animation, you can do it like this:

var that = this;
$(this).removeClass("theClass").sildeDown(function() {
  $(that).addClass("theClass");
});

It will remove the class from element, slide it down and after slide is finished it will add the class again. Use of that variable is necessary as inside the callback anonymous function this keyword can refer to something else than your DOM element. Hope that helps!

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.