Upgrade a show/hide toggle to use jQuery/Ajax

A friend of mine – Auke – is building a web application. The user has a secondary level of navigation that she
can show/hide at any time.

The app doesn’t include any javascript yet so clicking ‘Show Navigation’ currently reloads the page.
Auke rightly feels that this is a clunky solution and makes testing difficult. Here’s how to switch it around.

Before

1
2
3
4
5
6
7
8
9
<% if navigation_should_be_shown? %>
  <div id="navigation">
    <!-- Some links and stuff -->
  </div>

  <a href="/toggle-me-baby">Hide Navigation</a>
<% else %>
  <a href="/toggle-me-baby">Show Navigation</a>
<% end %>

After

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<head>
.....
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>

  <script type="text/javascript">
    function updateToggleText() {
      if ($("#navigation").is(":visible")) {
        $("#toggle").text("Hide Navigation");
      } else {
        $("#toggle").text("Show Navigation");
      }
    }
    
    $(document).ready(function() {
      $("#toggle").click(function() {
        $.post({url:  "/toggle-me-baby", function(response) {
          if (response == 'toggled!') {
            $("#navigation").toggle();
    
            updateToggleText();
          } else {
            alert("There was a problem toggling the navigation!");
          }
        });
      });
    });
  </script>
  
.......
</head>

<!-- Replacing the code from above -->
<% if navigation_should_be_shown? %>
  <div id="navigation">
    <!-- Some links and stuff -->
  </div>

  <a id="toggle" href="/toggle-me-baby">Hide Navigation</a>
<% else %>
  <div id="navigation" style="display:none">
    <!-- Some links and stuff -->
  </div>

  <a id="toggle" href="/toggle-me-baby">Show Navigation</a>
<% end %>

I haven’t tested this yet but it should do the trick. :)

Gustav