How to increase size of emoji using 'ArrowUp' in Javascript - javascript

I'm trying to continually increase the size of the balloon emoji 10px when a user pushes the up arrow as well as decrease size by 10px with down arrow on keypad.
I've been trying to set:
let size = para.style.fontSize;
in order to get a variable for the size and then adjust that value by adding +/- 10px in my function. However, I've tried this method and it seems as if you can not set:
para.style.fontSize = size +10;
Does anybody have any suggestions to get this to work?
Note: I have not included the size variable in the code below as I found it does not work.
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
p {
font-size: 50px;
}
</style>
</head>
<body>
<p>🎈</p>
<script>
let para = document.querySelector('p');
window.addEventListener("keydown", e => {
if (e.key == "ArrowUp") {
para.style.fontSize = '60px';
} else {
para.style.fontSize = '40px';
}
});
</script>
</body>
</html>

To achieve growing/shrinking behavior over multiple keydown events, you'll need to increment/decrement para.style.fontSize per event. Once way this could be done is as follows:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
p {
font-size: 50px;
}
</style>
</head>
<body>
<p>🎈</p>
<script>
let para = document.querySelector('p');
window.addEventListener("keydown", e => {
let currentSize = parseInt(para.style.fontSize);
// If unable to determine current fontSize, default to 50
if (isNaN(currentSize)) {
currentSize = 50;
}
// Define the rate of change
let changeAmount = 5;
if (e.key == "ArrowUp") {
para.style.fontSize = (currentSize + changeAmount) + 'px';
} else {
// Protect againt zero or negative font sizes via Math.max()
para.style.fontSize = Math.max(changeAmount, currentSize - changeAmount) + 'px';
}
});
</script>
</body>
</html>

The issue is that the current fontSize property was null so you can't add to a null value. The second issue is that the fontSize property is actually a string with "px". So if you want to increase or decrease the value, you need to parse out the integer value. Then, when you assign it back to para.style.fontSize, you need to append "px" back.
Here is your code with the changes described above.
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
p {
font-size: 50px;
}
</style>
</head>
<body>
<p>🎈</p>
<script>
let para = document.querySelector('p');
// Set to default size
para.style.fontSize = '24px';
window.addEventListener("keydown", e => {
var sizeAsInteger = parseInt(para.style.fontSize, 10);
if (e.key == "ArrowUp") {
sizeAsInteger += 10;
} else {
sizeAsInteger -= 10;
}
para.style.fontSize = sizeAsInteger + 'px';
});
</script>
</body>
</html>

