Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide html div

I'm developing a small application in Ruby-On-Rails. I want to hide a div in an html.erb file until a link is clicked. What is the simplest way to do this?

like image 434
notGeek Avatar asked Apr 26 '12 19:04

notGeek


2 Answers

In your html file:

<a href="#" id="show_whatever">Show Whatever</a>
<div id="whatever" class="hidden">...</div>

In your CSS file:

div.hidden { display: none; }

In an included javascript file, or inside of <script> tags:

$(function() {
  $('a#show_whatever').click(function(event){
    event.preventDefault();
    $('div#whatever').toggle();
  });
});   

The hidden class is hiding the div. The jQuery function is listining for a click on the link, then preventing the link from being followed (event.preventDefault() keeps it from browsing to #)`, and lastly toggling the visibility of the div.

See the jQuery API for click() and toggle().

like image 93
Andrew Avatar answered Sep 30 '22 18:09

Andrew


This is easy with javascript. For instance, using the jQuery javascript library, you can easily toggle whether a div appears based on a link, as shown here. http://jsfiddle.net/Yvdnx/

HTML:

<a href="#">Click Me To Display Div</a>
<div>Foo</div>​

Javascript:

$(function() {
    $("div").hide();
    $("a").click(function(event) {
        event.preventDefault();
        $("div").toggle();
    });
});​

jQuery is reliable and works across many browsers, which differentiates it from using CSS3 selectors such as :target.

like image 25
dangerChihuahua007 Avatar answered Sep 30 '22 19:09

dangerChihuahua007