I am stuck fixing my issue here with an hp bar - javascript

So I am doing an hp bar using js, I make an hp bar with 3000/3000 hp, and I have an input where I can type my damage... But When ever I type 2999, it should be 1/3000 right, and the width of the current Hp bar is 0%, the problem is, when I do 2999 again, it remains 1/3000, and it should be 0/3000, I don't know why. Heres my code:
let damage = 0;
let width = 100;
let minWidth = 0;
let text = '';
let hp = document.getElementById('hp');
let hpText = document.getElementById('hpText');
let currentHp = 3000;
let maxHp = 3000;
hpText.innerText = currentHp + '/' + maxHp;
let setUp = () => {
damage = parseInt(document.getElementById('text').value);
text = document.getElementById('text').value;
if(text.length > 0){
currentHp -= damage;
}
if(currentHp <= 0) {
currentHp = 0;
}
minWidth = (currentHp / maxHp) * 100;
let interval = setInterval(() => {
if(!(width <= minWidth)) {
if(width <= 0) {
currentHp = 0;
hpText.innerText = currentHp + '/' + maxHp;
clearInterval(interval);
alert('ha')
return;
}
width--;
hp.style.width = width + '%';
hpText.innerText = currentHp + '/' + maxHp;
if(width <= minWidth) {
alert(minWidth + " " + width)
clearInterval(interval);
return;
}
}
}, 15);
}

Why make it simple when you can make it complicated? ;)
see also for styling : Custom styling progress bar in CSS
const hp =
{ bar: document.getElementById('hp-bar')
, txt: document.getElementById('hp-bar').nextElementSibling
, itv: null
}
hp.itv = setInterval(()=>
{
hp.bar.value += 10
hp.txt.textContent = `${hp.bar.value} / ${hp.bar.max}`
if ( hp.bar.value >= hp.bar.max) clearInterval( hp.itv )
},200)
progress {
--bar-color : #0c1c499d;
width : 20em;
height : .6em;
color : var(--bar-color);
transition : All 0.2s linear;
}
progress::-moz-progress-bar {
background-color: var(--bar-color);
}
progress ~ span {
display : inline-block;
width : 6.6em;
margin-left : 1em;
padding : .1em .5em;
text-align : right;
border : 1px solid cadetblue;
border-radius : .4em;
transform : translateY(.2em);
}
<progress id="hp-bar" min="0" max="3000" value=0></progress><span>0 / 3000</span>

Related

How to save time value in dynamically created li to input box with javascript

