jQuery tricks: hiding body elements

Beatnik on 2008-04-22T17:37:04

Someone gestured me towards jQuery recently. I've been playing around with it a bit. Yesterday I got the following idea: allow the visitor to minimize the fancy logos and just show the important stuff. I had the following:




The background was the element I wanted to hide. I ended up with something like this:




[-]

This adds a small [-] link that, when clicked, clears the background and changes to a [+]. Clicking again switches back.


css classes?

phaylon on 2008-04-22T20:37:46

Wouldn't switching the body's css class also work and make it all more maintainable? :)

Re:css classes?

Beatnik on 2008-04-22T21:00:43

Yes, ofcourse it would.. It's one of those TIMTOWTDI thingies :)

Re:css classes?

Aristotle on 2008-04-23T04:29:43

It’s not TMTOWTDI… it’s a matter of, as Larry likes to say, baby talk. What you did is a way to do it, but really it’s not a very good way. Switching the body class is one thing you should really do; the other is unobtrusive scripting. Another thing is that you want to hide these links from people who don’t have Javascript in the first place.

Consider:

<style type="text/css">
body { /* ... */ }
body.with-bg { /* ... */ }
#toggle-bg b { font-weight: normal }
body.with-bg #toggle-bg .plus  { display: none }
body.with-bg #toggle-bg .minus { display: inline }
body         #toggle-bg .minus { display: none }
</style>

<script type="text/javascript" language="javascript"
src="http://jqueryjs.googlecode.com/files/jquery-1.2.3.mi n.js"></script>
<script type="text/javascript">
jQuery( function() {
    $('#toggle-bg')
        .append( '<a href="#"><b class="plus">[+]</b><b class="minus">[-]</b></a>' )
        .find( 'a' )
        .click( function() { $('body').toggleClass('with-bg'); return false } );
} );
</script>

<body class="with-bg">
<div id="toggle-bg"></div>
</body>

Re:css classes?

Aristotle on 2008-04-23T04:31:33

Err, s/jQuery/\$/.

Re:css classes?

phaylon on 2008-04-23T16:29:14

I can still remember those ugly times of NN4, where we still had to assume people who don't have JS on, might also have CSS off. The days really got better in this regard.