I need to change visibilities of two texts, but I don’t want a toggle button, just one icon that – when clicked – hides text1 and shows text2, and returns back when clicked again.
I use:
<span onclick="document.getElementById('text1').innerHTML = (this.innerHTML == document.getElementById('text1').innerHTML) ? document.getElementById('text2').innerHTML : document.getElementById('text1').innerHTML"><i class="fa fa-comments" aria-hidden="true"></i></span>and
<div class="content">
<div id="text1">
<h1>Welcome</h1>
<p>English text</p>
</div>
<div id="text2">
<h1>Välkommen</h1>
<p>Swedish text</p>
</div>
</div>
Edit: Miguel G’s answer solves it. However, I still try to figure out how to have the text change in other sections across the entire page.
5
Answers
Ok, I made a lot of changes in your code, I don’t know if this was exactly what you were expecting, but here it is.
To achieve the desired behavior of showing the content corresponding to each text when the user clicks on its respective element, you will need to make some changes to the HTML code and add JavaScript.
In this example, I’ve added code to toggle the display of text corresponding to the clicked button. If the text is visible, it will be hidden and vice versa. In addition, I added a loop to hide all texts except the text corresponding to the current button that was clicked. With these changes, you can click the buttons to show and hide the corresponding content.
EDIT:
Okay I think I know what you are asking for. You want to be able to click a button or something to switch the inner HTML of these two divs.
You can accomplish that as follows:
For your HTML, you can put the onclick property directly into the top div, or you can put it in a separate button. That is up to you. For this one, I added a button on top of the div to allow you to toggle back and forth between the two options. I also put some initial styling in the divs to show whats happening.
This is the JavaScript function that will swap your divs. Basically now we are just inspecting the style of each div and if it’s visible, we make it invisible, and if it’s not visible, we make it visible. By using the none property, we assure that they will show up in the same spot.
You can put this function inside a script tag and it should work! Let me know how it goes.
I don’t know if this is correct, but i add this answer just in case.
I understand that instead of swapping the contents of text1 and text2, you want to hide one and make the other visible. I hope the code below helps.
This should work.
Just add your icon instead of