How to save a time value in dynamically created li to input box with javascript
I have a simple timer, that starts, stops, pauses, takes a time snap and resets the time snap.
The timesnap in generated and displayed in the webpage inside a li. It all works fine what I am struggling with is trying to click on a displayed time snap and have the value placed in an input box so I can later save a selected value to a database.
This is the script I am using to place the clicked on li item into the input box
var items = document.querySelectorAll("#list li");
for (var i = 0; i < items.length; i++) {
items[i].onclick = function () {
document.getElementById("inptSnap").value = this.innerHTML;
};
}
This is the html
<div class="container">
<!-- Different App -->
<div class="timeDisplay">00:00:00</div>
<button id="begin">Start</button>
<button id="hold">Pause</button>
<button id="end">Stop</button>
<button id="timeSnap">Time Snap</button>
<button id="resetSnap">Reset Time Snap</button>
<ul id="list" class="laps"></ul>
<div>
<input type="text" id="inptSnap" />
</div>
</div>
This is the full timer script with the attempted select value onclick
var begin = document.getElementById("begin");
begin.addEventListener("click", start);
var end = document.getElementById("end");
end.addEventListener("click", stop);
var hold = document.getElementById("hold");
hold.addEventListener("click", pause);
var timeSnap = document.getElementById("timeSnap");
timeSnap.addEventListener("click", snap);
var timeSnap = document.getElementById("timeSnap");
timeSnap.addEventListener("click", pause);
var resetSnap = document.getElementById("resetSnap");
resetSnap.addEventListener("click", resetSnaps);
var ms = 0,
s = 0,
m = 0;
var timeCounter;
var displayEl = document.querySelector(".timeDisplay");
var lapsContainer = document.querySelector(".laps");
function start() {
if (!timeCounter) {
timeCounter = setInterval(run, 10);
}
}
function run() {
displayEl.textContent = displayTimeCount();
ms++;
if (ms == 100) {
ms = 0;
s++;
}
if (s == 60) {
s = 0;
m++;
}
}
function stop() {
stopTimer();
ms = 0;
s = 0;
m = 0;
displayEl.textContent = displayTimeCount();
}
function stopTimer() {
clearInterval(timeCounter);
timeCounter = false;
}
function pause() {
stopTimer();
}
function displayTimeCount() {
return (
(m < 10 ? "0" + m : m) +
":" +
(s < 10 ? "0" + s : s) +
":" +
(ms < 10 ? "0" + ms : ms)
);
}
function snap() {
if (timeCounter) {
var li = document.createElement("li");
li.innerText = displayTimeCount();
lapsContainer.appendChild(li);
}
}
function resetSnaps() {
lapsContainer.innerHTML = "";
}
// Script to put lap into input box
var items = document.querySelectorAll("#list li");
for (var i = 0; i < items.length; i++) {
items[i].onclick = function () {
document.getElementById("inptSnap").value = this.innerHTML;
};
}
This is the CodePen Link
I would be very grateful for any pointers and advice, thanks
You can do somthing like that...
PS: I think that the ergonomics of your button is to be reviewed, I did a kind of revision.
const
btStartPause = document.querySelector('#container button:nth-of-type(1)')
, btStopClear = document.querySelector('#container button:nth-of-type(2)')
, btSnap = document.querySelector('#container button:nth-of-type(3)')
, snapList = document.querySelector('ol')
, inptSnap = document.querySelector('input#inptSnap')
, chrono = ((dZTime='#container time') =>
{
const
displZone = document.querySelector(dZTime)
, chronoZero = '00:00:00.000'
, one_Sec = 1000
//, one_Min = one_Sec * 60
//, one_Hrs = one_Min * 60
, n_Dgts = (n,t) => `${t}`.padStart(n,'0')
;
let startTime = null
, timeElapsed = 0
, pausedTime = 0
, reqRef = null
, reqPause = false
, stoped = false
;
displZone.textContent = chronoZero
function reqLoop(timeStamp) // timeStamp is float
{
startTime ??= timeStamp // Logical nullish assignment (??=)
if (stoped)
{
cancelAnimationFrame(reqRef)
return
}
if (reqPause)
{
pausedTime = (timeStamp - startTime) - timeElapsed;
}
else
{
timeElapsed = ((timeStamp - startTime) - pausedTime) | 0 // get integer part of float
let
Tms = timeElapsed % one_Sec
, tim = (timeElapsed - Tms) / one_Sec
, T_s = tim % 60
, T_m = 0
, T_h = 0
;
tim = (tim - T_s) / 60
T_m = tim % 60
T_h = (tim - T_m) / 60
displZone.textContent = `${n_Dgts(2,T_h)}:${n_Dgts(2,T_m)}:${n_Dgts(2,T_s)}.${n_Dgts(3,Tms)}`
}
requestAnimationFrame( reqLoop )
}
const jso =
{ dispSz: chronoZero.length
, getVal: ()=> displZone.textContent
, start() { reqRef = requestAnimationFrame(reqLoop) }
, pause(OnOff) { reqPause = OnOff }
, stop() { stoped = true }
, RaZ()
{
startTime = null
timeElapsed = 0
pausedTime = 0
reqRef = null
reqPause = false
stoped = false
displZone.textContent = chronoZero
}
}
Object.freeze(jso)
return jso
})()
;
btStartPause.onclick =_=>
{
if (btStartPause.classList.toggle('pause') )
{
btStopClear.disabled = false
if ( btStartPause.dataset.lib !== 'continue' )
{
btStartPause.dataset.lib = 'continue'
chrono.start()
}
else
chrono.pause(false)
}
else
{
btStopClear.disabled = true
btStopClear.classList.remove('clear')
chrono.pause(true)
}
}
btStopClear.onclick =_=>
{
if (btStopClear.classList.toggle('clear') )
{
btStartPause.disabled = true
btStartPause.dataset.lib = 'start'
btStartPause.classList.remove('pause')
chrono.stop()
}
else
{
btStartPause.disabled = false
btStopClear .disabled = true
chrono.RaZ()
}
}
btSnap.onclick =_=>
{
snapList
.appendChild( document.createElement('li'))
.innerHTML = chrono.getVal()
+ '<span title="delete"> ✖ </span>'
+ '<span title="copy"> &#x2398 </span>'
}
snapList.onclick =({target}) =>
{
if (!target.matches('li > span'))
{
inptSnap.value = target.closest('li').textContent.substring(0, chrono.dispSz)
inptSnap.focus()
return
}
if (target.matches('span[title=delete]'))
{
target.closest('li').remove()
}
if (target.matches('span[title=copy]'))
{
let origin = target.closest('li')
copySomething ( origin.textContent.substring(0, chrono.dispSz), origin )
}
}
async function copySomething(toCopy, el )
{
try
{
await navigator.clipboard.writeText(toCopy);
el.classList.add('copyOK')
setTimeout(() => { el.classList.remove('copyOK')}, 1200);
}
catch (err)
{
el.classList.add('copyBad')
setTimeout(() => { el.classList.remove('copyBad')}, 1200);
console.error('Failed to copy :/', err);
}
}
body {
font-family : Arial, Helvetica, sans-serif;
font-size : 16px;
}
time {
display : block;
font-size : 1.4rem;
margin : .6rem 1rem;
letter-spacing : .2rem;
}
ol {
list-style : none;
font-size : 1.6rem;
padding : 0;
margin : 1.5rem;
width : 15rem;
list-style-type: decimal;
}
li {
border : 1px solid lightblue;
padding : .3rem .6rem;
position : relative;
cursor : pointer;
}
li::marker {
font-size : .9rem;
color : darkslategray;
}
li span {
float : right;
margin : 0 0 0 .3em;
font-size : 1.2rem;
color : darkslategray;
}
li span[title=delete]:hover {
color : crimson;
}
li span[title=copy]:hover {
background : white;
color : darkblue;
}
#container button {
min-width : 4.4rem;
text-transform : capitalize;
}
#container button:before {
content : attr(data-lib)
}
#container button.pause:before {
content : 'pause'
}
#container button.clear:before {
content : 'clear'
}
li:hover {
background : lightblue;
}
li.copyOK::after,
li.copyBad::after {
position : absolute;
display : block;
font-size : .8rem;
top : 1.2rem;
left : 11rem;
padding : .1rem .2rem;
}
li.copyOK::after {
content : 'copied';
background : lightgreen;
}
li.copyBad::after {
left : 1rem;
content : 'Failed to copy :/';
background : lightcoral;
}
<input type="text" id="inptSnap" >
<hr>
<div id="container">
<time datetime="00:00:00.000">00:00:00.000</time>
<button data-lib="start"><!-- start / continue / pause --></button>
<button data-lib="stop" disabled><!-- stop / clear --></button>
<button>snap</button>
</div>
<ol></ol>
for info :
Fastest way to cast a float to an int in javascript?
So I understand that you need a place value kind of thing.
var begin = document.getElementById("begin");
begin.addEventListener("click", start);
var end = document.getElementById("end");
end.addEventListener("click", stop);
var hold = document.getElementById("hold");
hold.addEventListener("click", pause);
var timeSnap = document.getElementById("timeSnap");
timeSnap.addEventListener("click", snap);
var timeSnap = document.getElementById("timeSnap");
timeSnap.addEventListener("click", pause);
var resetSnap = document.getElementById("resetSnap");
resetSnap.addEventListener("click", resetSnaps);
var ms = 0,
s = 0,
m = 0;
var timeCounter;
var displayEl = document.querySelector(".timeDisplay");
var lapsContainer = document.querySelector(".laps");
function start() {
if (!timeCounter) {
timeCounter = setInterval(run, 10);
}
}
function run() {
displayEl.textContent = displayTimeCount();
ms++;
if (ms == 100) {
ms = 0;
s++;
}
if (s == 60) {
s = 0;
m++;
}
}
function stop() {
stopTimer();
ms = 0;
s = 0;
m = 0;
displayEl.textContent = displayTimeCount();
}
function stopTimer() {
clearInterval(timeCounter);
timeCounter = false;
}
function pause() {
stopTimer();
}
function displayTimeCount() {
return (
(m < 10 ? "0" + m : m) +
":" +
(s < 10 ? "0" + s : s) +
":" +
(ms < 10 ? "0" + ms : ms)
);
}
function snap() {
if (timeCounter) {
var input = document.createElement("input");
input.value = displayTimeCount();
lapsContainer.appendChild(input);
}
}
function resetSnaps() {
lapsContainer.innerHTML = "";
}
// Script to put lap into input box
var items = document.querySelectorAll("#list li");
for (var i = 0; i < items.length; i++) {
items[i].onclick = function () {
document.getElementById("inptSnap").value = this.innerHTML;
};
}
.timeDisplay {
font-size: 32px;
}
ul li {
list-style: none;
font-size: 32px;
}
.container {
width: 400px;
margin: auto;
}
<div class="container">
<!-- Different App -->
<div class="timeDisplay">00:00:00</div>
<button id="begin">Start</button>
<button id="hold">Pause</button>
<button id="end">Stop</button>
<button id="timeSnap">Time Snap</button>
<button id="resetSnap">Reset Time Snap</button>
<ul id="list" class="laps">
</ul>
<div>
<input type="text" id="inptSnap" />
</div>
</div>

