Toggle text inserted with innerHTML from Javascript - javascript

As an exercise I am trying to create a small quiz app and a part of it are the question cards. On these cards I have a question and then a button to show the answer. When the button is clicked, then the answer (which doesn't exist in the HTML DOM yet, therefore not visible) will show up and with the next click, the answer should be hidden again. Basically it will look something like this:
Before Show Answer is clicked
After Show Answer is clicked
Here is the HTML code:
<section class="question-card">
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam vitae
labore repudiandae tenetur. Qui maiores animi quibusdam voluptatum
nobis. Nam aperiam voluptatum dolorem quia minima assumenda velit libero
saepe repellat. Tempore delectus deleniti libero aliquid rem velit illum
expedita nostrum quam optio maiores officiis consequatur ea, sint enim
cum repudiandae inventore ab nemo?
</p>
<div class="bookmark">
<i class="fa-regular fa-bookmark fa-lg"></i>
</div>
<button class="answer-button" data-js="answer-button">Show Answer</button>
<ul class="answer-container" data-js="answer-container">
</ul>
<div class="container-categories">
<button class="category-button category-html">#html</button>
<button class="category-button category-flexbox">#flexbox</button>
<button class="category-button category-css">#css</button>
<button class="category-button category-js">#js</button>
</div>
</section>
I have added an EventListener for the Show Answer button that adds a list item in the already existing ul when it is clicked. I have done this with innerHTML:
const answerButton = document.querySelector(".answer-button");
const answerContainer = document.querySelector(".answer-container");
const answer1 = "Lorem ipsum dolor sit amet consectetur adipisicing elit.";
answerButton.addEventListener("click", () => {
answerContainer.innerHTML = `<li class="show-answer">${answer1}</li>`;
});
Now what I can't seem to manage is to hide the answer when the button is clicked again (the next challenge will be that the button will change the text to "Hide Answer" after the first click, but I have no idea how to approach that yet). The closest I got was this:
answerButton.addEventListener("click", () => {
answerContainer.innerHTML = `<li class="show-answer">${answer1}</li>`;
answerContainer.classList.toggle("hide-answer");
});
However, this method displays the .hide-answer class first, after which the 2 classes are toggled and everything is as it should be. So after the first click, the answer is still hidden and only after the 2nd click the button behaves the way I want it to.
I have tried this as well:
answerButton.addEventListener("click", () => {
answerContainer.innerHTML = `<li class="hide-answer">${answer1}</li>`;
answerContainer.classList.toggle("show-answer");
});
But for some reason this shows the container with all the CSS properties, but there is no text:
Answer Container is there, but no text
This is the CSS for the 2 classes (show-answer and hide-answer):
.show-answer {
background-color: hotpink;
border-radius: 7px;
border: none;
list-style: none;
width: 50%;
display: flex;
justify-content: center;
align-items: center;
padding: 1rem;
box-shadow: rgba(0, 0, 0, 0.3) 0px 19px 38px;
}
.hide-answer {
display: none;
}
If anybody has any idea how I could get the result I need, I would be extremely grateful...

You're mixing up the answer-container with the answer-container's child (the innerHtml <li> element).
initially there's a visible, but empty <ul class="answer-container"></ul>.
Next on click of the button, you add the content into the answer-container expecting it to be visible with a show-answer class
Immediately after, you add the hide-answer class to the <ul class="answer-container"> parent element which hides the newly added content.
Click the button again and you finally see your answer because the container element has the hide-answer class toggled off. From here it works as you're expecting.
You can fix this by having the answer-container be hidden initially and then continue to toggle the display of the container. You can also just use a DOM element's hidden attribute to do this as I do in this code snippet below where I've taken your exact example and just modified the answer-container to start with hidden and toggle the hidden attribute on click. You can do the same thing w/ a CSS display: none class too.
const answerButton = document.querySelector(".answer-button");
const answerContainer = document.querySelector(".answer-container");
const answer1 = "Lorem ipsum dolor sit amet consectetur adipisicing elit.";
answerButton.addEventListener("click", () => {
answerContainer.innerHTML = `<li class="answer">${answer1}</li>`;
answerContainer.hidden = !answerContainer.hidden;
});
.answer {
background-color: hotpink;
border-radius: 7px;
border: none;
list-style: none;
width: 50%;
display: flex;
justify-content: center;
align-items: center;
padding: 1rem;
box-shadow: rgba(0, 0, 0, 0.3) 0px 19px 38px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<section class="question-card">
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam vitae
labore repudiandae tenetur. Qui maiores animi quibusdam voluptatum
nobis. Nam aperiam voluptatum dolorem quia minima assumenda velit libero
saepe repellat. Tempore delectus deleniti libero aliquid rem velit illum
expedita nostrum quam optio maiores officiis consequatur ea, sint enim
cum repudiandae inventore ab nemo?
</p>
<div class="bookmark">
<i class="fa-regular fa-bookmark fa-lg"></i>
</div>
<button class="answer-button" data-js="answer-button">Show Answer</button>
<ul class="answer-container" hidden data-js="answer-container">
</ul>
<div class="container-categories">
<button class="category-button category-html">#html</button>
<button class="category-button category-flexbox">#flexbox</button>
<button class="category-button category-css">#css</button>
<button class="category-button category-js">#js</button>
</div>
</section>

Would something like this work?
You just use if the container has the class show-answer to determine if the answer needs to be shown or hidden
answerButton.addEventListener("click", () => {
if (answerContainer.classList.contains('show-answer')) {
// container has `showing` class
// hide the answer
answerContainer.innerHTML = ``; // ? - my guess, not sure how to want to hide it
}else{
// container doesn't have `showing` class
// show the answer
answerContainer.innerHTML = `<li class="hide-answer">${answer1}</li>`;
};
// update class
answerContainer.classList.toggle("show-answer");
});

Related

Find element that's on the middle of the visible screen (viewport) to target another element

What I am aiming to achieve is something that looks like this. you can see it in action on this URL, if you scroll a bit.
I was thinking at first to try using inViewport, and every time a heading or a paragraph is in viewport to show one image and hide the previous. but my problem is that the elements are in viewport in conjunction
This is the initial code I was using:
$.fn.isInViewport = function () {
let elementTop = $(this).offset().top;
let elementBottom = elementTop + $(this).outerHeight();
let viewportTop = $(window).scrollTop();
let viewportBottom = viewportTop + window.innerHeight; // <-- here
return elementBottom > viewportTop && elementTop < viewportBottom;
};
$(window).scroll(function () {
if ($('.heading1 ').isInViewport()) {
// Use .blogcard instead of this
$('.img1').addClass('show');
} else {
// Remove class
$('.img1').removeClass('show');
}
if ($('.heading2 ').isInViewport()) {
// Use .blogcard instead of this
$('.img2').addClass('show');
} else {
// Remove class
$('.img2').removeClass('show');
}
});
I have found this answer but have no idea on how can I use is to my benefits.
I have also stumbled upon this solution, which looks even smarter, but the code adds the classes to the selector in viewport and not to a different element.
This is the code applied there:
ar getElementsInArea = (function(docElm){
var viewportHeight = docElm.clientHeight;
return function(e, opts){
var found = [], i;
if( e && e.type == 'resize' )
viewportHeight = docElm.clientHeight;
for( i = opts.elements.length; i--; ){
var elm = opts.elements[i],
pos = elm.getBoundingClientRect(),
topPerc = pos.top / viewportHeight * 100,
bottomPerc = pos.bottom / viewportHeight * 100,
middle = (topPerc + bottomPerc)/2,
inViewport = middle > opts.zone[1] &&
middle < (100-opts.zone[1]);
elm.classList.toggle(opts.markedClass, inViewport);
if( inViewport )
found.push(elm);
}
};
})(document.documentElement);
////////////////////////////////////
// How to use:
window.addEventListener('scroll', f)
window.addEventListener('resize', f)
function f(e){
getElementsInArea(e, {
elements : document.querySelectorAll('div'),
markedClass : 'highlight--1',
zone : [20, 20] // percentage distance from top & bottom
});
getElementsInArea(e, {
elements : document.querySelectorAll('div'),
markedClass : 'highlight--2',
zone : [40, 40] // percentage distance from top & bottom
});
}
Would love all the help I could get. Cheers
Using the IntersectionObserver API
It should be quite simple by using the IntersectionObserver API to watch for your elements intersecting the viewport, or any other (Options root) ancestor.
To detect an element reaches the viewport vertical center can be done by passing the Option rootMargin where the bottom and top values are set at -50%, with an Option threshold set to 0 (as soon as one pixel enters that intersecting area)
// Utility functions:
const EL = (sel, par) => (par || document).querySelector(sel);
const ELS = (sel, par) => (par || document).querySelectorAll(sel);
// App:
const ELS_pictures = ELS(".picture");
const switchPicture = (EL_entry) => {
const EL_picTarg = EL(EL_entry.dataset.reveal);
ELS_pictures.forEach(EL_pic => EL_pic.classList.toggle("is-active", EL_pic === EL_picTarg));
};
// In Viewport
const inViewport = (entries, observer) => entries.forEach(entry => entry.isIntersecting && switchPicture(entry.target));
// Assign observer to all Elements with data-reveal attribute (Articles)
ELS("[data-reveal]").forEach(el => {
const observer = new IntersectionObserver(inViewport, {
// root: (by default is Document),
rootMargin: "-50% 0px -50% 0px", // set the root intersecting area as a tiny line in the vertical center
threshold: 0, // 0 = as soon as 1px intersects
});
observer.observe(el);
});
/* QuickReset */
* {
margin: 0;
box-sizing: border-box;
}
body {
font: 18px/1.5 sans-serif;
}
.stickers {
display: grid;
grid-template-columns: 2fr 3fr;
max-width: 1000px;
margin: 0 auto;
}
/* Article Component */
.articles {
display: flex;
flex-direction: column;
}
.article {
margin: 100px 0;
padding: 30px;
}
.pictures {
position: sticky;
display: flex;
top: 0px;
right: 0;
height: 100vh;
background: #444;
}
.picture {
position: absolute;
height: 100%;
width: 100%;
object-fit: cover;
margin: auto;
transition: 0.3s opacity, 0.5s transform;
opacity: 0;
transform: scale(0.8);
}
.picture.is-active {
opacity: 1;
transform: scale(1);
}
<p style="height: 80vh;">Scroll down...</p>
<div class="stickers">
<div class="articles">
<div class="article" data-reveal="#picture_1">
<h1>Many cats</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Optio laudantium perferendis eius iusto vitae eaque, eligendi ullam, rerum maiores, totam velit! Debitis repudiandae aliquam placeat, minus. Facere nihil aspernatur nam!</p>
</div>
<div class="article" data-reveal="#picture_2">
<h1>Little cat</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur perferendis possimus asperiores deleniti voluptatum amet nostrum ratione odio, a perspiciatis suscipit ab nulla repellat laudantium praesentium adipisci! Nihil ex, quos!</p>
</div>
<div class="article" data-reveal="#picture_3">
<h1>Snowcat</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur perferendis possimus asperiores deleniti voluptatum amet nostrum ratione odio, a perspiciatis suscipit ab nulla repellat laudantium praesentium adipisci! Nihil ex, quos!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur perferendis possimus asperiores deleniti voluptatum amet nostrum ratione odio, a perspiciatis suscipit ab nulla repellat laudantium praesentium adipisci! Nihil ex, quos!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur perferendis possimus asperiores deleniti voluptatum amet nostrum ratione odio, a perspiciatis suscipit ab nulla repellat laudantium praesentium adipisci! Nihil ex, quos!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur perferendis possimus asperiores deleniti voluptatum amet nostrum ratione odio, a perspiciatis suscipit ab nulla repellat laudantium praesentium adipisci! Nihil ex, quos!</p>
</div>
<div class="article" data-reveal="#picture_4">
<h1>Cat</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aut recusandae doloribus laboriosam, quasi aspernatur modi illum voluptate dicta alias optio, omnis qui deserunt. Quisquam, beatae dolores cum nostrum sint minima!</p>
</div>
</div>
<div class="pictures">
<img class="picture is-active" id="picture_1" src="https://placekitten.com/380/300" alt="Catz!">
<img class="picture" id="picture_2" src="https://placekitten.com/460/400" alt="Catz!">
<img class="picture" id="picture_3" src="https://placekitten.com/400/450" alt="Catz!">
<img class="picture" id="picture_4" src="https://placekitten.com/500/450" alt="Catz!">
</div>
</div>
<p style="height: 180vh;">Etc...</p>
Use data-* Attribute on your articles Elements where the value should match the selector of the related picture.
Toggle a class i.e: .is-active using classList that will determine the active styles for the matching picture Element
To make the fixed effect use position: sticky on your pictures parent element.

Scroll up after click a href in page

I have a footnote system. When I click sup number it scroll down to footnote. But It didn't show because of sticky header.
I need to scroll up around 60px after href scrolling.
I tried to add window.scrollBy(0, 60); in onclick of "sup a" object. It didn't work when I add it as function as well.
Full code:
$(document).ready(function() {
// make a link out of any <sup> with class .footnoted
$('sup').each(function(i){
var superscript = i+1;
$(this).html('<a>' + superscript + '</a>');
});
// give <sup class="footnoted"> an id to scroll back to
$('sup').each(function(i){
this.id = "reading-position-"+(i+1);
});
// tell the superscripts where to go
$('sup a').each(function(i){
this.href = "#footnote-"+(i+1);
});
// set a target for the superscripts to scroll to
// if you're not using a list for your footnotes, change li to the correct selector
$('ol li').each(function(i){
this.id = "footnote-"+(i+1);
});
// add return to reading position link at the end of the footnote
$('ol li').append('<a rel="nofoot"> ↑ Okuma Alanına Geri Dön</a>');
// give the return to position url an href of the target ID
$('ol li a').each(function(i){
this.href = "#reading-position-"+(i+1);
});
// make a back to top link at the end of your footnotes
// if you're not using a list for your footnotes, change li to the correct selector
// smooth scroll between reading position and footnotes
$('sup a[href^="#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash,
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top - 60
}, 500, 'swing', function () {
window.location.hash = target;
});
// remove class and link to previous reading position from other <li> if you scrolled to a footnote previously
{#$('.current-footnote span').remove();#}
{#$('ol li').removeClass('current-footnote');#}
// add return to reading position link and give the current footnote a class for additional styles
$(target).addClass('current-footnote');
$('.current-footnote span').css('display', 'inline');
});
scrollBy(0, 60) scrolls down, not up. You need to use negative numbers to reverse the direction. So, window.scrollBy(0, -60).
If that still doesn't work, something is probably wrong with how you're registering the click handler. It would be useful if you could show your full code.
You can create references using the DATA attribute.
Example link: <span class="reference" data="#one">ONE</span>
This script will collect all elements with class class="reference" and add a listener to them. When the element is clicked, the script will take the DATA information which is the ID of the element to which the page should be scrolled.
In this line you can change the value 60 so that the information remains in the visible part
window.scrollTo(0, top - 60);
In this example, 60px is the height of the sticky navigation
var navLinks = document.querySelectorAll('.reference');
for (let i = 0; i < navLinks.length; i++) {
navLinks[i].addEventListener("click", function () {
var elId = this.getAttribute('data');
var top = document.querySelector(elId).offsetTop;
window.scrollTo(0, top - 60);
});
}
body {
margin: 0px;
}
nav {
height: 60px;
background: orangered;
position: fixed;
width: 100%;
top: 0px;
}
.reference {
cursor: pointer;
color: orangered;
}
#wrap {
margin-top: 60px;
}
<nav>Navigation...</nav>
<div id="wrap">
<div>
Lorem ipsum dolor, <span class="reference" data="#one">ONE</span> sit amet consectetur adipisicing elit. Cum nihil vero voluptatibus tempora repellendus <span class="reference" data="#two">TWO</span> aperiam quidem debitis, totam consequuntur ex aspernatur quasi quod molestias rem quibusdam? Facilis adipisci asperiores iste. Lorem ipsum dolor, sit amet consectetur adipisicing elit. Cum nihil vero voluptatibus tempora repellendus aperiam quidem debitis, totam consequuntur ex aspernatur quasi quod molestias rem quibusdam? Facilis adipisci asperiores iste. Lorem ipsum dolor, sit amet consectetur adipisicing elit. Cum nihil vero voluptatibus tempora repellendus aperiam quidem debitis, totam consequuntur ex aspernatur quasi quod molestias rem quibusdam? Facilis adipisci asperiores iste.
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</div>
<p id="one">
ONE - Reference One
<br><br><br><br><br><br><br><br><br><br><br>
</p>
<p id="two">
TWO - Reference Two
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</p>
</div>

Shrink overflowing content to fit container?

Is it possible in CSS (if not, javascript?) to shrink content that overflows its container, rather than hide it?
I have a box with some text etc, which shrinks in width as the viewport gets smaller, and the height is restricted too. All the content needs to remain visible, but within the bounds. Scroll is not an option.
body {
background-color: mediumaquamarine;
}
div {
width: 300px;
height: 150px;
overflow: hidden;
background-color: #fff;
}
<div>
<h1>example title</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati fugiat dolore amet odit quaerat iusto sapiente ea quod atque necessitatibus id eius accusantium itaque voluptatibus laborum, doloremque, recusandae, nobis consequatur.</p>
<button>a button</button>
</div>
Hmm, the question is a little unclear, but you could look into using viewport width font-size. It will resize based on the screen size:
body {
background-color: mediumaquamarine;
}
div {
width: 300px;
height: 150px;
overflow: hidden;
background-color: #fff;
font-size: 1.3vw;
}
button {
font-size: 1.3vw;
}
<div>
<h1>example title</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati fugiat dolore amet odit quaerat iusto sapiente ea quod atque necessitatibus id eius accusantium itaque voluptatibus laborum, doloremque, recusandae, nobis consequatur.</p>
<button>a button</button>
</div>
Use this function to adjust the font-size of a span inside a div:
function adjustHeights(elem) {
var fontstep = 2;
if ($(elem).height() > $(elem).parent().height() || $(elem).width() > $(elem).parent().width()) {
$(elem).css('font-size', (($(elem).css('font-size').substr(0, 2) - fontstep)) + 'px').css('line-height', (($(elem).css('font-size').substr(0, 2))) + 'px');
adjustHeights(elem);
}
}
div {
position: fixed;
width: 200px;
height: 100px;
border: 1px solid blue;
padding: 1px;
overflow-wrap: break-word;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<span id="text">
sldfjslfjladf
sf
as
f
wer
qwreqwrewasdf
sd
f
s
fs
df
s
ffadsssssssssssssssssssssssssssss
asdf<br/>
sdf
s
dsfsfaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
</span>
</div>
<script>
function adjustHeights(elem) {
var fontstep = 2;
if ($(elem).height() > $(elem).parent().height() || $(elem).width() > $(elem).parent().width()) {
$(elem).css('font-size', (($(elem).css('font-size').substr(0, 2) - fontstep)) + 'px').css('line-height', (($(elem).css('font-size').substr(0, 2))) + 'px');
adjustHeights(elem);
}
}
var div = document.getElementById("text");
adjustHeights(div);
</script>
JSFiddle: http://jsfiddle.net/e8B9j/1390/
SVG with text element.
Make an svg with expandable text.
It will eventually be hard to read.
<div style="width: 60px;">
<svg width="100%" height="100%" viewBox="0 -200 1000 300"
xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<text font-size="300" fill="black">Text</text>
</svg>
</div>
Non styled example
https://jsfiddle.net/k8L4xLLa/32/
Cool styled example
https://jsfiddle.net/k8L4xLLa/14/
You can use media queries to change the font size when needed.
Honestly though, consider flexbox. Its a much cleaner solution that does not make the text scalable. Then you can wrap your elements when theyre too small. :)

Render only selected element, React JS

I am trying to toggle class in one of my react component.
The idea is to add class when the mouse enter and to remove the class when the mouse leave only in the element only the element in where the user perform the actions. However this is not the case as when the action is being performed all the element with the function are behaving equally.
This is my code so far:
export default class Projects extends Component{
constructor(){
super();
this.state = {
isHovered : false
}
}
//handle mouse enter
handleMouseEnter = () =>{
this.setState({
isHovered : true
});
}
//handle mouse leave
handleMouseLeave = () =>{
this.setState({
isHovered : false
});
}
//render component
render(){
let display = "";
if(this.state.isHovered === true){
display = "active";
}else{
display = "disable";
}
return(
<section className="projects">
{/*section project wrapper*/}
<div className="p-wrapper">
<h1 className="title">Projects</h1>
<hr/>
{/*projet wrapper*/}
<div className="projects-wrapper">
{/*project item wrapper*/}
<div className="project-item" onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}>{/*FMA Web development*/}
<div className={"p-description " + display}>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Iure quos dolorem, ipsa eaque minima saepe fugit hic libero recusandae! Obcaecati esse odit id incidunt vitae aperiam dicta atque blanditiis sint?</p>
</div>
<div className="p-image">
<img src="asset/img/fma_web.png" alt="FMA Web Development"/>
</div>
</div>
<div className="project-item" onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}>{/*Web development using php*/}
<div className={"p-description " + display}>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Iure quos dolorem, ipsa eaque minima saepe fugit hic libero recusandae! Obcaecati esse odit id incidunt vitae aperiam dicta atque blanditiis sint?</p>
</div>
<div className="p-image">
<img src="asset/img/web_dev_php.png" alt="FMA Web Development Using PHP"/>
</div>
</div>
<div className="project-item" onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}>{/*Movie Catalog*/}
<div className={"p-description " + display}>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Iure quos dolorem, ipsa eaque minima saepe fugit hic libero recusandae! Obcaecati esse odit id incidunt vitae aperiam dicta atque blanditiis sint?</p>
</div>
<div className="p-image">
<img src="asset/img/movie_catalog.png" alt="Movie Catalog"/>
</div>
</div>
</div>
</div>
</section>
);
}
}
I have read the use of key in the documentation and read other question especially this one LINK,however when I try to implement I do not get the desired result.
===========================
EDIT
This is what I get now.
As you can see when I hover both of the element triggers.
This is my CSS Code:
/*Projects Start*/
.projects{
width: 100%;
}
.p-wrapper{
margin: 0 auto;
width: 90%;
height: 100%;
}
.projects-wrapper{
margin-top: 2rem;
width: 100%;
display: flex;
justify-content: center;
flex-wrap: wrap;
}
.project-item{
margin: 1rem;
width: 30%;
position: relative;
box-shadow: 2px 3px 37px -5px rgba(0,0,0,0.84);
}
.p-description{
position: absolute;
height: 100%;
width: 100%;
background-color: rgba(43, 40, 40, 0.61);
color: white;
}
.p-description p {
margin: 1rem;
}
.p-title{
margin: 1rem;
}
.active{
display: block;
transition: all 2s ease-in;
}
.disable {
display: none;
}

