Skip to content
Advertisement

Toggle display:none style with JavaScript

I want to change the style (second line below) to remove the display: none; part when the user clicks on the “Show All Tags” link. If the user clicks the “Show All Tags” link again, I need the display: none; text added back in to the “style…” statement.

<a href="#" title="Show Tags">Show All Tags</a>
<ul class="subforums" style="display: none; overflow-x: visible; overflow-y: visible; ">

I’ve searched here and Google for an example I can apply to my situation. I’ve found plenty of examples using 2 DIV blocks to show/hide. I really need to do it this way, by modifying the html style element. Does anyone have an example (or provide a link to an example) that does this type of toggle wtih the display: none text.

Advertisement

Answer

Give your ul an id,

<ul id='yourUlId' class="subforums" style="display: none; overflow-x: visible; overflow-y: visible; ">

then do

var yourUl = document.getElementById("yourUlId");
yourUl.style.display = yourUl.style.display === 'none' ? '' : 'none';

IF you’re using jQuery, this becomes:

var $yourUl = $("#yourUlId"); 
$yourUl.css("display", $yourUl.css("display") === 'none' ? '' : 'none');

Finally, you specifically said that you wanted to manipulate this css property, and not simply show or hide the underlying element. Nonetheless I’ll mention that with jQuery

$("#yourUlId").toggle();

will alternate between showing or hiding this element.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement