Michael Schwartz
Michael Schwartz

Reputation: 8415

JQuery - Change Element's CSS When Hidden/Visible

I have a div toggle when an anchor is clicked. I'm trying to change an icon via class when the div is visible, and when it's hidden, but the code's not working.

Does anyone know how to do this?

// Toggle design/code
$(".design-n-code").click(function(e) {
    code.toggle();
}); code.hide();

// Handles the icon so users know it's active when code is visible.
if (code.is(':visible')) {
    $(this).addClass('code-active');
} else {
    $(this).removeClass('code-active');
}

Upvotes: 0

Views: 192

Answers (3)

ComFreek
ComFreek

Reputation: 29424

You have to put the logic for checking the visiblity into the click handler. Otherwise, it will only execute once, and that is at the overall beginning of the script execution.

// Toggle design/code
$(".design-n-code").click(function() {
    code.toggle();

    // Handles the icon so users know it's active when code is visible.
    if (code.is(':visible')) {
      $(this).addClass('code-active');
    } else {
      $(this).removeClass('code-active');
    }
});
code.hide();

Upvotes: 2

aztechy
aztechy

Reputation: 640

You say you have an anchor which when clicked, toggles another element, a div. The use of 'this' when clicked won't change the other element's class then.

You would want something like this:

HTML

<a href="#" id="toggler">CLick me to toggle the other div</a> 
<div id="toBeToggled" class="IsShown">I have class abc</div>

JS

    $('#toggler').click(function() {
        var target = $('#toBeToggled');
        if (target.is(":visible")) {
            target.addClass('IsHidden').removeClass('IsShown');
            target.hide();
            // Demo purposes
            console.log(target.attr('class'));
        } else {
            target.addClass('IsShown').removeClass('IsHidden');
            target.show();
            // Demo purposes
            console.log(target.attr('class'));
        }
    });

JS FIDDLE EXAMPLE

Upvotes: 0

Michel
Michel

Reputation: 28269

The test for the visibility of the code should be in the handler. In the handler, this is referring to the clicked element, so you must call addClass / removeClass to the element #icon-id instead (adapt #icon-id to your proper id).

// Toggle design/code
$(".design-n-code").click(function(e) {
    code.toggle();

    // Handles the icon so users know it's active when code is visible.
    if (code.is(':visible')) {
      $('#icon-id').addClass('code-active');
    } else {
      $('#icon-id').removeClass('code-active');
    }
});
code.hide();

Upvotes: 1

Related Questions