Show one or more elements and their content that have been hidden

I'm stuck and not sure how to move on. I want to be able to click a tab to reveal its content. With the code I currently have, when I click a single tab, it reveals the content for all the tabs. But I just want the click to reveal the content that's associated with that single tab. I'm looking for a vanilla javascript solution.
Here's the code: http://codepen.io/anon/pen/KCJAc (inline below)
CSS:
.tab-content {
display: block;
height: 0;
opacity: 0;
overflow: hidden;
transition: all 1s ease-out;
}
.tab-active {
height: auto;
opacity: 1;
}
JavaScript:
var tabHeaders = document.getElementsByClassName('tab-header');
for (var i = 0; i < tabHeaders.length; i++) {
tabHeaders[i].addEventListener('click', activateTab);
}
function activateTab() {
var tabContents = document.getElementsByClassName('tab-content');
for (var i = 0; i < tabContents.length; i++) {
tabContents[i].classList.add('tab-active');
}
}
HTML:
<div>
<h3 class="tab-header">Tab1</h3>
<p class="tab-content">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium odio iste aliquam molestias corporis blanditiis nihil soluta sint illum quibusdam reprehenderit sed quaerat iusto maiores error iure ducimus dicta ipsum.</p>
</div>
<div>
<h3 class="tab-header">Tab2</h3>
<p class="tab-content">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium odio iste aliquam molestias corporis blanditiis nihil soluta sint illum quibusdam reprehenderit sed quaerat iusto maiores error iure ducimus dicta ipsum.</p>
</div>
You're adding tab-active to all of the tab-content elements. You just want to add it to the one following the header that's clicked: Updated Pen
var tabHeaders = document.getElementsByClassName('tab-header');
for (var i = 0; i < tabHeaders.length; i++) {
tabHeaders[i].addEventListener('click', activateTab);
}
function activateTab() {
var tabContents = this.nextElementSibling;
while (tabContents && (!tabContents.classList || !tabContents.classList.contains("tab-content"))) {
tabContents = tabContents.nextElementSibling;
}
if (tabContents) {
tabContents.classList.toggle("tab-active");
}
}
Notes:
I'm using nextElementSibling to get the next sibling that's an element since you used classList in the original, so I figure you're only using this code on fairly up-to-date browsers. If you intend to use it on older browsers, you can use nextSibling instead (and also use className rather than classList.
This is because by using document.getElementsByClassName you are getting all tab-content tabs in your page, rather than the DOM level of the clicked tab-header element. You can use the nextSibling property of tab-header to get the next DOM node beside tab-header:
function activateTab() {
this.nextSibling.classList.add("tab-active");
}
Or, if you are not sure if tab-content will definitely appear directly after tab-header you can query parentNode using querySelector:
function activateTab() {
this.parentNode.querySelector(".tab-content").classList.add("tab-active");
}
Note this last method won't work in anything lower than IE8, but then again neither will the classList property in your original question.

Categories

Resources