Note that if you grab the size and then do console.log(size), you will get a blank result for the first round (because it's initially not set) and all subsequent rounds you get the size with px appended to the end. Thus, size + 10 with an initial size of 40px will give you 40px10. This results in undesired behavior.
To fix this, you need to remove the px, convert to a number, then append the px again:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
p {
font-size: 50px;
}
</style>
</head>
<body>
<p>🎈</p>
<script>
let para = document.querySelector('p');
window.addEventListener("keydown", e => {
let size = para.style.fontSize.replace('px', '');
size = size == '' ? '50' : size; // size may not be initialized, so default to our intended starting value!
size = parseInt(size);
if (e.key == "ArrowUp") {
para.style.fontSize = (size + 10) + 'px';
} else {
para.style.fontSize = (size - 10) + 'px';
}
});
</script>
</body>
</html>

Related

Ascii Art Animation in Browser

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>

Cannot delete buttons using js

I can't delete two <button> tags using javascript. When you enter the wrong pin, I want the buttons to delete themselves but somehow it's not working.
var radar = document.getElementsByTagName("button");
var pin = 3778;
var pin_request = prompt("Podaj pin")
if (pin_request == pin) {
document.write("Podany pin: " + pin_request);
alert("Podano właściwy pin.");
} else {
document.write("odmowa dostępu.");
radar.parentNode.removeChild(radar);
}
<html>
<head>
<meta charset="UTF-8">
<style>
html {
text-align: center;
padding: 7em;
display: block;
}
button {
margin: 1cm;
}
</style>
</head>
<body><br>
<button>dodaj pieniÄ…dze</button>
<button>zainwestuj w nieruchomości</button>
<script src="do visual studio code.js"></script>
</body>
</html>
Also sorry for half-English code.
You can use querySelectorAll to get elements and in loop remove them.
var radar = document.querySelectorAll("button");
var pin = 3778;
var pin_request = prompt("Podaj pin")
if (pin_request == pin)
{
document.write("Podany pin: "+pin_request);
alert("Podano właściwy pin.");
}
else {
document.write("odmowa dostępu.");
radar.forEach(el=>{
el.remove();
})
}
<html>
<head>
<meta charset="UTF-8">
<style>
html{text-align:center; padding:7em; display:block;}
button{
margin:1cm;
}
</style>
</head>
<body><br>
<button>dodaj pieniÄ…dze</button>
<button>zainwestuj w nieruchomości</button>
<script src="do visual studio code.js"></script>
</body>
getElementyByTagName() returns an array of elements, but removeChild() only takes one element as an argument. If you use a loop it should work:
var parent = radar[0].parentNode
for(var i = 0; i < radar.length; i++) {
parent.removeChild(radar[i])
}
<!DOCTYPE HTML5>
<html>
<head>
<meta charset="UTF-8">
<style>
html{text-align:center; padding:7em; display:block;}
button{
margin:1cm;
}
</style>
</head>
<body><br>
<button>dodaj pieniÄ…dze</button>
<button>zainwestuj w nieruchomości</button>
<script>
var radar = document.querySelectorAll("button");
var pin = 3778;
var pin_request = prompt("Podaj pin")
if (pin_request == pin)
{
document.write("Podany pin: "+pin_request);
alert("Podano właściwy pin.");
}
else {
document.write("odmowa dostępu.");
radar.forEach(ele =>{
ele.remove();
})
}
</script>
</body>
</html>
This should work
var radar = document.getElementsByTagName("button");
var pin = 3778;
var pin_request = prompt("Podaj pin")
if (pin_request == pin)
{
document.write("Podany pin: "+pin_request);
alert("Podano właściwy pin.");
}
else {
document.write("odmowa dostępu.");
var elem = document.getElementById('btn1');
elem.parentNode.removeChild(elem);
var elem2 = document.getElementById('btn2');
elem2.parentNode.removeChild(elem2);
}
<button id = 'btn1'>dodaj pieniÄ…dze</button>
<button id = 'btn2'>zainwestuj w nieruchomości</button>

Javascript Font scaling code from body to div / element

I found some code which will scale some text when the browser window is resized and it seems to work well.
Here is the code:
document.body.setScaledFont = function (f) {
var s = this.offsetWidth,
fs = s * f;
this.style.fontSize = fs + '%';
return this
};
document.body.setScaledFont(0.35);
window.onresize = function () {
document.body.setScaledFont(0.35);
}
My question is:
How can I modify this code so the text scales when a specified div is scaled instead?
Updated code from suggested answer by #Deano. This code scales only when the browser is resized.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
#window {
border:1px dashed #ccc;
overflow: hidden;
resize: both;
text-align: center;
}
</style>
</head>
<body>
<div id="window">Scale the window</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#window').mouseup( function() {
document.getElementById('window').setScaledFont = function (f) {
var s = this.offsetWidth,
fs = s * f;
this.style.fontSize = fs + '%';
return this
};
document.getElementById('window').setScaledFont(0.35);
window.onresize = function () {
document.getElementById('window').setScaledFont(0.35);
}
});
});
</script>
</body>
</html>
document.body targets the entire body, if you want to target a specific element, use Id or class.
document.getElementById('window').setScaledFont = function (f) {
var s = this.offsetWidth,
fs = s * f;
this.style.fontSize = fs + '%';
return this
};
document.getElementById('window').setScaledFont(0.35);
window.onresize = function () {
document.getElementById('window').setScaledFont(0.35);
}
div {
font-size:2em;
}
<div id="window">Scale the window</div>
JSfiddle
Update Since the question requirement has changed :-/
You will need to use a libary like mimetic.js DEMO

jQuery Maximum characters in a div

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>

Progress bar not working in html file

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>

Categories

Resources