d4rty d4rty - 1 year ago 67
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?


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


var refreshInterval;
var loadingBalls;
var whiteSpace;
function startAnimation() {
whiteSpace = " ";
refreshInterval = setInterval(function(){
if(loadingBalls.length === 5){
whiteSpace=" ";
var j=loadingBalls.length+whiteSpace.length;
}, 500);


Answer Source

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;


  var newHTML = originalHTML;
  for (var i=0; i < counter; i++) {
  	newHTML = newHTML.replace('&nbsp;', '.');
  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;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download