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?
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().
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With