Toggling Content
Occasionally you have some information that is needed, but not the most important, and you may want to hide it away, and let the visitor decide when they want to see it. So you toggle that content! Here’s a simple and fast way to add this functionality to your website, it’s reusable and can appear multiple times in a single HTML document.
Let’s start with the JavaScript. I used jQuery.
$(function(){
$('.toggle-link').on('click',function(e){
var txtIs = $(this).attr('data-open');
var hideIs = $(this).attr('data-close');
var objIs = $(this).attr('data-rel');
var toggleObj = $('[data-rev='+objIs+']');
if($.trim($(this).text()) === txtIs){
$(this).text(hideIs);
}
else{
$(this).text(txtIs);
}
toggleObj.toggleClass('toggle-open');
// stop THIS href from loading
// in the source window
e.preventDefault();
});
}); // close (document).ready
This will listen for .toggle-link
clicks and then open and close (toggle) the proper .toggle-content for you
.
Here is the HTML
<h1>Content Header <a href="#" class="toggle-link" data-rel="toggle-test" data-close="Hide" data-open="Show">Show</a></h1>
<div class="toggle-content" data-rev="toggle-test">
<p>This content is hidden, until the toggle-link is clicked.</p>
</div>
The important bit to remember here is that the values of data-rel
and data-rev
need to match, and need to be unique from any other pairs in the same HTML document.
The value of data-close
determines what the link’s text will be when the content is visible. And the value of data-open
determines the text when the content is hidden. The text in the link should match the value of data-open
.
And lastly, just a little CSS to get our open and closed states.
.toggle-content{
display: none;
}
.toggle-open{
display: block;
}
You can demo and play with this code here: https://jsfiddle.net/jmathias/bqf3ht3y/
So there you have it another tool for your next ExpressionEngine CMS site.
Comments 0
Be the first to comment!