faqts : Computers : Programming : Languages : JavaScript : Windows

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

17 of 22 people (77%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

How can I put centered text in an alert box?

Apr 3rd, 2000 10:50
Martin Honnen, Marc de Wree,


That makes only sense if you have multiple input lines. Then you can 
use JavaScript to pad the lines to appear centered:

function centeredAlert (string) {
  var lines = string.split(/\r\n|\r|\n/);
  var max = 0;
  for (var l = 0; l < lines.length; l++)
    if (max < lines[l].length)
      max = lines[l].length;
  for (var l = 0; l < lines.length; l++) {
    var s = Math.floor((max - lines[l].length) / 2);
    var r = '';
    for (var i = 0; i < s; i++)
      r += ' ';
    lines[l] = r + lines[l] + r;
  }
  string = lines.join('\n');
  alert(string);
}

centeredAlert(
  'Is\nthis text\nappearing being\ncentered in the alert box?'
);