Toggling Elements
You may have seen some sites that hide comments for people, and you can click a button or text to expand the hidden information. This is great if you were to creating a site where you are reviewing a book or movie and you do not want spoil the ending for your readers. Using a little CSS, we can create a script that will hide this information until the user wants to look at the hidden data.
<script language="JavaScript" type="text/JavaScript">
<!--
function toggle(id, id2 ) {
var toggle_block = document.getElementById(id);
var toggle_text = document.getElementById(id2);
if(toggle_block.style.display == 'block'){
toggle_block.style.display = 'none';
toggle_text.innerHTML = 'Expand';
}else{
toggle_block.style.display = 'block';
toggle_text.innerHTML = 'Hide';
}
}
//-->
</script>
This function is passed to variables, called id, and id2. The we create to variables after that this also makes it easier to edit the script in the future, if we ever need to change it, and it saves us some typing. After the two variables are given their values, we create a if else function. This is what what will allow us to toggle what is displayed on the site. If we did not have a if else, then we could only be able to toggle the element one way, and not back. For the toggle_block variable we are going to be changing the CSS display from none to block and back again. For the toggle_text variable, we will be changing the text that is sent to it. Lets now look at the HTML part of the code.
Expand Comments
Just by looking at the HTML alone, we know that we have an anchor tags with the id of toggleSwitch. We also have a div tag with the id of comments. If we look at the CSS part of the code, we see that the div is not shown, and has a padding of ten pixels. We also see that the anchor tag has the JavaScript onclick element, so that when it is clicked it passes information to the toggle() function. How this script works all together is when the user clicks the anchor tag, it then passes the two ids to the toggle() function. This then changes the text that is displayed for the anchor tag, and the display property for the CSS. Since we created the code that does toggles these settings, we can hide more the one element in our code, as long as it has a different id value. Additionally if we pass a third variable to the toggle function, we could even make the text for the link change also, like the example below.
Expand Spoliers
iEntry 10th Anniversary
CSS Snippets
JavaScript Snippets