I am trying to build a collapsible onclick function in HTML to display an image upon clicking a plus sign to fold out to a src image.
I have accomplished this, but need to program the function to collapse and close the image once I click onto the "-" sign.
Can someone please help me with this?
function myFunction() {
document.getElementById("demo").innerHTML = `<image style="width= 100%; height:auto" src="https://sharepoint2.web.PNG"/>`;
document.querySelector('#testButton').innerHTML = '-';
}
<button id="testButton" onclick="myFunction()">+</button>
<p id="demo"> </p>
2
Answers
I can’t find your image. So, I use stackoverflow site’s img. just change that.
You need to track whether the button has been toggled or not, you can do this in various ways.
In this example the
onclick
attribute on the HTML element is changed to run a different function:In this example there is a global variable which tracks if the button has been toggled:
In this example we use a html data attribute to track the button toggle: