Chachamaru Nyan
Chachamaru Nyan

Reputation: 1

Changing font size and modifying Javascript Show/Hide Toggle

I'm a total beginner in Javascript, and I came across this script for a show/hide toggle:

<script language="javascript">
function toggle() {
var ele = document.getElementById("toggleText");
var text = document.getElementById("displayText");
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "show";
}
else {
ele.style.display = "block";
text.innerHTML = "hide";
}
} 
</script>

I would like to change the font size of the "show" and "hide" in this code. Seems like a really easy task, but I've looked everywhere and can't find an answer.

Also another question, how could I modify the code so that I don't have to copy and paste the whole code and changing toggle() to toggle2(), toggle3() for each separate show/hide toggle on the same page?

Thank you very much!

Upvotes: 0

Views: 568

Answers (2)

Matt Greenberg
Matt Greenberg

Reputation: 2330

You can use element.style.fontSize to dynamically set the font size of an element.

function toggle() {
  var ele = document.getElementById("toggleText");
  var text = document.getElementById("displayText");
  if(ele.style.display == "block") {
  ele.style.display = "none";
  text.style.fontSize = "50px";
  text.innerHTML = "show";
  } else {
  ele.style.display = "block";
  text.style.fontSize = "30px";
  text.innerHTML = "hide";
  }
}

document.getElementById("displayText").addEventListener('click', function(){

		toggle();

});
#toggleText{
  display:none;
}
#displayText{
  color: #00af00;
  background: #d9d9d9;
  padding: 4px 20px;
  display: inline-block;
  text-decoration:none;
}
<p id="displayText">show</p>
<div id="toggleText">
Hidden or naw?
</div>

Upvotes: 1

Ray
Ray

Reputation: 637

You don't have to create toggle2, toggle3, This will make your code redundant. Instead, add a parameter on your toggle to pass the toggleText.

<script language="javascript">
function toggle(toggleText) {
var ele = document.getElementById(toggleText);
var text = document.getElementById("displayText");
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "show";
}
else {
ele.style.display = "block";
text.innerHTML = "hide";
}
} 
</script>

For the font, you can have this on your css.

<style>
#displayText {
    font: bold 12px Georgia, serif;
}
</style>

Upvotes: 0

Related Questions