Here's a tutorial on how to create a simple jQuery spoiler. This tutorial assumes that you already have an HTML file ready to edit and have basic HTML knowledge, so I won't bother with those things. Note: You will need jQuery for this code to work. If you don't already have jQuery installed, add inside your <head> tag.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
First, let's get started with the HTML markup. What you'll need is something like this:
<div class="spoiler_wrap">
<input type="button" value="Show" />
<div class="spoiler_content">Here's some hidden content</div>
</div>
At first, it'll look something like this:
As you can see, the content isn't hidden like it's supposed to be, but that's because we haven't applied the CSS yet. Let's do that right now.
In your .css file, add this:
.spoiler_wrap input[type='button'] {
color: #fff;
background-color: #2C93FA;
padding: 2px;
border: 1px solid rgba(0, 0, 0, 0.1);
border-radius: 2px;
text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.3);
cursor: pointer;
}
.spoiler_wrap .spoiler_content {
display: none;
margin-top: 5px;
padding-left: 5px;
border-left: 3px solid #2C93FA;
}
It should now look like this:
Looks pretty good, right?
The next (and final) part of this tutorial would be the jQuery itself. Some of you may not know jQuery, so I'll leave some comments in the code to make things easier to understand.
$(document).ready(function() {
// Once we click the spoiler button
$(".spoiler_wrap input[type='button']").click(function() {
// If the button's value is "Show", use the value "Hide"
// But if it's not "Show", then change it back to "Show"
var btn_txt = ($(this).val() == "Show") ? "Hide" : "Show";
// Actually change the button's value
$(this).val(btn_txt);
// Go to HTML element directly after this button and slideToggle it
$(this).next().stop().slideToggle();
});
});
And you're done! Super easy, nice looking jQuery spoiler with just 3 pieces of code.
Here's what it looks like after being opened:
You can see that the button's text has been changed to "Hide" and that the content is now shown.
You can even copy/paste the HTML as many times as you want and create multiple spoilers! Like so:
Hope you found this useful!