tags:

views:

385

answers:

2

I am doing slideToggle as follows:

$(document).ready(function(){    
        $("#show_morecats").click(function(){
     $("#morecats").slideToggle("slow");
     $("#show_morecats").css("background-color","#399C05");
    });
});

HTML

<a href="#" id="show_morecats">More</a>
<div id="morecats" style="display:none;">Some text</div>

Now I want when I click More link then morecats div will open with a slide effect and the color of more link will be red and when again click on more link then it will be closed and color of link will be blue.

SlideToggle is working quite fine, but coloring of link is not working correctly. I dont want to put :visible condition, because I know there is a function in jquery which does the same, toggle your div and same time will toggle the class or css of the main element, but what that exact function and how to use it. I googled about it but didn't get anything.

Can anyone please suggest me the shortest way to solve this toggling problem.

+1  A: 

I think what you mean is you want to change the background colour once the animation has completed? That's what the callback argument is for in slideToggle.

Change the second line to:

$('#morecats').slideToggle('slow',
    function() { $('#show_morecats').css({ backgroundColor: '#399C05' });
});

You can also use the toggleClass() method, though the way you've phrased your question is a little confusing, if I'm honest.

Will Morgan
+2  A: 

the best way to accomplish the color change when opened and then back to blue when closed, is with a custom class... this way you can toggle the class...

jQuery:

$(document).ready(function(){
    $('#show_morecats').bind('click', function(){
        $('#morecats').slideToggle('slow', function() { 
      $('#show_morecats').toggleClass("opened");
     });
    });
});

HTML:

<a href="#" id="show_morecats">More</a> 
<div id="morecats" style="display:none;">Some text</div>

CSS:

#show_morecats { color: blue; }
#show_morecats.opened { color: red; }
Sander
Yes, that's the method `toggleClass`, thanks, +1 :)
Prashant