I was working on some basic code where I wanted a div to show or hide based on a link. This is simple stuff, but it took me a while to remember it since it’s actually baked into MediaWiki (where I normally use it).
First up is my HTML code:
<h2 class="suggestions-header"><a href="javascript:toggle_visibility('suggestionscontainer');">Suggestions? Click Here!</a></h2> <div style="display:none;" class="sugestions-container" id="suggestionscontainer"> <p>I will display when clicked!</p> </div>
Like I said, this is basic stuff. I can get more into it and do things like change the text of the title when you click, but for now this suffices.
Now for the jquery:
/** * Custom jQuery to toggle visibility */ jQuery( document ).ready( function toggle_visibility(id) { var e = document.getElementById(id); if(e.style.display == 'block') e.style.display = 'none'; else e.style.display = 'block'; } );
This code got tossed into a toggle.js file and then enqueued with wp_enqueue_script, with a jquery dependancy. Done and done.
I’m sure this could be done with pure CSS, but I believe in release and iterate.
Comments
3 responses to “jQuery Toggling”
Since you’re using jQuery anyway, it has a built-in function for this kind of thing called .toggle()
It can take a load of parameters, but without any, it simple shows/hides the element like you’re doing here.
See http://api.jquery.com/toggle/
Hey Mika, the code you’re using actually doesn’t need the jQuery at all. The only thing you’re using that’s jQuery-specific is the bit that doesn’t load your function until DOM Document-ready. Since it’s just a simple function (nothing automatically runs and there’s no heavy lifting), you don’t really need that part, so you could remove the “jQuery( document ).ready(” and it’s corresponding “)” and not have the jQuery dependency.
If you’re loading JQuery anyway and want to use it, it has a .toggle() function so you could just do this:
$( "#id-of-link" ).click(function() {
$( "#suggestionscontainer" ).toggle();
});
This is something that might be best to load inside your document-ready code.
@Aaron D. Campbell: I edited your post to use HTML code tags (since that’s all the comments allow – it’s pure html!)
I tried Toggle and it just laughed at me, but the amount I know about jQuery is measured in beans right now. I’ll have another go at it!