Pim Peters
Pim Peters

Reputation: 43

jQuery if statement to change CSS

This code is about pressing the button which makes the text toggle (show/hide):

jQuery('Button']').click(function () {
    jQuery('#text').slideToggle('fast', function () {});      
    if (jQuery('#text').css('display') == 'block') {
        jQuery('#dropdown1arrow').css({"border-top":"0px"});
        jQuery('#dropdown1arrow').css({"border-bottom":"7px solid #0767B1"});            
       }
    if (jQuery('#text').css('display') == 'none') {
        jQuery('#dropdown1arrow').css({"border-bottom":"0px"});
        jQuery('#dropdown1arrow').css({"border-top":"7px solid #0767B1"});        
       }    
});

Everything works except the display:none, anyone got any idea why/how to fix this?

Upvotes: 0

Views: 488

Answers (3)

Karl-André Gagnon
Karl-André Gagnon

Reputation: 33880

You can try this :

jQuery('button').click(function () {
    jQuery('#dropdown1arrow').css(jQuery('#text').is(":visible") ? 
                  {"border-top":"0px", "border-bottom":"7px solid #0767B1"} :
                  {"border-bottom":"0px", "border-top":"7px solid #0767B1"}
                 );
});

Upvotes: 0

yoavmatchulsky
yoavmatchulsky

Reputation: 2960

Some improvments:

  • Use .is(':visible') to check if the element is visible
  • Move the if statement inside the callback function of slideToggle()
  • Merge the two css calls into a single call
  • You have a typo in the first row - 'Button']'

Code:

jQuery('Button').click(function () {
  jQuery('#text').slideToggle('fast', function () {
    text_obj = $(this)
    if (text_obj.is(':visible')) {
      jQuery('#dropdown1arrow').css({"border-top":"0px", "border-bottom":"7px solid #0767B1"});
    }
    else {
      jQuery('#dropdown1arrow').css({"border-bottom":"0px", "border-top":"7px solid #0767B1"});
    }
  });
});

Upvotes: 0

Jon
Jon

Reputation: 437734

Test instead if the element is visible:

if (jQuery('#text').is(":visible")) {
    // something
}
else {
    // something else
}

Upvotes: 3

Related Questions