Basic Show and Hide

As promised in my last entry, I'll be showing you a simple effect that you can do using jQuery: showing or hiding something, or a group of things, on the page. The two functions that let us do this are, not surprisingly, show() and hide().

jQuery also comes with another function called toggle(), which will make matching elements visible if they are hidden or hidden if they are visible.

So, let's get down to business. We're going to start with our $(document).ready() function.

[js]$(document).ready(function() { // we'll put our code here });[/js]

Next, we'll choose what we want to show or hide. Hmm, let's see. How about the site's title? Excellent! Now, whenever we refer to an element in jQuery, we start with the dollar sign, $, and we put any CSS or XPATH selector in parentheses right after it:


Since the site's title is wrapped in an <h1> tag, we'll refer to it this way: $('h1'). We could just as easily refer to all DIVs with a class of "treacle" — $('div.treacle') — or any paragraph that is a chlid of a DIV with an ID of "bonespur" — $('#bonespur > p').

Now for the magic. To make the site's title disappear, we just connect $('h1') and hide() with a dot (.) and stick it all inside the $(document).ready() like so:

[js]$(document).ready(function() { $('h1').hide(); });[/js]

The code above will make the site's title hide when the DOM / page loads, which isn't ideal for our purposes here, so I'm going to attach the the hide() event to the first button below instead. The second and third buttons will handle show() and toggle() respectively.

Just for kicks, we'll show and hide this sentence, which is wrapped in a div with class="showhide", too.

How did I attach the hiding and showing to those buttons? I'll show you that in my next entry.

Responsive Menu
Add more content here...