What you’re describing, and the example you linked, is using javascript to toggle the display style attribute of a container div.
The example you linked is only using it when additional details are available, and they have placed them within a separate div to the description text, etc.
The functionality works as follows:
We have a some divs
with ids, and a <span>
with an onclick calling our javascript function, showHide()
. In this example, we are concerned with showing/hiding the div
with id showAndHide
:
<div id="somewrapper">
<div id="always-visible">
<span onclick="showHide()">Read More</span>
</div>
<div id="showAndHide">
<p>This is the show-and-hide div.</p>
</div>
</div>
For the javascript portion:
We get the div by its id and set it to a variable, here sh
. Then we check the state of sh
‘s style:display attribute. If it is none
, the onclick()
sets it to block
to show it. If it has block
, then it sets it none
, “hiding” it.
All of that is done very easily in a few lines of code:
<script>
function showHide() {
var sh = document.getElementById('showAndHide');
if (sh.style.display === 'none') {
sh.style.display = 'block';
} else {
sh.style.display = 'none';
}
}
</script>
W3C gives a very clean example of this you can try in your browser
As a sidenote, you could achieve similar functionality with the css visibility
attribute, but it behaves differently. Display:none;
will not take up space, it is effectively removed; while with visibility:hidden;
the element’s place is preserved. That is unless you are dealing with table
elements and using the collapse
value. Since the example you linked was not using tr
s, and the space does expand/collapse, I opted for Display:Block/None
.
Read More on Visibility: visible/hidden/collapse here.
A much more knowledgeable explanation on the differences between Display and Visibility
Adding this functionality to a shortcode’s output in wordpress
1) You need the id(s) of the element(s) you wish to show/hide.
2) If you’re going to add a “read more” text and onclick, you will need to know either a) a measurable point at which to insert it in the containing div, or b) an element to which it can be prepended or appended.
3) take the full javascript function(s), add them to a file, myShowHide.js perhaps, and upload it to your child theme’s directory.
4) In functions.php, Register the script with wp_register_script
and Enqueue it with wp_enqueue_script
to include that javascript file in your template pages. You can also wrap wp_enqueue_script
in a function if you need it to only include the script on certain pages.