Search code examples
jquerytoggleparentchildrentoggleclass

parent().children() and toggle not working


I have the following HTML:

<div class="connections">
    <h2>Grads that share your interests</h2>
        <div id="connections_nav" class="collapse">
            <ul>
            <li><h3><a href="">Sally Struthers </a></h3><p>Class of 2008</p></li> 
                <li><h3><a href="">Sally Struthers </a></h3><p>Class of 2008</p>
                                </li>
            <li><h3><a href="">Sally Struthers </a></h3><p>Class of 2008</p>
                                </li> 
            </ul>
        </div>
</div> 

And the following CSS:

.connections h2 {
    background-image: url(images/show.gif);
    background-position: 0px;
    background-repeat: no-repeat;
    color: #660a11;
    font-size: 13px;
    font-weight: bold;
    margin: 0px 0px .4em;
    padding: 0px 0px 0px 25px; }

.connections .hide h2 {
    background-image: url(images/hide.gif);
    background-position: 0px;
    background-repeat: no-repeat; }

.connections h2.over {
    background-image: url(images/hover-show.gif);
    background-position: 0px;
    background-repeat: no-repeat; }

.connections .hide h2.over {
    background-image: url(images/hover-hide.gif);
    background-position: 0px;
    background-repeat: no-repeat; }

With the following jQuery:

$(document).ready(function() {

$('.connections h2').click(function() {
    $(this).parent().children('.collapse').toggle('slow');
    $(this).toggleClass('hide');
});

$('.connections h2').hover( 
    function() {
        $(this).toggleClass('over');
      },
      function () {
        $(this).toggleClass('over');
});

});

What happens is the entire div disappears. When I take out the $(this).toggleClass('hide'); code, the collapse div properly collapses (but the 'hide' class which shows a closed triangle image isn't applied, obviously). Why is that?


Solution

  • The line $(this).toggleClass('hide') changes <h2></h2> to <h2 class="hide"></h2>.

    Therefore, the correct CSS selectors should be:

    .connections h2.hide {}
    .connections h2.hide.over {}
    

    Working example: http://jsfiddle.net/PTnXU/

    Your original selector, .connections .hide h2.over, would have been good if you had another element between the <div> and the <h2>, for example:

    <div class="connections">
      <div class="hide">
        <h2 class="over"></h2>
      </div>
    </div>