My Code for web resources javascript is running on chrome but not in IE 11 of dynamics crm

My java-script Code for on-load event is running successfully in chrome and not working in IE 11. Don't know why its happening .Please help me, i searched a lot and not found the correct solutions.i am working the java-script for dynamics crm 2011 but not able to get the job done.Any changes is not showing in IE 11 but showing in chrome.I am adding my code below.
function calculateManHour() {
debugger;
var advantageManHourCost = 0;
var engageManHourCost = 0;
var advantageManDayCost = 0;//new
var engageManDayCost = 0;//new
var advantageManHour = 0;
var engageManHour = 0;
var advantageManDay = 0;//new
var engageManDay = 0;//new
var currentQuoteProductId = Xrm.Page.data.entity.getId().toString().split("{")[1].split("}")[0];
var costPricePerUnit = parseFloat(Xrm.Page.getAttribute("costprice").getValue());
var serviceProvider = Xrm.Page.getAttribute("serviceprovider").getValue()[0].name;
var quoteProductType = Xrm.Page.getAttribute("quoteproducttype").getValue();
var quoteProductElem = Xrm.Page.getAttribute("quoteproducttype");
var config = getRecord("manhourcostconfigSet", "2A7F8D4D-10C4-E911-943A-00155D1E13EA");
var currentQuoteProduct = getRecord("QuoteDetailSet", currentQuoteProductId);
advantageManHourCost = parseFloat(config.ManHourCost.Value);
engageManHourCost = parseFloat(config.EngageManhourcost.Value);
advantageManDayCost = parseFloat(config.AdvantageMandaycost.Value);//new
engageManDayCost = parseFloat(config.EngageMandaycost.Value);//new
if (quoteProductType == false) {
Xrm.Page.getAttribute("valueoffering").setValue(true);
if (serviceProvider == "Services_ADVANTAGE") {
advantageManHour = costPricePerUnit / advantageManHourCost;
advantageManDay = costPricePerUnit / advantageManDayCost;
engageManHour = null;
engageManDay = null;
Xrm.Page.getControl("engagebudgetedmanhours").setVisible(false);
Xrm.Page.getControl("engagemandaycost").setVisible(false);
setTooltip("advantagemandaycost", advantageManDayCost, "advantagebudgetedmanhours", advantageManHourCost);
}
if (serviceProvider == "Services_ENGAGE") {
engageManHour = costPricePerUnit / engageManHourCost;
engageManDay = costPricePerUnit / engageManDayCost;
advantageManHour = null;
advantageManDay = null;
Xrm.Page.getControl("advantagebudgetedmanhours").setVisible(false);
Xrm.Page.getControl("advantagemandaycost").setVisible(false);
setTooltip("engagemandaycost", engageManDayCost, "engagebudgetedmanhours", engageManHourCost);
}
var data = {
"engagebudgetedmanhours": engageManHour,
"advantagebudgetedmanhours": advantageManHour,
"engagemandaycost": engageManDay,
"advantagemandaycost": advantageManDay
}
Xrm.Page.getAttribute("advantagebudgetedmanhours").setValue(advantageManHour);
Xrm.Page.getAttribute("engagebudgetedmanhours").setValue(engageManHour);
Xrm.Page.getAttribute("advantagemandaycost").setValue(advantageManDay);//new
Xrm.Page.getAttribute("engagemandaycost").setValue(engageManDay);//new
Xrm.Page.getAttribute("engagebudgetedmanhours").setSubmitMode("always");
Xrm.Page.getAttribute("advantagebudgetedmanhours").setSubmitMode("always")
Xrm.Page.getAttribute("engagemandaycost").setSubmitMode("always");//new
Xrm.Page.getAttribute("advantagemandaycost").setSubmitMode("always")//new
Xrm.Page.data.entity.save();
}
}
function setTooltip(attribute1, tip1, attribute2, tip2) {
debugger;
try {
if (!attribute1 || !tip1 && !attribute2 || !tip2) {
return;
}
var control1 = Xrm.Page.getControl(attribute1);
var control2 = Xrm.Page.getControl(attribute2);
if (!control1 || !control2) {
return;
}
var element1 = document.getElementById(attribute1 + "_d");
var element2 = document.getElementById(attribute2 + "_d");
if (!element1 || !element2) {
return;
}
var tooltipSpan1 = document.createElement("span");
tooltipSpan1.id = attribute1 + "_tooltip";
tooltipSpan1.textContent = "Man Day Cost is = " + tip1;
tooltipSpan1.setAttribute(
"style",
"display: none; width: 120px; background-color: #fdfafa; color: ; rgb(23, 22, 22): center; padding: 5px 5px; border-radius: 3px;" +
"border: 1px solid black;z-index: 1;"
);
var tooltipSpan2 = document.createElement("span");
tooltipSpan2.id = attribute1 + "_tooltip";
tooltipSpan2.textContent = "Man Hour Cost is = " + tip2;
tooltipSpan2.setAttribute(
"style",
"display: none; width: 120px; background-color: #fdfafa; color: ; rgb(23, 22, 22): center; padding: 5px 5px; border-radius: 3px;" +
"border: 1px solid black;z-index: 1;"
);
element1.appendChild(tooltipSpan1);
element2.appendChild(tooltipSpan2);
document.getElementById(attribute1 + "_c").setAttribute("title", "Man Day Cost is = " + tip1);
document.getElementById(attribute2 + "_c").setAttribute("title", "Man Hour Cost is = " + tip2);
element1.addEventListener("mouseover", (e) => {
tooltipSpan1.style.display = "inline";
tooltipSpan1.style.top = (e.clientX + 20) + 'px';
tooltipSpan1.style.left = (e.clientY + 20) + 'px';
});
element1.addEventListener("mouseout", (e) => {
tooltipSpan1.style.display = "none";
});
element2.addEventListener("mouseover", (e) => {
tooltipSpan2.style.display = "inline";
tooltipSpan2.style.top = (e.clientX + 20) + 'px';
tooltipSpan2.style.left = (e.clientY + 20) + 'px';
});
element2.addEventListener("mouseout", (e) => {
tooltipSpan2.style.display = "none";
});
} catch (e) {
console.log(e);
}
}
You're using arrow => functions. IE11 doesn't support them. Arrow function come under ES6 which is not yet supported by IE11.
There are lot of online tools which will help you convert ES6 to Es5
Convert below function
element1.addEventListener("mouseover", (e) => {
tooltipSpan1.style.display = "inline";
tooltipSpan1.style.top = (e.clientX + 20) + 'px';
tooltipSpan1.style.left = (e.clientY + 20) + 'px';
});
to something like below
element1.addEventListener("mouseover", function(e) {
tooltipSpan1.style.display = "inline";
tooltipSpan1.style.top = (e.clientX + 20) + 'px';
tooltipSpan1.style.left = (e.clientY + 20) + 'px';
});

