Simple jQuery show / hide script

I know, I know..  this is a really simple process for those of you who have had more than an hour with jQuery.  But this article’s intention is to show just how quickly and how easily you can utilize jQuery’s robust features that make it so easy and fun to use.

So I am going to keep the explanation short and sweet. I think the code speaks for itself for the most part.

$(document).ready(function(){... does as you would think. Waits for the document to fully load.

$('.hide').hide; finds all elements with the “hide” classname and actually hides them. I am using this as opposed to hiding the elements via css so that those with javascript turned off will see the elements that are hidden. If I used css to hide the elements, then anyone with javascript turned off but have a css capable browser, would have a dysfunctional experience. Hiding elements via javascript ensures that those without javascript will still be able to see the hidden paragraph. nuf said, I think

From there, we are finding #link1 and adding a toggle when clicking. I love this because I dont have to find out the toggle status myself. I just add the two different toggle scenarios, separated by a comma, and I am good to go.

$(this).next() is how I get to the element I want to change. In this case, it is the node / element below the link that has been clicked. I kept the traversal code generic so I could use this anywhere. The only worry I have, is to make sure that the element to show / hide is precisely below the link which it relates to. This simple technique makes the code re-usable.

Next, I am using another of jQuery’s strengths by “chaining” my code to run on click. I do this by using dot for each new behavior I am passing.

.slideDown('slow').removeClass('hide').preventDefault; does three things:

  • gives the element a slide down effect when showing
  • removes the hide class from the element
  • prevents the default behavior of the link

and that’s it!

JQuery uses very simple and familiar syntax for CSS developers and it uses techniques that make it much easier to focus on what you want the page to do as opposed to figuring out how to make it work.

Example:

Show

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.