I'm looking for a way to fill a div with single characters.
The div should be the width of the viewport. I get the width with:
$(window).width();
JS should build a HTML-code like this:
<div id="text">ccccccccccccccccccccccccccccccccccccccccc</div>
Thanks for your inputs.
Here's a way to do it:
var char = 'i';
$('#text').html($('#text').html() + char)
var initialheight = $('#text').height();
while ($('#text').height() === initialheight) $('#text').html($('#text').html() + char)
$('#text').html($('#text').html().slice(0,-1))
#text {
word-break: break-all;
font-size: 2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="text"></div>
The way this works is that the script inserts a character int the div and gets the height. Then in repeatedly adds characters until the height changes, which indicates that more than one line has occurred. Then it trims the last character that caused it to overflow onto two lines. It's independent of any font characteristics.
Because a character size can be fixed or not accordig to the font I suggest to use a function to approximate the numbers of characters to print:
function writeMaxNumCharsInOneLine(textObj, charToWrite) {
var innWidth = textObj.innerWidth();
textObj.append('<span id="charSize" style="visibility: visible; white-space: nowrap;">' + charToWrite + '</span>');
var charSize = $('#charSize').width();
var numCharsToWrite = (innWidth / charSize).toFixed(0);
var strToWrite = charToWrite.repeat(numCharsToWrite);
$('#charSize').text(strToWrite);
charSize = $('#charSize').width();
while (charSize < innWidth) {
strToWrite = strToWrite + charToWrite;
$('#charSize').text(strToWrite);
charSize = $('#charSize').width();
}
if (charSize > innWidth) {
strToWrite = strToWrite.slice(0,-1);
}
$('#charSize').remove();
textObj.text(textObj.text() + '\n' + strToWrite);
}
$(function () {
writeMaxNumCharsInOneLine($('#text'), 'Y')
writeMaxNumCharsInOneLine($('#text'), 'a')
writeMaxNumCharsInOneLine($('#text'), 'b')
writeMaxNumCharsInOneLine($('#text'), 'c')
});
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<div id="text" style="border: double;width: 50%;height: 100px;"></div>
Next time you may want to add more information as well as what you have tried, your question doesn't show much troubleshooting on your side; however I think the code below should work or help you figure out something for what you are trying to do.
var w = $(document).width();
var d = $("#text").width();
var s = "";
do{
s+= "X";
$("#text").text(s)
d = $("#text").width();
}
while(d < w)
<div>
<span id="text"></span>
</div>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function() {
var b=$( "<span padding=0 margin=0></span>").appendTo( $("#text") );
do {
$(b).append("M");
} while ($(b).width() < $(b).parent().width() )
});
});
</script>
</head>
<body>
<div id="text"></div>
<button>Click me</button>
</body>
</html>
You mean this?
$(function() {
var windowWidth = $(window).width();
var oneCharacterWidth = $("#text").width();
var total = windowWidth / oneCharacterWidth;
$("#text").html("");
for (i = 0; i < total; i++) {
$("#text").append("c");
}
})
#text {
display:inline;
font-size:12px;
}
body {
margin:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text">c</div>
Related
I want to animate Ascii Art in the Browser.
The Ascii Art should be loaded via a text file. There are many libraries which convert but I have found none, which actually animates it.
By animation I mean a typewriter animation that speeds up over time and changes the 'zoom factor' so that the whole image is visible in the viewport at the end.
Hopefully anyone knows a libary for my problem.
I have a feeling SO doesn't like library recommendations, and actually I haven't found one, so here's some basic code to get you started.
It sets the typing speed to the old Teletype 10 chars per second and of course that can be changed, and an acceleration function can be added when you know what you want for that. Note: the txt file needs to be on the same domain to prevent CORS problems.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Typewriter print</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Courier, monospace;
font-size: 12px;
}
</style>
</head>
<body>
<div id="container">
<input id="file" type="text" value="" placeholder="Filename" />
<button onclick="loadFile()">Click to draw the file</button>
<div id="picture"></div>
</div>
<script>
let file = '';
let reader = new XMLHttpRequest();
function loadFile() {
file = document.getElementById('file').value;
reader.open('get', file, true);
reader.onreadystatechange = draw;
reader.send(null);
}
function draw() {
if (reader.readyState == 4) {
const picture = document.getElementById('picture');
picture.innerHTML = '';
let str = reader.responseText;
let chs = str.split('');
//set as the typing speed in characters
//per second 10 is the old teletype speed
let chsPerSec = 10;
let i = 0;
function reveal() {
if (i < chs.length) {
let nextch = chs[i];
if (nextch.charCodeAt(0) == 10) {
nextch = '<br>';
} else if (nextch.charCodeAt(0) == 32) {
nextch = '<span style="color:transparent;">.</span>';
}
picture.innerHTML = picture.innerHTML + nextch;
setTimeout(reveal, Math.floor(1000 / chsPerSec));
i++;
}
}
reveal();
}
}
</script>
</body>
</html>
I am a guitar addict and I try to make a UI for guitar tablature.
In my js code, you can see
var notes = ['s6f1', 's5f5', 's4f7', 's3f6', 's2f5', 's1f3', 's6f8',
's5f1', 's4f6', 's3f1', 's2f3', 's1f3', 's6f9', 's5f17', 's4f19'];
's6f1' means string 6 & fret 1 and I want to show it on tablature. The way I show this is to put a "1" on string 6. Please the picture below. In my code, I basically traverse the notes array and attach each note on tablature . I define each 6 six lines as a group. After a group is filled with 4 notes, a new group is shown. Since In my real application, I do not know how many notes that notes array has(In this examples, I just simplify there are 15 notes), I have to dynamically create each group and assign each line a unique id. My question is that I do not know how to attach the number on the string. For instance, after dynamically create a "six-line", how do I attach the number on the correct line. I think the challenge in my question is that I cannot predefine the location of six-liner in html. The code below is the html, css, js code that I wrote. Hope someone could help me out. Thank you in advance.
html:
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="code.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script type="text/javascript" src="code_js.js"></script>
</head>
<body>
</div>
<div id = "output">
</body>
</html>
css:
.deco {
border-bottom: 1px solid black;
width: 120px;
margin-left:0px;
margin-bottom:10px;
z-index: 2;
position: relative;
display: block;
margin-right: 20px;
}
#output {
width: 300px;
height: 200px;
position:absolute;
float:left;
background-color: yellow;
}
.six_line {
width: 125px;
height: 80px;
float:left;
margin-right: 20px;
}
js:
"use strict"
var count = 0;
var group = -1;
$(document).ready(function() {
var notes = ['s6f1', 's5f5', 's4f7', 's3f6', 's2f5', 's1f3', 's6f8', 's5f1', 's4f6', 's3f1', 's2f3', 's1f3', 's6f9', 's5f17', 's4f19'];
hideNote(notes, 0);
});
function hideNote(notes, i) {
var x = -2;
if(count == 4) {count = 0;}
if(count++ == 0) {
group++;
makeItHappen();
}
var ns4 = notes[i];
// retrive the info of string
var ns2 = ns4.substring(0,2);
x = parseInt(ns4.substring(1,2)) + (group*6);
**/*How to attach fret(#) on the string*
// finds the line with corresponding id
$('#hr' + x).attr('class', '?');
*/**
hide(function(){
if(++i < notes.length) {
hideNote(notes, i);
}
},notes[i]);
}
function hide(callback, note) {
setTimeout(function(){
callback();
}, 1000);
}
function makeItHappen() {
var six = document.createElement('div');
six.className = "six_line";
for (var i = 1; i < 7; i++) {
var hr = document.createElement('hr');
hr.className = "deco";
hr.id = "hr" + (group * 6 + i);
six.append(hr);
}
$('#output').append(six);
}
I suggest some modifications in your code.
Starting with the function that creates your strings:
function makeItHappen(nbGroup) {
for(var g = 1; g <= nbGroup; g++){
var six = document.createElement('div');
six.className = "six_line";
for (var i = 6; i >= 1; i--) {
var string = document.createElement('div');
string.className = "deco";
string.id = "string" + ('G' + g + 'S' + i);
six.append(string);
}
$('#output').append(six);
}
}
That will create all your groups of strings at the same time. It becomes easily to attribute an explicit ID for each of them : strGiSj where i is the group and j the string in the group.
Next, how about the hideNode function:
function hideNote(notes) {
makeItHappen(Math.ceil(notes.length / 4));
notes.forEach(function(n, i){
var values = n.match(/s(\d)f(\d)/); // values[1] = string, values[2] = fret
var parentEl = $("#stringG" + (Math.ceil((i + 0.5) / 4)) + "S" + values[1]);
var child = $("<div></div>")
.addClass("fret")
.css("left", (10+ (i%4) * 25) + "px")
.text(values[2]);
parentEl.append(child)
});
}
We create the amount of groups needed (amount of notes / 4 rounded to next int). For each note in your array, we retrieve the string and the fret with a regular expression /s(\d)f(\d+)/:
\d matches a digit
\d+ matches one or more digits
Parenthesis allow to retrieve values easily
Next, we just have to retrieve the appropriate group, and retrieve the associated div with good id, then create the fret element and place it.
The full code looks like this:
"use strict"
$(document).ready(function() {
var notes = ['s6f1', 's5f5', 's4f7', 's3f6', 's2f5', 's1f3', 's6f8', 's5f1', 's4f6', 's3f1', 's2f3', 's1f3', 's6f9', 's5f17', 's4f19'];
hideNote(notes);
});
function hideNote(notes) {
makeItHappen(Math.ceil(notes.length / 4))
notes.forEach(function(n, i){
var values = n.match(/s(\d)f(\d+)/);
var parentEl = $("#stringG" + (Math.ceil((i + 0.5) / 4)) + "S" + values[1]);
var child = $("<div></div>")
.addClass("fret")
.css("left", (10+ (i%4) * 25) + "px")
.text(values[2]);
parentEl.append(child)
})
}
function makeItHappen(nbGroup) {
for(var g = 1; g <= nbGroup; g++){
var six = document.createElement('div');
six.className = "six_line";
for (var i = 6; i >= 1; i--) {
var string = document.createElement('div');
string.className = "deco";
string.id = "string" + ('G' + g + 'S' + i);
six.append(string);
}
$('#output').append(six);
}
}
Here is a codepen with a working sample.
I need to truncate the text(with ... at the end) and on mouseover the entire text should get expanded.
I have tried to truncate by the below code. Problem with this code is, it expands the content on click of the ... but I need it to get opened when user mouse over anywhere on p tag
var len = 100;
var p = document.getElementById('truncateMe');
if (p) {
var trunc = p.innerHTML;
if (trunc.length > len) {
trunc = trunc.substring(0, len);
trunc = trunc.replace(/\w+$/, '');
trunc += '<a href="#" ' +
'onmouseover="this.parentNode.innerHTML=' +
'unescape(\''+escape(p.innerHTML)+'\');return false;">' +
'...<\/a>';
p.innerHTML = trunc;
}
}
DEMO
I am looking for an easy way to do it.
Thanks in advance.
PS: No CSS solution please, as it is not compatible with all browsers (IE7).
You can use Jquery Like this :
HTML :
<p>Some Text</p>
JS :
var lengthText = 30;
var text = $('p').text();
var shortText = $.trim(text).substring(0, lengthText).split(" ").slice(0, -1).join(" ") + "...";
$('p').text(shortText);
$('p').hover(function(){
$(this).text(text);
}, function(){
$(this).text(shortText);
});
DEMO : http://jsfiddle.net/1yzzbv4b/2/
Or you can also achieve this with css3 property text-overflow:ellipsis;
CSS :
p{
text-overflow:ellipsis;
width: 250px;
white-space: nowrap;
overflow: hidden;
}
p:hover{
text-overflow:clip;
width:auto;
white-space: normal;
}
DEMO : http://jsfiddle.net/1yzzbv4b/
Assuming that you set the class of your p-elements to be of escape-text, the following jQuery-code should work.
$(document).ready(function() {
$ps = $('.escape-text');
$ps.each(function(i, el) {
$(el).data('full-text', el.innerHTML);
strip(el);
});
$ps.on('mouseover', function() {
$(this).text($(this).data('full-text'));
}).on('mouseout', function() {
$(this).text(strip(this));
})
});
var length = 100;
var strip = function(el) {
el.innerHTML = el.innerHTML.substr(0, length) + '...';
}
I am creating a progrees bar is it working fine in jsfiddle demo but when i use in html file it is not working here is my code
i am writing same code as given in jsfiddle but it is not working
<html>
<head>
<style>
.ui-progressbar.beginning .ui-progressbar-value { background: red; }
.ui-progressbar.middle .ui-progressbar-value { background: yellow; }
.ui-progressbar.end .ui-progressbar-value { background: green; }
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<script>
var $progressbar = $("div").progressbar();
function updateProgressbar(current, target) {
var value = parseInt(current / target * 100);
$progressbar
.progressbar("value", value)
.removeClass("beginning middle end")
.addClass(value < 40 ? "beginning" : value < 80 ? "middle" : "end");
}
var total = 255;
var working = 0;
function update() {
working++;
updateProgressbar(working, total);
if (working < total) setTimeout(update, 10);
}
var $progressbar = $("div").progressbar();
function updateProgressbar(current, target) {
var value = parseInt(current / target * 100);
$progressbar
.progressbar("value", value)
.removeClass("beginning middle end")
.addClass(value < 40 ? "beginning" : value < 80 ? "middle" : "end");
}
var total = 255;
var working = 0;
function update() {
working++;
updateProgressbar(working, total);
if (working < total) setTimeout(update, 10);
}
</script>
</head>
<body onload="update()">
<div>
</div></body></html>
and here is js fiddle link working
http://jsfiddle.net/ZQrnC/305/
Look in the left sidebar of jsfiddle below "External Resources". You are embedding the jQuery UI css and js for your progressbar() there, but your html file jQuery UI is missing.
Add the following after your jquery-1.9.1.js-script-tag:
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
There are three reasons why it does not work:
As robbi5 stated you don't import the jquery ui JS and CSS files
Your var $progressbar is initialized in the header when the page is not already loaded and so no div can be found. In other words $progressbar points on nothing
Your progress bar has an height of zero making it invisble, you should wrap him a container div with a fixed height
Also your code contains duplicate part but it may due to a wrong copy/paste.
Here is an updated working version of your page with the corrected points. I checked rapidly only on chrome and firefox and it works.
<html>
<head>
<style>
.ui-progressbar.beginning .ui-progressbar-value { background: red; }
.ui-progressbar.middle .ui-progressbar-value { background: yellow; }
.ui-progressbar.end .ui-progressbar-value { background: green; }
</style>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
<script src=" http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script>
</head>
<script>
var $progressbar;
function updateProgressbar(current, target) {
var value = parseInt(current / target * 100);
$progressbar.progressbar("value", value).removeClass("beginning middle end")
.addClass(value < 40 ? "beginning" : value < 80 ? "middle" : "end");
}
var total = 255;
var working = 0;
function update() {
$progressbar = $("#pbholder").progressbar();
working++;
updateProgressbar(working, total);
if (working < total) setTimeout(update, 10);
}
</script>
</head>
<body onload="update()">
<div id="container" style="height:50px">
<div id="pbholder">
</div>
</div>
</body></html>
I am facing this problem.. May i know, how can i put image into this element tag,
<div id="item1"></div>
The purpose of this code below, is when the user click "+" the image will appear. And When the user click "play" button, the image that appeared, is supposed to put into the tag as mentioned above.
Unfortunately, i am not able to make the image that just appear, to be put into the tag..
I know there is hardcoding method, but sorry, i am not looking for this method..
<!DOCTYPE html>
<html>
<head>
<script src="code.jquery.com/jquery-1.7.2.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<style>
.myClass {
width: 40px; height: 40px; float:left;
padding: 1px; margin:3px; position:absolute;
left:50px; top:60px; background:blue; color:white;
}
</style>
</head>
<body bgcolor="green";>
<div id="item1" class="myClass">F1</div>
<div id="item2" class="myClass">F2</div>
<div id="item3" class="myClass">F3</div>
<script>
var predator;
var Predatorlist = [];
function addvalue()
{
Predatorlist.push(uniqueid)
alert(Predatorlist);
}
function removevalue()
{
Predatorlist.pop(uniqueid)
alert(x.innerHTML=Predatorlist);
}
//************** End of Array ***********************
function Add() {
var id = Math.floor(Math.random()*101+1);
x = Math.random() * 550;
y = Math.random() * 250;
if (document.getElementById('amount').value < 50){
document.getElementById('amount').value++;
svg = document.getElementById("main");
var id = 'predator';
uniqueid = "frog" + document.getElementById('amount').value;
//namespaces for SVG
svgNS="http://www.w3.org/2000/svg";
xlinkNS="http://www.w3.org/1999/xlink";
// create a image element
image = document.createElementNS(svgNS, 'image');
// set id and other attributes
image.setAttributeNS(null, "id", uniqueid);
image.setAttributeNS(xlinkNS, "href","jef-frog.gif");
image.setAttributeNS(null, "x", x);
image.setAttributeNS(null, "y", y);
image.setAttributeNS(null, "width", "50");
image.setAttributeNS(null, "height", "50");
// append to svg
svg.appendChild(image);
} else {
alert("we got 50");
}
}
function Remove() {
if(document.getElementById('amount').value > 0)
{
document.getElementById('amount').value--;
svg = document.getElementById("main");
svg.removeChild(svg.lastChild);
}
}
function numinput(e){
// get the input value if enter
key=e.keyCode || e.which;
if (key==13){
total = document.getElementById("amount").value;
dummy = total;
// clear svg with image to avoid clearing the canvas
svg = document.getElementById("main");
element = svg.getElementsByTagName("image");
while(element.length>0){
element = svg.getElementsByTagName("image");
element[0].parentNode.removeChild(element[0]);
}
// use the input to create the number of frog.
while (dummy>0)
{
Add();
dummy--;
}
document.getElementById("amount").value = total;
}
}
function randomRange(min,max) {
return Math.random() * (max-min) + min;
}
/* Generate some random starting position */
var startItem1X = randomRange(50,100);
var startItem1Y = randomRange(50,100);
var startItem2X = randomRange(50,100);
var startItem2Y = randomRange(50,100);
var startItem3X = randomRange(50,100);
var startItem3Y = randomRange(50,100);
var startmyClassX = randomRange(50,100);
var startmyClassY = randomRange(50,100);
var item1 = $("#item1"),cycle1;
var item2 = $("#item2"),cycle1;
var item3 = $("#item3"),cycle1;
function runItem1() {
/* Set a the starting position to be random by editing the css */
$("#item1").css("left", startItem1X+"px");
$("#item1").css("top", startItem1Y+"px");
/* Cycle1 and Cycle2 variables allow infinite loop */
(cycle1 = function() {
var m = randomRange(50,100);
var n = randomRange(75,150);
item1.appendChild(image)
item1.animate({left:'+='+n},2000);
item1.animate({left:'+='+m, top:'+='+m}, 2000)
item1.animate({left:'-='+m, top:'+='+m}, 2000)
item1.animate({left:'-='+n},2000);
item1.animate({top:'-='+n},2000,cycle1)
})();
}
function runItem2() {
$("#item2").css("left", startItem2X+"px");
$("#item2").css("top", startItem2Y+"px");
(cycle2 = function() {
var m = randomRange(50,100);
var n = randomRange(75,150);
item2.animate({top:'+='+m, left:'+='+n},2000);
item2.animate({left:'-='+n},2000);
item2.animate({left:'+='+n, top:'-='+n},2000);
item2.animate({left:'-='+n},2000)
item2.animate({top:'+='+m},2000,cycle2)
})();
}
runItem1();
runItem2();
</script>
<SVG xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" id="main" style="border:inset 1px #000000;width:600;height:300"><param name='wmode' value='transparent'/></SVG>
<img src="jef-frog.gif" alt="frogsonice.com" width="100" height="100"/><BR/>
<INPUT type="button" value="+" onClick="Add(); addvalue();">
<INPUT type="text" id="amount" value=0 maxlength="3" size="1" onkeypress="numinput(evt)">
<INPUT type="button" value="-" onClick="Remove(); removevalue();">
<INPUT type="button" value="Play" onClick="runItem1(); runItem2();">
</body>
</html>
Many thanks to whoever out there, taking time to read and trying to help.. Thanks again..
would do it.
$('#your-play-button').click(function(e) {
$('#item1').html('<img src="mygif.gif" />');
});
edit after looking into your code you could replace:
document.getElementById('amount')
by $("#amount") etc. and really work with jQuery. Because now you don't use the advantage of jQuery, but you are just writing plain javascript...
well you can add a img tag using the innerhtml property or creating the element and appending it to div. then based on your logic you can set the tag's src of the image to the desired one.