Creating a message that pops up at the end of a quiz depending on score

I hope someone can help me but I have just started learning javascript and I have been working on a quiz for a page of a learning website that I am helping to create. I have been asked to add a message that pops up at the end of the quiz but I can't seem to get it to work. Please excuse any terrible obvious mistakes as like I said I have only been looking into it for a couple of days.
I have a div in the html called message that I wanted to the message to appear.
This is the js I have so far. Any tips would be massively appreciated.
(function($) {
$.fn.emc = function(options) {
var defaults = {
key: [],
scoring: "normal",
progress: true
},
settings = $.extend(defaults,options),
$quizItems = $('[data-quiz-item]'),
$choices = $('[data-choices]'),
itemCount = $quizItems.length,
chosen = [],
$option = null,
$label = null;
emcInit();
if (settings.progress) {
var $bar = $('#emc-progress'),
$inner = $('<div id="emc-progress_inner"></div>'),
$perc = $('<span id="emc-progress_ind">0/'+itemCount+'</span>');
$bar.append($inner).prepend($perc);
}
function emcInit() {
$quizItems.each( function(index,value) {
var $this = $(this),
$choiceEl = $this.find('.choices'),
choices = $choiceEl.data('choices');
for (var i = 0; i < choices.length; i++) {
$option = $('<input name="'+index+'" id="'+index+'_'+i+'" type="radio">');
$label = $('<label for="'+index+'_'+i+'">'+choices[i]+'</label>');
$choiceEl.append($option).append($label);
$option.on( 'change', function() {
return getChosen();
});
}
});
}
function getChosen() {
chosen = [];
$choices.each( function() {
var $inputs = $(this).find('input[type="radio"]');
$inputs.each( function(index,value) {
if($(this).is(':checked')) {
chosen.push(index + 1);
}
});
});
getProgress();
}
function getProgress() {
var prog = (chosen.length / itemCount) * 100 + "%",
$submit = $('#emc-submit');
if (settings.progress) {
$perc.text(chosen.length+'/'+itemCount);
$inner.css({height: prog});
}
if (chosen.length === itemCount) {
$submit.addClass('ready-show');
$submit.click( function(){
return scoreNormal();
});
}
}
function scoreNormal() {
var wrong = [],
score = null,
$scoreEl = $('#emc-score');
for (var i = 0; i < itemCount; i++) {
if (chosen[i] != settings.key[i]) {
wrong.push(i);
}
}
$quizItems.each( function(index) {
var $this = $(this);
if ($.inArray(index, wrong) !== -1 ) {
$this.removeClass('item-correct').addClass('item-incorrect');
} else {
$this.removeClass('item-incorrect').addClass('item-correct');
}
});
score = ((itemCount - wrong.length) / itemCount).toFixed(2) * 100 + "%";
$scoreEl.text("You scored a "+score).addClass('new-score');
}
function print(message) {
document.write(message);
}
if (score===100){
print('congratulations');
}else if(score<=99){
print('Try Again');
}
}
}(jQuery));
$(document).emc({
key: ["1","2","1","1","1","1"]
});
Popup Message
form controls tags
template literal interpolation
nested ternaries
Event Delegation
CSS transform and transition driven by .class
Demo
Enter a number in the <input>. To close the popup message, click the X in the upper righthand corner.
$('#quiz').on('change', function(e) {
var score = parseInt($('#score').val(), 10);
var msg = `Your score is ${score}<sup>×</sup><br>`;
var remark = (score === 100) ? `Perfect, great job!`: (score < 100 && score >= 90) ? `Well done`: (score < 90 && score >= 80) ? `Not bad`: (score < 80 && score >= 70) ? `You can do better`:(score < 70 && score >= 60) ? `That's bad`: `Did you even try?`;
$('#msg legend').html(`${msg}${remark}`).addClass('newScore');
$('#msg legend').on('click', 'sup', function(e) {
$(this).parent().removeClass('newScore');
});
});
#msg legend {
position: absolute;
z-index: 1;
transform: scale(0);
transition: 0.6s;
}
#msg legend.newScore {
font-size:5vw;
text-align:center;
transform-origin: left bottom;
transform: scale(2) translate(0,70%);
transition: 0.8s;
}
#msg legend.newScore sup {
cursor:pointer
}
<form id='quiz'>
<fieldset id='msg'>
<legend></legend>
<input id='score' type='number' min='0' max='100'> Enter your test score in the range of 0 to 100
</fieldset>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Why isn't it possible to change max-height with % in javascript?

