tags:

views:

57

answers:

2
<span class='act_inact active'>Active</span><span class='act_inact inactive'>Inactive</span>

When I click .active it should become hidden and .inactive should be come visible and vice verca. As these are classes, there are many on the page.

$('.act_inact').click(function() {          
   $(this).toggle();
   $(this).closest('.act_inact').toggle(); 
  });

This does nothing but I don't quite know why? I'd prefer using closest() to avoid having to use next() and prev().

+2  A: 

You're misunderstanding the closest method.

The closest method will return the element's closest parent element that meets the condition. For example, $('td').closest('table') will return the table that directly contains the td. (If the table is inside another table, it will return the innermost one)

You can use the nextAll or prevAll methods along with the :first selector to find the closest element after or before your element, or you can use the siblings method to find all of the element's siblings, but I don't think there's a simple way to find the nearest sibling.

I would recommend that you nest all togglable pairs inside of separate elements, like this:

<div class="Togglable">
    <span class="Active">Hello!</span>
    <span class="Inactive">Goodbye!</span>
</div>

You can then write

$('.Togglable span').click(function() {                          
    $(this).parent().children().toggle(); 
});
SLaks
Ah indeed, thanks for that
stef
siblings() is what I wanted, thanks
stef
A: 
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
    <title></title>
    <script src="jquery-1.3.2.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function() {
            $("span.adjSpan").toggle(function() {
                $("span.active").hide();
                $("span.inactive").show();
            }, function() {
                $("span.inactive").hide();
                $("span.active").show();
            });
        });
    </script>
    <style type="text/css">
        .active {
            display: block;
        }

        .inactive {
            display: none;
        }

        .adjSpan { }
    </style>
</head>
<body>
    <span class='adjSpan active'>Active</span><span class='adjSpan inactive'>Inactive</span>
</body>
</html>
Colour Blend