mare
mare

Reputation: 13083

How do I programmatically show and hide a DIV by clicking on a link?

1) How to programatically (without writing the onclick="javascript:.." attribute) attach JavaScript (jQuery) function to the link below?

2) The simplest way to toggle hide/unhide after clicking on the Statement link? First click should display the DIV (unhide), the second click should hide it and so forth.

<a>Statement</a>
<div id="taxStatement">insert select statement dropdownbox</div>

Upvotes: 0

Views: 5805

Answers (3)

kennytm
kennytm

Reputation: 523524

   var theDiv = $('#taxStatement');

   theDiv.hide();
// make the div hidden by default.

   theDiv.prev('a').click(function(){ theDiv.toggle(); });
// ^^^^^^^^^^^^^^^^^^^^^^             ^^^^^^^^^^^^^^^^
// Attach the onclick                 hide & unhide.
//  assume the <a> is 
//  immediately before that <div>.
// It may be better to give an
//  id to that <a>.

Upvotes: 0

JasCav
JasCav

Reputation: 34652

For Question 1 and 2, you'll want to use toggle:

$('a').toggle(
function () {
  // Unhide Statement
  $('#taxStatement').show();
},
function () {
  $('#taxStatement').hide();
});

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630569

You can give the link a class, for example:

<a class="toggle" href="#">Statement</a>
<div id="taxStatement">insert select statement dropdownbox</div>

Then attach script on document.ready with .click() and .toggle() the element, like this:

$(function() {
  $("a.toggle").click(function(e) {
    $(this).next().toggle();
    e.preventDefault();
  });
});

You can initially hide the <div> in multiple ways, CSS:

#taxStatement { display: none; }

Or give it a class, e.g. class="toggleDiv" and hide them all the same way:

.toggleDiv { display: none; }

Or also in your document.ready, via script:

$(".toggleDiv").hide();

You can give it a try/experiment here.

Upvotes: 3

Related Questions