I'm trying to build a responsive menu, with a hamburger icon. I want the menu list to slide in and out, no jquery - pure javascript only.
HTML :
<div id="animation">
</div>
<button id="toggle">Toggle</button>
CSS :
div {
width: 300px;
height: 300px;
background-color: blue;
}
Javascript :
var but = document.getElementById('toggle');
var div = document.getElementById('animation');
var animate = function(type, callback){
var inter = -1, start = 100, end = 0;
if(type==true){
inter = 1;
start = 0;
end = 100;
}
var si = setInterval(function(){
console.log('maxheight');
div.style.maxHeight = (start + inter) + '%';
if(start == end){
clearInterval(si);
}
}, 10);
}
var hidden = false;
but.onclick = function(){
animate(hidden, function(){
hidden = (hidden == false) ? true : false;
});
}
div.style.maxHeight = "50%";
The problem is that proportional height in an element needs a fixed height on the parent, and you didn't provided any parent with a fixed height because for the maxHeight property too the % Defines the maximum height in % of the parent element.
You have to put your div in a parent container with a fixed height, this is your working code:
var but = document.getElementById('toggle');
var div = document.getElementById('animation');
var animate = function(type, callback) {
var inter = -1,
start = 100,
end = 0;
if (type) {
inter = 1;
start = 0;
end = 100;
}
var si = setInterval(function() {
console.log('maxheight');
div.style.maxHeight = (start + inter) + '%';
if (start == end) {
clearInterval(si);
}
}, 10);
}
var hidden = false;
but.onclick = function() {
animate(hidden, function() {
hidden = !hidden ;
});
}
div.style.maxHeight = "50%";
#animation {
width: 300px;
height: 300px;
background-color: blue;
}
#parent {
width: 500px;
height: 500px;
}
<div id="parent">
<div id="animation">
</div>
<button id="toggle">Toggle</button>
</div>
Note:
As stated in comments there are some statements in your JavaScript code that need to be adjusted:
if(type==true) can be written as if(type).
hidden = (hidden == false) ? true : false; can be shortened to hidden = !hidden
There seems to be a few errors with your code. I have fixed the js and added comments to what I have changed
var but = document.getElementById('toggle');
var div = document.getElementById('animation');
var animate = function (type, callback) {
var start = 100,
end = 0;
if (type) {
start = 0;
end = 100;
}
var si = setInterval(function () {
if (type) { // check whether to open or close animation
start++;
} else {
start--
}
div.style.maxHeight = start + '%';
if (start == end) {
clearInterval(si);
}
}, 10);
callback.call(this); // do the callback function
}
var hidden = false;
but.onclick = function () {
animate(hidden, function () {
hidden = !hidden; // set hidden to opposite
});
}
/*make sure parent container has a height set or max height won't work*/
html, body {
height:100%;
margin:0;
padding:0;
}
div {
width: 300px;
height: 300px;
background-color: blue;
}
<div id="animation"></div>
<button id="toggle">Toggle</button>
Example Fiddle

