I am not sure why this is not working. Could it be the way I wrote my id name and class name? I wrote that way for demo purposes.
I checked the spelling and so far, so good. Your help will be very much appreciated. I have read somewhere that it is always recommended to use:
content.classList.add("open")
instead of:
content.className = "open"
as the latter one may eliminate all other classes that exist in the content element.
Here is my code:
let contentVar = document.getElementById("idOfcontent");
let buttonVar = document.getElementById("idOfshowmore");
buttonVar.onclick = function() {
if (contentVar.className == "classOfopen") {
// shrink the box
contentVar.className = "";
buttonVar.innerHTML = "Show More";
} else {
// expand the box
contentVar.className = "classOfopen";
buttonVar.innerHTML = "Show Less";
}
}
body {
background: #eee;
}
#idOfcontent {
width: 400px;
background: #ffff;
padding: 18px;
font-family: Verdana, Geneva, Tahoma, sans-serif;
font-size: 18px;
color: #444;
margin: 0 auto;
max-height: 100px;
overflow: hidden;
/* Set transitions up */
-webkit-transition: max-height 0.7s;
-moz-transition: max-height 0.7s;
transition: max-height 0.7s;
}
#idOfcontent .classOfopen {
max-height: 5000px;
/* Set transitions up */
/* for smooth transition */
-webkit-transition: max-height 0.7s;
-moz-transition: max-height 0.7s;
transition: max-height 0.7s;
}
#idOfshowmore {
background: #1594e5;
color: #ffffff;
font-family: Verdana, Geneva, Tahoma, sans-serif;
display: block;
width: 140px;
font-size: 17pxx;
text-transform: uppercase;
padding: 10px;
text-align: center;
margin: 20px auto;
cursor: pointer;
}
<div id="idOfcontent">
<p>In this JavaScript tutorial I want to run through a detailed example of how we can use the onclick event in JavaScript to create cool functionality on our websites.</p>
<p> In this example I'll use the onclick event to create a 'show more' style content box which expands and shrinks as you click the button. </p>
<p>The difference between an ID and a class is that an ID is only used to identify one single element in our HTML. IDs are only used when one element on the page should have a particular style applied to it. However, a class can be used to identify more
than one HTML element.</p>
</div>
<a id="idOfshowmore">Show More</a>