I am currently using this code for a MORE hide/reveal button, but can't figure out how to make it be @media query dependent so it only shows up and works at particular browser width.
CSS:
<div>
<p>
Can I put a paragraph of text here?
<div id="dots1">...</div>
</p>
<div style="display: none;" id="more1">
<p>
The text I want to be on read more
</p>
</div>
<button class="btn" id="myBtn1">
Read more
</button>
</div>
JAVASCRIPT
<script>
for (const btn of document.querySelectorAll('.btn')) {
btn.addEventListener('click', () => {
const [ dots, moreText ] = Array.from(btn.parentElement.querySelectorAll('div'));
if (dots.style.display === "none") {
dots.style.display = "inline";
btn.innerHTML = "MORE";
moreText.style.display = "none";
}
else {
dots.style.display = "none";
btn.innerHTML = "LESS";
moreText.style.display = "block";
}
});
}
</script>
And that's essentially because it is dependent on this "span style" that has to be placed inline the HTML file. It won't work if I make that span style a class attribute.
<div style="display: none;" id="more1">
Either:
Separately, I would also like to get rid of the "dots" being part of the script. I currently just leave that with the dots empty, but it's not perfect coding.
EDITED: I want to say that I want to have the text show up at a certain width without the more button, then be hidden by a button at another browser width. And also say "READ MORE" first and "READ LESS" or something different after it opens. Thank you very much!
Thank you!
Using CSS, I hide the read more button and display the read more text by default. Then using a media query, I determine based on the size to hide the text and show the button. Then using javascript, I attach an event handler to the document and catch all of the btn-readmore clicks and toggle an active class that will display block or not.
document.addEventListener("click",function(e){
let el = e.target;
if(el.className == "btn-readmore"){
let moreTxt = el.parentNode.querySelector(".more-text");
moreTxt.classList.toggle("active");
el.innerHTML = (moreTxt.className.indexOf("active") > 0) ? "Read Less" : "Read More";
}
});
.active.more-text,.more-text{display:block;}
.btn-readmore{display:none}
@media screen and (min-width: 200px) and (max-width: 1000px){
.btn-readmore{display:block}
.more-text{display:none;}
}
<div>
<p>
Can I put a paragraph of text here?
</p>
<div class="more-text">
<p>
The text I want to be on read more
</p>
</div>
<button class="btn-readmore">
Read more
</button>
</div>