Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS / Javascript Show / Hide DIV using a CSS class?

I've googled around and found many scripts for hiding and showing DIV contents, as a toggle on button click.

But they are work using ID's.

I would like to do the same thing BUT I want to use a class instead of an id so that if I want to have 20 DIV's that toggle ... Hide / Show I don't have to add extra code.

Here is some code:

<script language="javascript"> 
function toggle() {
    var ele = document.getElementById("toggleText");
    var text = document.getElementById("displayText");
    if(ele.style.display == "block") {
            ele.style.display = "none";
        text.innerHTML = "show";
    }
    else {
        ele.style.display = "block";
        text.innerHTML = "hide";
    }
} 
</script>

<a id="displayText" href="javascript:toggle();">show</a> <== click Here
<div id="toggleText" style="display: none"><h1>peek-a-boo</h1></div>

Can anyone help with this please?

Thanks

like image 762
Satch3000 Avatar asked Apr 29 '11 19:04

Satch3000


People also ask

How do I show/hide a Div in JavaScript?

Show / hide a DIV using javascript. One simple way to do this would be have to simple functions one to hide and one to show. onclick="showstuff('id_of_element_to_show');". You could also switch a class, add it when you want to hide the element and remove it when you want to show it again.

How do I hide a class in a HTML page?

Firstly setup a rule in your stylesheet to hide the element with display:none or visibility:hidden. Then on a JavaScript event such as onmouseover or onclick, toggle the class. That looks like what i need, except I need each onclick to hide one and show the other.

How to hide and show the <div> element with pure CSS?

Now let’s see how you can hide and show your <div> element with pure CSS using the CSS :hover pseudo-class. Here’s the full code: When the user hovers over the <div>, it disappears, and the form is displayed.

How to toggle (hide/show) an element in HTML?

Toggle (Hide/Show) an Element Step 1) Add HTML: Example <button onclick="myFunction()">Click Me</button> <div id="myDIV"> This is my DIV element. </div> Step 2) Add JavaScript: Example


1 Answers

Is jquery an option? Hopefully so, because this does what you want:

http://api.jquery.com/toggle/

$(".class").toggle();
or
$(".class").show();  $(".class").hide();
like image 148
dpb Avatar answered Sep 27 '22 17:09

dpb