Issue
I want to shrink my paragraph into a couple of read more, without the need to read less. I only manage to do it once and 'm now lost.
.bio {
font-family: monospace;
}
#check {
display: none;
}
#check:checked~.more {
display: block;
}
.more {
display: none;
}
label {
color: rgb(0, 0, 0);
cursor: pointer;
font-weight: bold;
text-decoration: underline;
}
<div class="bio">
<input type="checkbox" id="check">
<p>craftsman</p> *original display*
<div class="more">
<p>since birth has always had a love/hate relationship</p> *first readmore*
</div>
<label for="check"> more</label>
<div class="more">
<p>She had half-survived blahblahblah.</p> *second readmore*
</div>
</div>
Solution
- Make all elements with the class more hidden by using:
.more { display: none }
- Create a class to make elements visible again:
.d-block { display: block }
- Create a Node List in JS with all elements with the class more:
let bio_sections = document.querySelectorAll('.more')
- Create a variable at 0 as index:
let bio_index = 0
- Add a
click
-eventListener
linked to the button:button-element.addEventListener('click', () => { ... })
- Within the function create an
if
-condition to ensure that the actual function is only as often run as you have elements with the class more as otherwise, you will create an error after every further button click:if (bio_index < bio_sections.length)
- select the element out of the Node List with the current index:
bio_sections[bio_index]
- Add that previously created class to that element:
.classList.add('d-block')
- Increase the index to jump to the next element within your Node List:
bio_index++
let button = document.querySelector('.bio button');
let bio_sections = document.querySelectorAll('.bio .more');
/* index to iterate */
let bio_index = 0;
//trigger to check for button clicks
button.addEventListener('click', function() {
// ensures JS errors as otherwise elements going to be called that does not exist
if (bio_index < bio_sections.length) {
// makes the section visible
bio_sections[bio_index].classList.add('d-block');
//increases the index onclick
bio_index++;
}
})
.more {
display: none;
}
.d-block {
display: block;
}
button {
display: block;
margin-top: 2em;
}
<div class="bio">
<p>craftsman</p> *original display*
<div class="more">
<p>since birth has always had a love/hate relationship</p> *first readmore*
</div>
<div class="more">
<p>She had half-survived blahblahblah.</p> *second readmore*
</div>
<button>Read more about craftsman</button>
</div>
Answered By - tacoshy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.