Replace Text on Click Using JavaScript
This tutorial will show you how to replace text with text by using JavaScript. The text that you click will be replaced with new text. Specifically, we will use JavaScript to hide one div and show another in it’s place. Here is a demo:
JavaScript does the magic behind the scenes. The way you accomplish this is by putting your two text fields into divs. I’ll set the first one to be visible, then when you click on it, I will hide the first and show the second in its place. I use the style.display feature of JavaScript to change whether or not it is visible or shown. Let’s take a look at the JavaScript:
<script type="text/javascript">
function toggle_text(shown, hidden) {
var e = document.getElementById(shown);
var f = document.getElementById(hidden);
if(e.style.display == 'inline') {
e.style.display = 'none';
f.style.display = 'inline';
}
else {
e.style.display = 'inline';
f.style.display = 'none';
}
}
</script>
I’m simply passing in the two divs to the JavaScript function, then JavaScript checks whether or not the first div (the shown div) is visible or not. If it is visible, it hides it and shows the hidden one. The opposite happens if it isn’t visible. Note that using inline will display your text on the same line. If we wanted it to be on its own line, we could just use block instead.
Now you just need to insert the divs into the body of the page. Here is the code used from the sample above:
<div id="shown_first" style="display:inline">
<a style="cursor:pointer" onclick="toggle_text('shown_first', 'hidden_first')">
Click me
</a>
</div>
<div id="hidden_first" style="display:none">
<a style="cursor:pointer" onclick="toggle_text('shown_first', 'hidden_first')">
I used to be hidden!
</a>
</div>





How about when you have more than 2 texts you want to change? I am building a website that has a photo gallery and I want the titles to change when I click on a thumbnail. I have some javascript that worked in IE, but not in Firefox, and I’m hoping to find another code that’ll work.
That good tutorial. You can add fade effect to text link. That maybe helpful to me.
Sirs, My business is extremely thankful just for this wonderful post. I was carrying out a research for my university project this also post helped me just in the nick of their time. I can be very grateful just for this article. Thanks a lot.