views:

71

answers:

2

Check out my example here: http://timkjaerlange.com/foobar/test.html

I'm currently trying to apply a class to a header based on the visibility of a div on the page.

This is my markup:

<a href="#">Toggle visibility!</a>

<div></div>

<h1 class="one">If the box is hidden this headline should be italic.</h1>
<h1 class="two">If the box is visible this headline should be italic.</h1>

And these are the classes that are in play:

.hideIt {
 display: none;
        }

.ifHidden {
 font-style: italic;
        }

.ifVisible {
 font-weight: italic;
        }

jQuery adds the behaviour:

$('a').click(function() {
 $('div').toggleClass('hideIt');
 if ( $('div').is(':hidden') ) {
  $('h1.one').addClass('ifHidden');
  $('h1.one').removeClass('ifVisible')
  }
 if ( $('div').is(':visible') ) {
  $('h1.two').addClass('ifVisible');
  $('h1.two').removeClass('ifHidden');
  }
});

Initially it works, when I click the anchor, h1.one is italized, however when I click again nothing happens. I'm somewhat of a Javascript, jQuery n00b, so any hint of what could be wrong is highly appreciated!

A: 

font-weight in .ifVisible has an incorrect value so won't change anything.Try here for allowed values

Ian Devlin
+1  A: 

There are a couple of problems. Firstly:

.ifVisible {
   font-weight: italic;
}

Italic is not a valid value for font-weight. It is for font-style.

Secondly, your logic is a little weird. If div is hidden you add ifHidden and remove ifVisible from h1.one. If div is visible you add ifVisible and remove ifHidden from h1.two. Thing is you never add the class you're removing. I'm not sure you're doing what you're intending.

cletus
Fixed the CSS thing and changed the jQuery to the following:$('a').click(function() { $('div').toggleClass('hideIt'); if ( $('div').is(':hidden') ) { $('h1.one').addClass('ifHidden'); $('h1.two').removeClass('ifVisible'); } if ( $('div').is(':visible') ) { $('h1.two').addClass('ifVisible'); $('h1.one').removeClass('ifHidden'); } });Works now, thanks for helping me out!
timkl