Paulius K. Paulius K. - 1 year ago 118
CSS Question

How to change expand div after click and collapse it after another click?

I have an explandable/collapsible element that I created using Simple-expand
(A jQuery plug-in to expand/collapse elements).

What I want to do is change the css of the element when user clicks on it, expanding it ,and change it again when user clicks on it again ,collapsing it.

Problem is, I don't know how to do that. I know how to change class on click, but how can I change the CSS after the user "unclicked" this tab and it shrinked up?

EDIT: Thanks to George for correcting me on what I wanted to do, to be more clear. I was a bit tired, so I needed it fast. I know this is really bad excuse, but I fully understand and respect you guys, who gave me negative feedback.

Basically what I needed, is:

  • There's 6 different divs;

  • When you click on one div, it will expand;

  • When you click on another div, it will check if ANY OF THESE divs are EXPANDED, if YES - close (collapse) them, and open that div which I clicked on.

For that simple task (it's really simple, it's just me being stupid) I needed to use jQuery
statement and a few if's.

I found a solution after 15 mins after publishing this post here and I wanted to delete it, unfortunately, I can't, because it has answers.

Thanks to everyone who tried to help me, I appreciate your help.


Answer Source

Just use a class for when the element is expanded and toggleClass() to toggle the class on click

$( ".your_element" ).click(function() {
  $( this ).toggleClass( "expanded" );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download