Skip to main content
April 1, 2026Dan Rodney/8 min read

Introduction to jQuery: Showing & Hiding Content

Master jQuery fundamentals with interactive show hide effects

Why jQuery Matters for Developers

Write Less, Do More

jQuery's industry-standard philosophy means leveraging pre-written JavaScript code instead of building from scratch. This dramatically reduces development time and complexity.

Industry Standard

As an established JavaScript library, jQuery provides battle-tested solutions that thousands of developers rely on daily for professional web development.

Animation Made Simple

Complex animations that would require extensive vanilla JavaScript can be achieved with single jQuery method calls like slideToggle().

Topics Covered in This JavaScript & jQuery Tutorial:

Getting Started with jQuery, Running Code When the Document is Ready, Click Events, Using jQuery's SlideToggle() Method

Exercise Preview

show hide basic

Exercise Overview

jQuery remains one of the most influential JavaScript libraries in web development history. Known for its motto "Write Less, Do More," jQuery revolutionized how developers interact with the DOM by providing a simplified, intuitive API that abstracts complex vanilla JavaScript operations. While modern frameworks like React and Vue have shifted the landscape, understanding jQuery is essential for maintaining legacy codebases and grasping foundational web development concepts. In this exercise, you'll master jQuery fundamentals by building interactive show/hide functionality with smooth animations—skills that translate directly to modern development practices.

Prerequisites Check

Before starting this exercise, ensure you have a code editor installed and can preview HTML files in a browser. You'll be working with the Show-Hide-Basic folder from the provided class files.

Getting Started

  1. Launch your preferred code editor and ensure you have a clean workspace.
  2. Close any previously opened files to maintain focus on this exercise.
  3. Navigate to the Show-Hide-Basic folder located in Desktop > Class Files > yourname-JavaScript jQuery Class. For optimal workflow, open this entire folder in your code editor if it supports project-based navigation (such as Visual Studio Code, Sublime Text, or Atom).
  4. Open the index.html file from the Show-Hide-Basic folder.
  5. Launch index.html in your browser to examine the current state of the application.
  6. Examine the Contact button positioned in the top right corner of the interface.

    Currently, there's a hidden contact div containing contact information that's been concealed using CSS. Our objective is to create an interactive experience where clicking the Contact button reveals this hidden content using jQuery's powerful DOM manipulation capabilities.

  7. Keep the browser tab open for testing purposes as we'll be iterating on our code.
  8. Return to the index.html file in your code editor to begin implementation.
  9. Before leveraging jQuery's functionality, we must include its library file. Locate the closing </body> tag around line 70 and add the following script reference:

    </div>
       <script src="js/jquery-2.1.0.min.js"></script>
    </body>

    NOTE: While jQuery.com offers the latest versions and comprehensive documentation, we're using a locally hosted version for this exercise to ensure consistent performance and eliminate external dependencies. In production environments, you might choose to use a Content Delivery Network (CDN) for improved caching and global distribution, though many modern applications have moved toward native JavaScript or newer frameworks.

    Project Setup Workflow

    1

    Open Project Files

    Navigate to Desktop > Class Files > yourname-JavaScript jQuery Class and locate the Show-Hide-Basic folder. Open this folder in your code editor.

    2

    Preview Initial State

    Open index.html in your browser to see the Contact button. Note that the contact div is hidden by CSS and will be revealed through jQuery.

    3

    Link jQuery Library

    Add the jQuery script tag before the closing body tag to enable jQuery functionality in your project.

Minified vs. Regular Version

