Alan
Alan

Reputation: 1265

Javascript label position

I'm working on a morse code trainer. There are 26 audio elements (A-Z) each with a button which hides or shows the letter. The code is listed below, with only one letter for brevity.

My issue is when the display of the letter is toggled it forces a newline before printing the value. I'd like the letter to appear directly to the right of the button eliminating the newline. Better yet, would be to have each button's text toggle between "Show" and the element's letter.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CW Practice</title>
</head>
<body>
<script>

function aFunction() {
  var x = document.getElementById("aDIV");
  if (x.innerHTML === "") {
    x.innerHTML = "A";
  } else { 
    x.innerHTML = "";
  }
}

// followed by bFunction, cFunction, etc.

</script>


<audio controls>
  <source src="a.wav" type="audio/wav">
</audio>

<button onclick="aFunction()">Show <div id="aDIV"></div> </button>  

<br>
</body>


</html>

Upvotes: 0

Views: 225

Answers (1)

caramba
caramba

Reputation: 22490

use a <span> instead

function aFunction() {
  var x = document.getElementById("aDIV");
  if (x.innerHTML === "") {
    x.innerHTML = "A";
  } else { 
    x.innerHTML = "";
  }
}
<button onclick="aFunction()">Show <span id="aDIV"></span> </button>  

or if it really has to be a <div> you can set it to display: inline-block;

function aFunction() {
  var x = document.getElementById("aDIV");
  if (x.innerHTML === "") {
    x.innerHTML = "A";
  } else { 
    x.innerHTML = "";
  }
}
#aDIV {
    display: inline-block;
}
<button onclick="aFunction()">Show <span id="aDIV"></span> </button>

and now the interesting part: You could use a data-attribute containing the value you need to show. Then you don't need to repeat the function over and over again. Something like:

[...document.querySelectorAll('[data-placeholder]')].forEach( item => {
  item.addEventListener('click', (event) => {
      event.preventDefault();
      var x = item.querySelector('.placeholder');
      // this one liner is the same as your if / else
      x.innerHTML = x.innerHTML === "" ? item.dataset.placeholder : "";
  });
});
.placeholder {
    padding: 0 0 0 5px;
}
<button data-placeholder="A">Show<span class="placeholder"></span></button>
<button data-placeholder="B">Show<span class="placeholder"></span></button>
<button data-placeholder="C">Show<span class="placeholder"></span></button>

Upvotes: 1

Related Questions