Changing single digit number to double digit in javascript

How can I add a zero to a to the output for a percentage?
Here is the code:
var margin = 0;
if(total_quantity>1000){margin = .32;}
else if(total_quantity>575){margin = .35;}
else if(total_quantity>143){margin = .36;}
else if(total_quantity>71){margin = .38;}
else if(total_quantity>36){margin = .40;}
else{margin = .55;}
document.getElementById('margin').value=margin;
The output of the .40 margin is always 4%. I need it to be 40%
var margin = 0;
if (total_quantity > 1000) {
margin = .32;
} else if (total_quantity > 575) {
margin = .35;
} else if (total_quantity > 143) {
margin = .36;
} else if (total_quantity > 71) {
margin = .38;
} else if (total_quantity > 36) {
margin = .40;
} else {
margin = .55;
}
function formatPercentage (decimalNumber) {
return parseInt(decimalNumber * 100, 10); + "%";
}
document.getElementById('margin').value = formatPercentage(margin);
EDIT
You said "but I'm getting two percent signs"... then this should be your formatPercentage function:
function formatPercentage (decimalNumber) {
return parseInt(decimalNumber * 100, 10);
}
In your post you probably wanted to say "The output of the .40 margin is always .4%. I need it to be 40%", right?
Multiply your margin by 100 and you will get 40% instead of .4%

Categories