d4rty d4rty - 6 months ago 14
Javascript Question

How to avoid moving text inside a button, when text is changing continuously?

So far I implemented a button and when the user clicks on it, it shows a loading text where every 500ms some dots appear/ disappear, to point out that something is going on.

See my example on bootply.

The problem is that the text will move inside the button. My approach was to fill the buttontext with spaces at the end, but this isn't working, because HTML interpreter will delete all mutliple spaces. Any suggestions how I can achieve that the text of the button is not moving around inside the button?

HTML:

<button id="buttonTextShowPath">Click me</button>


JS:

var refreshInterval;
var loadingBalls;
var whiteSpace;
function startAnimation() {
$("#buttonTextShowPath").html("Loading");
loadingBalls=".";
whiteSpace = " ";
refreshInterval = setInterval(function(){
$("#buttonTextShowPath").html("Loading"+loadingBalls+whiteSpace);
loadingBalls+=".";
whiteSpace.slice(1);
if(loadingBalls.length === 5){
loadingBalls=".";
whiteSpace=" ";
}
var j=loadingBalls.length+whiteSpace.length;
}, 500);
}

$("#buttonTextShowPath").click(function(){
startAnimation();
});

Answer

You may be able to use &nbsp; instead of spaces. They will affect the width of the text.

If you're not using a mono-space font, the number of &nbsp;s you need may be different from the number of .s.

Here's a version of the code that should do what you want it to:

var $btn = $('#space_button');
var originalHTML = $btn.html();
var counter = 0;

setInterval(function(){

  var newHTML = originalHTML;
  
  for (var i=0; i < counter; i++) {
  	newHTML = newHTML.replace('&nbsp;', '.');
  }
  
  $btn.html(newHTML);
  
  counter++;
  
  if (counter > 5) counter = 0;

}, 200);
#space_button {
  min-width: 180px;
  text-align: center;
  background-color: lightblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="space_button">
Hello World&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</button>

Comments