We're linking to the minified version of jQuery, which is optimized for production use. This compressed file removes whitespace, comments, and shortens variable names to reduce file size and improve load times. Compare jQuery-2.1.0.min.js and jQuery-2.1.0.js to see how minification dramatically reduces file size while maintaining identical functionality.

  • The script tag we just added provides access to jQuery's extensive method library. All custom jQuery code must be placed after this library inclusion to ensure proper dependency loading. Add your custom script block below the jQuery reference:

    <script src="js/jquery-2.1.0.min.js"></script>
       <script>
    
       </script>
    </body>
  • Now that we have jQuery properly configured, let's explore how this powerful library transforms JavaScript development.

    jQuery File Versions Comparison

    FeatureMinified VersionRegular Version
    File SizeCompressedFull Size
    ReadabilityNot Human-ReadableHuman-Readable
    Load SpeedFaster DownloadSlower Download
    Use CaseProductionDevelopment/Learning
    Recommended: Use minified version (jquery-2.1.0.min.js) for faster page loading in production environments.

    Understanding the jQuery Library

    The term "query" refers to the act of searching or questioning, and jQuery excels at querying the Document Object Model (DOM) to locate elements and manipulate them efficiently. While vanilla JavaScript provides methods like getElementById() for simple selections and querySelectorAll() for more complex CSS selector-based searches, jQuery streamlines this process with its unified jQuery() function. This approach creates a consistent, intuitive API for DOM manipulation:

    jQuery('#wrapper'); // select the element with an ID of 'wrapper'
    jQuery('p');        // select all paragraphs on the page
    jQuery('ul li');    // select list items inside unordered lists
    jQuery('.special'); // select all elements with a class of 'special'

    Recognizing that typing "jQuery" repeatedly would be inefficient, the library provides the $ symbol as a convenient alias. This shorthand notation embodies jQuery's core philosophy of writing less code while accomplishing more. Throughout this tutorial, the $ symbol you'll see is simply a more concise reference to the jQuery function.

    Implementing Document Ready Functionality

    Timing is crucial in web development. JavaScript code that executes before the DOM is fully constructed will fail to find elements and throw errors. jQuery addresses this challenge with its ready event, which ensures code execution only occurs after the DOM structure is complete and safe to manipulate.

    While JavaScript's native window.onload event serves a similar purpose, jQuery's ready event offers superior performance. The onload event waits for all page resources—including images, stylesheets, and external content—to fully load. In contrast, jQuery's ready event fires as soon as the DOM structure is complete, enabling users to interact with your application significantly faster.

    1. Implement the document ready pattern with the following code:

      <script>
         $(document).ready(function() {
      
         });          
      </script>
    2. Save the file to preserve your progress.

    With our foundation in place, we can now implement interactive click functionality.

    Implementing Click Events

    1. Locate the anchor tag on line 13: <a href="#" id="navContact">.

      This element serves as our trigger for revealing the contact information. We'll use jQuery's event handling system to detect clicks and respond appropriately.

    2. Select the target element using jQuery's CSS selector syntax:

      $(document).ready(function() {
         $('#navContact')   
      });

      jQuery leverages familiar CSS selector syntax, making it intuitive for developers already comfortable with styling. Here we're targeting the element with the ID navContact.

    3. Attach a click event handler to monitor user interactions:

      $(document).ready(function() {
         $('#navContact').click();
      });
    4. Define the callback function that will execute when the click event occurs:

      $(document).ready(function() {
         $('#navContact').click(function() {});
      });

      NOTE: jQuery's event handling system requires a callback function that contains the code to execute when the event triggers. This function-based approach provides clean separation between event detection and event handling logic.

    5. Format the code for readability by adding proper line breaks within the function block:

      $(document).ready(function() {
         $('#navContact').click(function() {
      
         });
      });

      NOTE: The nested structure ending with }); is a common pattern in jQuery development, indicating proper closure of both the click handler function and the ready event handler.

    6. Add a simple test to verify the click event is functioning correctly:

      $(document).ready(function() {
         $('#navContact').click(function() {
            alert('You clicked');
         });
      });

      NOTE: jQuery seamlessly integrates with native JavaScript functions. This alert serves as a debugging tool to confirm our event handling is working before implementing more complex functionality.

    7. Save the file and refresh index.html in your browser.
    8. Click the Contact button to verify the alert appears with the message "You clicked".
    9. Dismiss the alert by clicking OK.
    10. Return to your code editor to implement the actual show/hide functionality.

    Now that we've confirmed our event handling works correctly, let's implement the core show/hide functionality.

    Implementing Click Event Handlers

    1

    Select Target Element

    Use jQuery selector $('#navContact') to target the element with ID navContact that users will click.

    2

    Attach Click Handler

    Chain the .click() method to create an event listener that responds to user clicks on the selected element.

    3

    Define Callback Function

    Add function() {} inside click() to specify what code should execute when the click event occurs.

    4

    Add Event Logic

    Place your desired functionality inside the callback function, such as showing/hiding elements or triggering animations.

    Implementing Show & Hide Functionality for Contact Information

    1. Replace the test alert with jQuery's show() method to reveal the contact information:

      $(document).ready(function() {
         $('#navContact').click(function() {
            $('#contact').show();
         });
      });

      jQuery's show() method is part of an extensive API containing hundreds of utility methods for DOM manipulation, animation, and AJAX operations. You can explore the complete method reference at api.jQuery.com for advanced functionality.

    2. Save your changes and refresh index.html in the browser.
    3. Click the Contact button to verify the Contact Info panel appears as expected.

      While this basic functionality works, a complete user experience requires the ability to close the contact information panel when it's no longer needed.

    4. Return to your code editor to implement the closing functionality.
    5. Locate the img tag with the ID closeBox around line 21.
    6. Implement a click handler for the close button using jQuery's hide() method:

      $(document).ready(function() {
         $('#navContact').click(function() {
            $('#contact').show();
         });
         $('#closeBox').click(function() {
            $('#contact').hide();
         });
      });
    7. Save your changes and refresh the browser to test the complete functionality.
    8. Click the Contact button to open the contact information panel.
    9. Click the close button (X icon) in the top-right corner to hide the panel. Excellent!
    10. Return to your code editor for further enhancement.
    11. Let's implement jQuery's toggle() method for more elegant functionality. Replace both show() and hide() with toggle():

      $(document).ready(function() {
         $('#navContact').click(function() {
            $('#contact').toggle();
         });
         $('#closeBox').click(function() {
            $('#contact').toggle();
         });
      });
    12. Save the file and refresh the browser to test the improved functionality.
    13. Click the Contact button and observe that the contact information still appears.
    14. Click the Contact button again to see the contact information disappear.

      The toggle() method intelligently switches between show and hide states, providing more flexible user interaction. Now users can use the same Contact button to both reveal and conceal the contact information.

    15. Switch back to your code editor for code optimization.
    16. Since both buttons now perform identical operations, we can consolidate them into a single, more maintainable handler. Remove the redundant #closeBox click method:

      $('#closeBox').click(function() {
         $('#contact').toggle();
      });
    17. jQuery supports CSS-style multiple selectors, allowing us to target multiple elements simultaneously. Update the remaining click handler:

      $(document).ready(function() {
         $('#navContact, #closeBox').click(function() {
            $('#contact').toggle();
         });
      });
    18. Save your changes and test the consolidated functionality in the browser.
    19. Verify that both the Contact and close buttons continue to work correctly for opening and closing the contact information panel.
    20. Return to your code editor for the final enhancement.
    21. Implement jQuery's slideToggle() method to add smooth animation effects:

      $(document).ready(function() {
         $('#navContact, #closeBox').click(function() {
            $('#contact').slideToggle();
         });
      });
    22. Save the file and refresh the browser for final testing.
    23. Click the Contact and close buttons to experience the smooth sliding animation as the contact information appears and disappears.

      This polished animation effect would require dozens of lines of vanilla JavaScript code to implement manually, demonstrating jQuery's power in simplifying complex UI interactions. The slideToggle() method automatically handles the mathematical calculations for smooth transitions, timing functions, and state management.

      NOTE: For reference implementation, you can examine the completed code in Desktop > Class Files > yourname-JavaScript jQuery Class > Done-Files > Show-Hide-Basic.

    Key Takeaways

    1jQuery is an industry-standard JavaScript library that follows the 'Write Less, Do More' philosophy, allowing developers to leverage pre-written code instead of building from scratch.
    2Always link to the jQuery library file before writing jQuery code, and use the minified version in production for faster loading times.
    3The dollar sign ($) serves as a convenient alias for the jQuery function, making code more concise and readable.
    4jQuery selectors use the same syntax as CSS selectors, making it easy to target elements by ID, class, tag, or complex combinations.
    5Wrap jQuery code in $(document).ready() to ensure the DOM is fully loaded before script execution, which is faster than window.onload.
    6jQuery event handlers like .click() provide a clean way to respond to user interactions with callback functions containing the desired functionality.
    7Animation methods like show(), hide(), toggle(), and slideToggle() provide varying levels of visual feedback, from instant changes to smooth animations.
    8Multiple selectors can be combined with commas to apply the same event handlers to different elements, reducing code duplication and improving maintainability.

    RELATED ARTICLES