Repeating A Character Across The Full Width Of An Element
I am trying to write a function using JavaScript and jQuery (since I'm already using jQuery for my site) to detect the width of the view port and output a character repeated across
Solution 1:
This can probably be improved, but you could do it by:
- Appending a single character to the body, and get its width, then remove it.
- Divide the width of the body by the width of the character to get the number of times to repeat the character.
Example
var $char = $('<span>').css({ padding: 0, margin: 0 }).text('=').appendTo('body'),
charWidth = $char.width(),
numberOfChars = parseInt(( $('body').width() / charWidth ).toFixed(), 10);
$char.remove();
document.write( Array(numberOfChars).join('=') );
Here's a fiddle
Solution 2:
my take on it:
for (
var x = Math.floor(
$("body").append("<span>=</span>").width() / $($("body").children()[0]).width());
x > 1;
x-- && $("body").append("<span>=</span>")
);
change $("body")
to whatever element you wanna add your stuff into.
Post a Comment for "Repeating A Character Across The Full Width Of An Element"