I’m trying to make a code box you can see in image . My question is how can ı change code in code tag when click another language button ?
<div class="container"> <div class="row align-items-center py-1"> <div class="embedcontainer"> <button class="language">JavaScript</button> <button class="language">PHP</button> <div class="code-wrapper"> <pre> <code id="code"> function fibonacci(num)<br/> {<br/> var num1=0;<br/> var num2=1;<br/> var sum;<br/> var i=0;<br/> for (i = 0; i < num; i++)<br/> {<br/> sum=num1+num2;<br/> num1=num2;<br/> num2=sum;<br/> }<br/> return num2;<br/> }<br/> <br/> console.log(fibonacci(155)); </pre> <button id="copy-button">Copy</button> </div> <span id="copy-success">Code copied!</span> </div> </div> </div>
Advertisement
Answer
You have to put some Javascript code. If click on JavaScript tab, display none
PHP tab data and if click on PHP tab, display none
the Javascript tab data.
Here down is code:
function openTab(evt, languageName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(languageName).style.display = "block"; evt.currentTarget.className += " active"; }
.tab { overflow: hidden; border: 1px solid #ccc; background-color: #f1f1f1; } .tab button { background-color: inherit; float: left; border: none; outline: none; cursor: pointer; padding: 14px 16px; transition: 0.3s; font-size: 17px; } .tab button:hover { background-color: #ddd; } .tab button.active { background-color: #ccc; } .tabcontent { display: none; padding: 6px 12px; border: 1px solid #ccc; border-top: none; }
<div class="container"> <div class="row align-items-center py-1"> <div class="embedcontainer"> <div class="tab"> <button class="tablinks" onclick="openTab(event, 'JavaScript')">JavaScript</button> <button class="tablinks" onclick="openTab(event, 'PHP')">PHP</button> </div> <div id="JavaScript" class="tabcontent"> <pre> <code id="code"> JavaScript code </code> </pre> <button id="copy-button">Copy</button> </div> <div id="PHP" class="tabcontent"> <pre> <code id="code"> PHP code </code> </pre> <button id="copy-button">Copy</button> </div> </div> </div> </div>