so I'm currently making a clicker game With a twist that the only thing that makes you bottles are bottlers, but they are directly upgraded along with the bottle type throughout the game until you can beat it, and here is my code so far. if you run the code you can see that pressing the upgrade button more than once only returns an error, how do I fix this? also if anyone has any tips to improve or shorten the code I'll take that as well as this is my first time coding.
<html>
<head>
<link rel="icon" href="bottle1.png">
<title>Bottle empire</title>
<style>
p.cash {
font-family: "Comic Sans MS", "Comic Sans", cursive;
position: relative;
left: -5px;
}
p.cookie {
font-family: "Comic Sans MS", "Comic Sans", cursive;
position: relative;
top: -300px;
}
</style>
</head>
<center>
<p class="cash">Cash: <span id="score">0</span></p>
</center>
<center><img src="bottle1.png" height="256px" width="256px" onclick="addToScore(1)"></center>
<Center><button onclick="upgrade()">Upgrade bottle [<span id="upgradecost">1000</span>] </button></Center>
<button onclick="buybottler()">Bottler [<span id="bottlercost">10</span>] -- <span id="bottlers">0</span></button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/3.0.0/js.cookie.min.js"></script>
<script>
var score = 1000000;
var bottlercost = 10;
var bottlers = 0;
var upgradecost = 1000;
function buybottler() {
if (score >= bottlercost) {
score = score - bottlercost;
bottlers = bottlers + 1;
bottlercost = Math.round(bottlercost * 1.15);
document.getElementById("score").innerHTML = score;
document.getElementById("bottlercost").innerHTML = bottlercost;
document.getElementById("bottlers").innerHTML = bottlers;
document.getElementById("upgradecost").innerHTML = upgradecost
}
}
function upgrade() {
if (score >= upgradecost) {
score = score - upgradecost;
upgrade = upgrade + 1;
upgradecost = upgradecost * 5;
document.getElementById("score").innerHTML = score;
document.getElementById("upgradecost").innerHTML = upgradecost
}
}
function addToScore(amount) {
score = score + amount
document.getElementById("score").innerHTML = score;
}
setInterval(function () {
score = score + bottlers
document.getElementById("score").innerHTML = score;
}, 2000); // 2000 msec = 1 sec
</script>
</body>
</html>
You're reassigning the value of upgrade in the upgrade function itself (therefore essentially removing your upgrade() function)
function upgrade() {
if (score >= upgradecost) {
score = score - upgradecost;
upgrade = upgrade + 1; // Here
...
I'm not sure what you're trying to achieve with this line, but removing it will fix your error problem
Related
So i am using this font called "Aileron" which i downloaded from here.
CSS:
#font-face {
font-family: 'Aileron SemiBold';
src: url('./fonts/Aileron-SemiBold.otf');
}
body {
font-family: 'Aileron SemiBold';
font-size: 12px;
}
Please refer the image:
Digit "2" looks smaller than the rest of the digits
This is only for SemiBold variant of the font and when font-size is between 11.7px and 12px.
For sizes lower than 11.7px and higher than 12px it works fine.
I tried the "font-variant-numeric" property but it doesn't work.
I have had similar problem with font being smaller for English than other language. I wrote some javascript code to make font-size smaller for those letters. So based on my answer I have adapted (since in your case you only care where font-size is between 11.7px and 12px I also used this answer)
function do_elem(elem) {
function getStyle(el, styleProp) {
var camelize = function(str) {
return str.replace(/\-(\w)/g, function(str, letter) {
return letter.toUpperCase();
});
};
if (el.currentStyle) {
return el.currentStyle[camelize(styleProp)];
} else if (document.defaultView && document.defaultView.getComputedStyle) {
return document.defaultView.getComputedStyle(el, null)
.getPropertyValue(styleProp);
} else {
return el.style[camelize(styleProp)];
}
}
function getFontSize(elem) {
return parseFloat(getStyle(elem, 'font-size'));
}
function textNodesUnder(node) {
var all = [];
var font_size = getFontSize(node)
for (node = node.firstChild; node; node = node.nextSibling) {
if (node.nodeType == 3) {
if (font_size >= 11.7 && font_size <= 12.0) {
all.push(node);
}
} else {
all = all.concat(textNodesUnder(node));
}
}
return all;
}
function replace_node(node, str) {
var replacementNode = document.createElement('span');
replacementNode.innerHTML = str
node.parentNode.insertBefore(replacementNode, node);
node.parentNode.removeChild(node);
}
function decorate_english(str, cls) {
var a = []
for (var i = 0; i < str.length; i++) {
var c = str.charAt(i);
if (c == 2) {
a.push("<span class=\"" + cls + "\">" + c + "</span>")
} else {
a.push(c)
}
}
return a.join("")
}
function process_text_nodes(nodes) {
for (var index = 0; index < nodes.length; index++) {
var node = nodes[index];
var value = node.nodeValue
var str = decorate_english(value, "eng2")
if (str != value) {
replace_node(node, str)
}
}
}
var nodes = textNodesUnder(elem);
process_text_nodes(nodes)
}
// fix smaller letter "2"
do_elem(document.body);
body {
font-size: 16px
}
.eng2 {
font-size: 120%;
color: red;
}
.inner {
font-size: 11.9px
}
<body>
0123456789
<div style="font-size:11.8px">
0123456789
</div>
<div style="font-size:12.8px">0123456789
<div class="inner">0123456789</div>
</div>
</body>
This issue is related to (cff based) opentype hinting.
Hinting will try to fit stems to the current pixel grid.
Unfortunately this can sometimes result in weird rendering.
As a workaround you could convert your otf to a woff2 with a tool like transfonter.
This will usually strip the original cff hinting or convert them to truetype hinting instructions (transfonter has several hinting options).
Example: unhinted woff2
#font-face {
font-family: 'Aileron_not_hinted';
src: url('data:font/woff2;charset=utf-8;base64,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') format('woff2');
font-weight: 600;
font-style: normal;
font-display: swap;
}
p{
font-size:11.8px
}
.nothinted{
font-family:'Aileron_not_hinted';
font-weight: 600;
}
<p>not hinted: <span class="nothinted">0123456789</span></p>
Expected result
Another benefit of this conversion is a smaller filesize due to woff2 more advanced file compression.
I'm working on a game named Factory Tycoon and have spotted a bug which I can't resolve myself. Every second you get plus what your items per second is on your items but it is failing to do so. Feel free to test the code. Code:
<!DOCTYPE html>
<html>
<head>
<title>Factory Tycoon</title>
<script type="text/javascript">
var money = 1000;
var items = 0;
var itemsps = 1;
var dropper1Cost = 100;
var dropper1Audio = new Audio('Audio/dropper1Sound.mp3');
function addDropper() {
if (money <= dropper1Cost - 1) {
alert('Not Enough Money.')
}
if (money >= dropper1Cost) {
dropper1Audio.play()
itemsps += 1;
money -= dropper1Cost;
dropper1Cost += 100;
}
}
setInterval(function renderMoney() {
document.getElementById('money').innerHTML = "Money:" + money;
})
setInterval(function renderItemsProcessedPS() {
document.getElementById('items').innerHTML = "Items Processed:" + items;
})
setInterval(function renderItemsProcessedPS() {
document.getElementById('itemsps').innerHTML = "Items Processed Per Second:" + itemsps;
}, 1000)
</script>
</head>
<h4 id="money"></h4>
<h4 id="items"></h4>
<h4 id="itemsps"></h4>
<body>
<img src="Images/dropper1IMG.png" onclick="addDropper()">
</html>
There isn't much code as I've only just started to develop it tonight :).
There is a few issues in the code:
<h4> elements need to be inside the <body> element
the </body> end tag is missing
the setInterval is called before all elements had a chance to load, which will make it error, so I wrapped them in an init function and called that on body load
Side note, this code can be optimized with addEventListener for the load event etc., but here you have a start
<!DOCTYPE html>
<html>
<head>
<title>Factory Tycoon</title>
<style>
span { display: inline-block; padding: 5px; background: #ddd; }
</style>
<script type="text/javascript">
var money = 1000;
var items = 0;
var itemsps = 1;
var dropper1Cost = 100;
var dropper1Audio = new Audio('Audio/dropper1Sound.mp3');
function addDropper() {
if (money <= dropper1Cost - 1) {
alert('Not Enough Money.')
}
if (money >= dropper1Cost) {
dropper1Audio.play()
itemsps += 1;
money -= dropper1Cost;
dropper1Cost += 100;
}
}
function init() {
setInterval(function renderMoney() {
document.getElementById('money').innerHTML = "Money:" + money;
})
setInterval(function renderItemsProcessedPS() {
document.getElementById('items').innerHTML = "Items Processed:" + items;
})
setInterval(function renderItemsProcessedPS() {
document.getElementById('itemsps').innerHTML = "Items Processed Per Second:" + itemsps;
}, 1000)
}
</script>
</head>
<body onload="init();">
<h4 id="money"></h4>
<h4 id="items"></h4>
<h4 id="itemsps"></h4>
<span onclick="addDropper()">Click Me</span>
</body>
</html>
I'm helping my I.T teacher to create easter eggs for some tasks, and I would like to create a countdown timer with html.
Explanation:
Everytime you enter into a website, the countdown timer starts.
Example:
I have a html code with a countdown timer at 30 min, if I go into the website, the countdown timer starts going down, but if I refresh the website, it reset.
I hope you will understand, thanks!
If you want to use only javascript, without any server-side language you could store the time that is left in the localStorage variable, because after you exit the website/browser it will stay the same;
Example:
function countdown() {
time = parseInt(localStorage.time); //All variables in localstorage are strings
//Resets timer if cannot parse the localStorage.time variable or if the time is greater than 30 mins
if(isNaN(time) || time > (30*60)) {
alert("An error occured: time left variable is corrupted, resetting timer");
localStorage.time = 30*60; //30 mins in seconds
countdown();
return null;
}
//Decrementing time and recalling the function in 1 second
time--;
localStorage.time = time;
setTimeout('countdown()', 1000);
}
You can add a function that turn seconds into: Minutes:Seconds and edit the function so it will change an element everytime it calls it self, or do something when the time reaches 0(don't forget to call it once, unless the timer won't run). Good luck!
I made a pen for you:
http://codepen.io/DaCurse0/pen/kkxVYP
It should have everything you need.
P.S: you should probably remove the alert when checking if timer is corrupted because it will show when the timer wasn't set.
html code:
<h1>Countdown Clock</h1>
<div id="clockdiv">
<div>
<span class="days"></span>
<div class="text">Days</div>
</div>
<div>
<span class="hours"></span>
<div class="text">Hours</div>
</div>
<div>
<span class="minutes"></span>
<div class="text">Minutes</div>
</div>
<div>
<span class="seconds"></span>
<div class="text">Seconds</div>
</div>
</div>
css code:
#clockdiv{
font-family: sans-serif;
color: #fff;
display: inline-block;
font-weight: 100;
text-align: center;
font-size: 30px;
}
#clockdiv > div{
padding: 10px;
border-radius: 3px;
background: #00BF96;
display: inline-block;
}
#clockdiv div > span{
padding: 15px;
border-radius: 3px;
background: #00816A;
display: inline-block;
}
.text{
padding-top: 5px;
font-size: 16px;
}
javascript code:
function getTimeRemaining(endtime) {
var t = Date.parse("June 31,2017") - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(id, endtime) {
var clock = document.getElementById(id);
var daysSpan = clock.querySelector('.days');
var hoursSpan = clock.querySelector('.hours');
var minutesSpan = clock.querySelector('.minutes');
var secondsSpan = clock.querySelector('.seconds');
function updateClock() {
var t = getTimeRemaining(endtime);
daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
var timeinterval = setInterval(updateClock, 1000);
}
var deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000);
initializeClock('clockdiv', deadline);
in the html documnet,include the new files:
<script type="text/javascript" src="assets/js/count.js"></script>
<link rel="stylesheet" type="text/css" href="assets/css/flipclock.css">
hope it works...
I'm learning HTML, CSS, and Javascript with Coder on the Raspberry pi. Currently, I'm trying to make a simple page that displays time, date, and the current weather. Something is going wrong with the $.getJSON call in the getWeather() function.
Typing the URL passed to $.getJSON works correctly (i.e., a page is loaded with all the information in JSON), but the "Got Weather" string is never displayed. I've also tried using the AJAX call requesting JSON or JSONP data type. Neither of those methods worked either. What am I missing?
$(document).ready( function() {
//This code will run after your page loads
function displayTime() {
var current_time = new Date();
var hours = current_time.getHours();
var minutes = current_time.getMinutes();
var seconds = current_time.getSeconds();
var meridiem = "AM"; // default is AM
var day = current_time.getDay();
if(seconds < 10) {
seconds = "0" + seconds;
}
if(minutes < 10) {
minutes = "0" + minutes;
}
// Set the meridiem for a 12hr clock
if(hours > 12) {
hours -= 12;
meridiem = "PM"
} else {
meridiem = "AM"
}
var clock_div = document.getElementById('clock');
clock_div.innerText = hours + ":" + minutes + ":" + seconds + " " + meridiem;
// Depending on the value of 'day', set the corresponding string
var day_div = document.getElementById('day');
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var today = weekday[current_time.getDay()];
day_div.innerText = today;
// Get the date information
var date = current_time.getDate();
// Get the year
var year = current_time.getFullYear();
// Get the month and set the string
var month = new Array(12);
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
var this_month = month[current_time.getMonth()];
// set the string
var date_div = document.getElementById('date');
date_div.innerText = this_month + " " + date + " " + year;
}
function getWeather() {
var api_key = REMOVED; // API key for open weather
var weather_api = "http://api.openweathermap.org/data/2.5/weather?lat=40.115&lon=-88.27&units=imperial&appid=" + api_key;
var weather_div = document.getElementById('weather');
$.getJSON(weather_api).then(function(result){
//alert("City: "+result.city.name);
//alert("Weather: "+ result.list[0].weather[0].description);
weather_div.innerText = "Got Weather";
});
//weather_div.innerText = "Got Weather";
}
// This runs the displayTime function the first time
displayTime();
getWeather();
// This makes the clock "tick" repeatedly by calling it every 1000 ms
setInterval(displayTime, 1000);
setInterval(getWeather, 2000);
});
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Coder</title>
<meta charset="utf-8">
<!-- Standard Coder Includes -->
<script>
var appname = "{{app_name}}"; //app name (id) of this app
var appurl = "{{&app_url}}";
var staticurl = "{{&static_url}}"; //base path to your static files /static/apps/yourapp
</script>
<link href="/static/apps/coderlib/css/index.css" media="screen" rel="stylesheet" type="text/css"/>
<script src="/static/common/js/jquery.min.js"></script>
<script src="/static/common/ace-min/ace.js" type="text/javascript" charset="utf-8"></script>
<script src="/static/apps/coderlib/js/index.js"></script>
<script>
Coder.addBasicNav();
</script>
<!-- extra inludes to get weather from OpenWeather -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.0.min.js"><\/script>')</script>
<script src="js/vendor/jquery-ui.min.js"></script>
<!-- End Coder Includes -->
<!-- This app's includes -->
<link href="{{&static_url}}/css/index.css" media="screen" rel="stylesheet" type="text/css"/>
<script src="{{&static_url}}/js/index.js"></script>
<!-- End apps includes -->
</head>
<body>
<div id='day'></div><br>
<div id='date'></div>
<div id='clock'></div>
<div id='weather'></div>
</body>
</html>
CSS:
body {
background-color: black;
}
#day {
height:100px;
width: 300px;
margin-left: 10px;
padding-top: 50px;
position: fixed;
top: 0px; left: 20px;
font-family: courier, monospace;
text-align: center;
color: white;
font-size: 30px;
font-weight: bold;
}
#date {
height:100px;
width: 300px;
margin-left: 10px;
padding-top: 50px;
position: fixed;
top: 50px; left: 20px;
font-family: courier, monospace;
text-align: center;
color: white;
font-size: 20px;
}
#clock {
height:100px;
width: 300px;
margin-left: 10px;
padding-top: 50px;
position: fixed;
top: 100px; left: 20px;
font-family: courier, monospace;
text-align: center;
color: white;
font-size: 20px;
}
I found the issue. Opening up the developer console showed an error along the lines of "Blocked loading mixed active content...". It seems I need to better familiarize myself with the developer tools.
Apps built within Coder are accessed over HTTPS. However, the call to openweather is over HTTP. The openweather API permits HTTPS calls only if you have a pro (paid) subscription. Fortunately, https://forecast.io allows a set number of free calls per day and uses HTTPS.
I've got a problem with this script. I don't know how to make dynamic rgb using this. I am javascript noob. I have used three vars and saved using getElementById. And I dont know how to save it to style from the spans.
var i = 0;
var ii = 20;
var iii = 18;
function increment() {
i++;
document.getElementById('number').innerHTML = i;
if (i==255) {
document.getElementById('number').innerHTML = i--;
}
}
function increment2() {
ii++;
document.getElementById('pica').innerHTML = ii;
if (ii==255) {
document.getElementById('pica').innerHTML = ii--;
}
}
function increment3() {
iii++;
document.getElementById('dick').innerHTML = iii;
if (iii==255) {
document.getElementById('dick').innerHTML = iii--;
}
}
setInterval('increment()', 50);
setInterval('increment2()', 60);
setInterval('increment3()', 55);
var rgb = document.getElementById('rgb').innerHTML;
document.write(rgb);
And this is html:
<div id="rgb">
<span id="number"></span>
<span id="pica"></span>
<span id="dick"></span>
</div>
This is the rgb I need make dynamic:
<div id="id" style="background-color: rgb(255,255,255);
width: 100%; height: 100%;"></div>
JQuery is a javascript plugin very used. With it javascript becomes simplier.
In JQuery you can access to css properties of an object very simply using .css() function
Here you have a big tutorial about JQuery.
Here you have the Stack overflow guide about JQuery.
Try this
var r = $('#number').html();
var g = $('#pica').html();
var b = $('#dick').html();
$("#id").css("background-color", "rgb(" + r + "," + g + "," + b + ")");
Try this
Guidance:
I think your way to code is inappropiate. By using bad variables name and so one, you do not save time. You confuse yourself.
1/ Make unique function that modify a rgb value ex
function increment(value)
{
value += 1;
if (value == 256) {
return 255;
}
return value;
}
2/ Instead of using span maybe another solution exist?
/**
* Where we are storing the colors
*/
const colors = {
red: 0,
green: 0,
blue: 0,
};
/**
* Increment the color by one
*/
function increment(value) {
value += 1;
return value == 256 ? 0 : value;
}
/**
* Gives a random number so we can increase a random color
*/
function getRandomNumber(maxNumber) {
return Math.floor(Math.random() * Math.floor(maxNumber));
}
/**
* Function that's incrementing the colors
*/
function incrementBackground() {
const randomColorIndexToChange = getRandomNumber(Object.keys(colors).length - 1);
const keyOfTheColorToChange = Object.keys(colors)[randomColorIndexToChange];
colors[keyOfTheColorToChange] = increment(colors[keyOfTheColorToChange]);
$('#myDynamicBackground').css(
'background-color',
`rgb(${colors.red}, ${colors.green},${colors.blue})`,
);
setTimeout(incrementBackground, 1);
}
setTimeout(incrementBackground, 1);
#myDynamicBackground {
background-color: rgb(0, 0, 0);
width: 5em;
height: 5em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDynamicBackground"></div>
You could leverage the following code, which (after making only minor changes to yours) calls the updateBgColorDynamically() method. Which in turn used the .style.backgroundColor and a string concatenation to update the color.
<html lang="en">
<head>
<meta charset="utf-8">
<title>IrishGeek82 SO Help File</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<link href='http://fonts.googleapis.com/css?family=Roboto:400,700,300,400italic,700italic' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" />
<script>
$(document).ready(function()
{
increment1();
increment2();
increment3();
}
);
</script>
<style type="text/css">
.invalid
{
border:1px solid red;
}
.noSelect
{
-webkit-touch-callout: none;
-webkit-user-select: none;
-webkit-tap-highlight-color: rgba(0,0,0,0);
-webkit-tap-highlight-color: transparent;
}
</style>
<script type="text/javascript">
var iRed = 0;
var iGreen = 20;
var iBlue = 18;
function increment1()
{
iRed++;
document.getElementById('red').innerHTML = iRed;
if (iRed == 255)
{
document.getElementById('red').innerHTML = 0;
}
updateBgcolorDynamically();
}
function increment2() {
iGreen++;
document.getElementById('green').innerHTML = iGreen;
if (iGreen==255)
{
document.getElementById('green').innerHTML = 0;
}
updateBgcolorDynamically();
}
function increment3()
{
iBlue++;
document.getElementById('blue').innerHTML = iBlue;
if (iBlue == 255)
{
document.getElementById('blue').innerHTML = 0;
}
updateBgcolorDynamically();
}
function updateBgcolorDynamically()
{
document.getElementById("dynamicDiv").style.backgroundColor = "rgb("+iRed+","+iGreen+","+iBlue+")";
}
</script>
</head>
<body>
<div id="rgb">
<span class ="noSelect" id="red" onclick="increment1();">0</span>
<span class ="noSelect" id="green" onclick="increment2();">0</span>
<span class ="noSelect" id="blue" onclick="increment3();">0</span>
<hr>
<div id="dynamicDiv" style="background-color:rgb(255,255,255);min-width: 100%; min-height: 500px;">
</div>
</div>
</body>
</html>
Please let me know if that helps :)
Try this
document.getElementById('id').style.backgroundColor = 'rgb(' + [a,b,c].join(',') + ')';
use HSL It's all you need.
jsBin demo
var $div = document.getElementById('id'),
c = 0;
function changeColor(){
++c; // increment counter
$div.style.backgroundColor = "hsl("+( c%360 )+", 50%, 50%)";
}
setInterval(changeColor, 50);
Simply change the Hue dynamically, while keeping a desired Saturation to 50% and Lightness to 50%.
Hue values are from 0 to 360, (0=red, 360=red) and in between you have all your colors palette.
c%360 (%=Reminder operator) is used to reset our c counter back to 0.
hsl( HUE[0-360] , SATURATION[0-100%] , LIGHTNESS[0-100%]);
Expore also HSLA colors if you need opacity ;)