You could use details
and summary
HTML5 elements (if IE and Opera Mini are not a big concern; for those the below example will fallback gracefully)
<details> <summary>Please fill out our optional survey</summary> <p>What year are you in college?</p> <label><input type="radio" name="clg" value="0"> Not yet there</label> <label><input type="radio" name="clg" value="1"> Junior</label> <label><input type="radio" name="clg" value="2"> Senior</label> </details>
Find also other ways to Toggle an element
To recreate the above in JavaScript here's a ES6 example:
[...document.querySelectorAll('[data-details]')].forEach( el => el.addEventListener('click', () => { document.querySelector(el.getAttribute('data-details')).classList.toggle('hide'); el.classList.toggle('open'); el.setAttribute('aria-expanded', el.classList.contains('open')); }) );
[data-details] { display: block; width: 100%; -webkit-appearance: none; background: none; border: none; text-align: left; font: inherit; } [data-details]:before { content: "\\25ba"; speak: none; } [data-details].open:before { content: "\\25bc"; speak: none; } .hide{ display: none; }
<button type="button" data-details="#d1" aria-describedby="d1" aria-expanded="false" >Summary 1</button> <div id="d1" class="hide">CONTENT ONE</div> <button type="button" data-details="#d2" aria-describedby="d2" aria-expanded="false">Summary 2</button> <div id="d2" class="hide">CONTENT TWO</div>
As another answer pointed out, you can use the details
and summary
elements, but they are poorly supported, only usable in Chrome and Firefox, if you need a solution that works in IE, Edge, and Safari, you need to use javascript, thankfully, this is very simple.
<div id="summary" onclick="toggle();">Summary</div>
<div id="togglable" style="display:none;">Toggleable text</div>
<script>
var i=0;//Counter
function toggle(){//Function called when Summary is clicked
if(i%2===0){//Even number
document.getElementById("toggle").style.display="initial";//Make it visible
}else{//Odd number
document.getElementById("toggle").style.display="none";//Visible
}
i++;
if(i===2){
i=0;//Reset i to ensure it doesn't get too big
}
}
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.