Toggle content with jQuery; show/hide a block

Estimated reading time of this article: 0 minutes 48 seconds

Do you want to show and hide content? Thus, toggle the content?

Here's an simple way doing it with jQuery. This is really a basic example, e.g. the link could be replaced by a button.

The toggle of the text could also be omitted and you could write "Show/hide Example".

Example

Show Example

Code

<a id="show-example" onclick="false">Show Example</a>

<div id="example" style="display: none">Example block</div>

<script>
    (function ($) {
          $(document).ready(function() {
          $("#show-example").click(function () {
             if ($('#example').is(":visible")) {
                 $(this).html($(this).html().replace(/Hide/, 'Show'));
             } else {
                 $(this).html($(this).html().replace(/Show/, 'Hide'));
             }
             // Do it afterwards as the operation is async
             $("#example").slideToggle("slow");
          });
      });
  })(jQuery);
</script>

In case of Drupal, you should use the Drupal.behaviors instead of $(document).ready(function() {

  Drupal.behaviors.toggle = {
    attach: function (context, settings) {
      [inner of "$(document).ready(function() {" comes here]
    }
  };