I tend to notice on a lot of the forums that I read, many people ask about a way to click on a HTML element in order to reveal another element. For instance: they are building an FAQ and want people to click on their question to have the answer slide down to reveal itself. I developed this short little JavaScript awhile back to do just that.
Step 1 – setup the HTML elements
On the element that you want to click to reveal the text, give it a class of “jsclick” and add ‘data-target=”(element id to reveal here)”‘. On the element that you want hidden, give it a class of “jshide”.
If I have one paragraph tag that I want to click to reveal the paragraph below it, I would write it like this:
<p class=”jsclick” data-target=”reveal1″>Click this</p>
<p id=”reveal1″ class=”jshide”>To reveal this</p>
Step 2 – Add jQuery
jQuery is an amazing framework and makes writing a lot of things in JavaScript a breeze. If you aren’t already using it on your site, put this at the bottom of your body tag:
<script
src=”https://code.jquery.com/jquery-3.1.1.min.js”
integrity=”sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=”
crossorigin=”anonymous”></script>
Step 3 – Add the reveal script
At some point after you have inserted jQuery, paste this code:
<script>
$(document).ready(function(){
$(“.jsclick”).click(function(){
$(“#” + this.dataset.target).slideToggle();
});
$(“.jshide”).slideToggle();
});
</script>
Note: I recommend putting all JavaScript at the bottom of your body tag (just before you close it). (Obviously if there is some reason why that doesn’t work – that’s up to you.) The reason is that by putting your JavaScript in the head, you are requiring the JavaScript to load before the page does. By putting it at the end, your page will load much faster.
Step 4 – Styling (optional)
If the “jsclick” elements are not already formatted like an anchor tag where the mouse looks like a pointer when you hover over it, you might want to add this to your CSS so people understand they can click on it:
.jshide {
cursor: pointer;
cursor: hand;
}
Putting it all together
Here’s what this code (inside the script tags) does:
1. The first script tag loads in jQuery. I tend to use this a lot in my JavaScript – I’m sure that it could be written without JQuery, but it’s much easier and easier to read if I use jQueryj
2. On document load, it creates a listener on each element on your page that has the “jsclick” function so that when that element is clicked, it reads the “target” dataset that you set in the element tags, and toggles the element to slide up or down depending on the last state.
3. At the end, it slides all of the elements with the “jshide” class up, so that they start in the hidden position and are not revealed until someone clicks one of the “jsclick” elements.
Graceful degradation
If JavaScript isn’t enabled, your page will still load properly, the elements just will not be hidden – resulting in your page still being usable.