I've created the following fiddle https://jsfiddle.net/jnoweb/v421zzbe/2/
At the moment it has one variable which makes all three IDs count up to 20:
var game = {score:0},
scoreDisplay = [
document.getElementById("score1"),
document.getElementById("score2"),
document.getElementById("score3")];
function add20() {
TweenLite.to(game, 1, {score:"+=20", roundProps:"score", onUpdate:updateHandler, ease:Linear.easeNone});
}
function updateHandler() {
scoreDisplay.forEach(function(display) {
display.innerHTML = game.score;
});
}
add20();
I want to change this so that each ID counts to a different value, for example 16, 18 and 20!
Does anyone know how to achieve this?
Here is the more elegant, generic, configurable solution.
function ScoreDisplay(id, increment) {
this.elm = document.getElementById(id);
this.inc = increment;
this.game = {score: 0};
}
ScoreDisplay.prototype = {
update: function(){
this.elm.innerHTML = this.game.score;
}
};
var scoreDisplay = [];
scoreDisplay.push(new ScoreDisplay('score1', 16));
scoreDisplay.push(new ScoreDisplay('score2', 18));
scoreDisplay.push(new ScoreDisplay('score3', 20));
function addScore() {
scoreDisplay.forEach(function(sd) {
TweenLite.to(sd.game, 1, {score: "+=" + sd.inc, roundProps:"score", onUpdate:sd.update.bind(sd), ease:Linear.easeNone});
});
}
addScore();
#score1 {
position: relative;
font-size: 30px;
font-weight: bold;
padding: 20px;
text-align: center;
background-color: transparent;
color: $white;
border-radius: 20px 20px;
top: -11px;
left: -42px;
}
#score2 {
position: relative;
font-size: 30px;
font-weight: bold;
padding: 20px;
text-align: center;
background-color: transparent;
color: $white;
border-radius: 20px 20px;
top: -11px;
left: -42px;
}
#score3 {
position: relative;
font-size: 30px;
font-weight: bold;
padding: 20px;
text-align: center;
background-color: transparent;
color: $white;
border-radius: 20px 20px;
top: -11px;
left: -42px;
}
<!--TweenLite/TweenMax GSAP-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/latest/plugins/CSSPlugin.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/latest/easing/EasePack.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TweenLite.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TimelineLite.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/latest/plugins/RoundPropsPlugin.min.js"></script>
<div id="prodArrow"></div>
<div id="prodCount">
<div id="score1"></div>
</div>
<div id="testArrow"></div>
<div id="testCount">
<div id="score2"></div>
</div>
<div id="devArrow"></div>
<div id="devCount">
<div id="score3"></div>
</div>
var game = {
score1: 0,
score2: 0,
score3: 0
},
scoreDisplay = [
document.getElementById("score1"),
document.getElementById("score2"),
document.getElementById("score3")
];
function add(scoreIndex, numToAdd) {
TweenLite.to(game, 1, {score:("+="+numToAdd), roundProps: ("score" + scoreIndex), onUpdate:updateHandler, ease:Linear.easeNone});
}
function updateHandler() {
scoreDisplay.forEach(function(display, i) {
var key = ("score" + (i+1))
display.innerHTML = game[key];
});
}
add(1 , 16);
add(2 , 18);
add(3 , 20);
What about this ?
var game = {
score1:0,
score2:0,
score3:0
},
scoreDisplay = [
document.getElementById("score1"),
document.getElementById("score2"),
document.getElementById("score3")];
function add20() {
TweenLite.to(game, 1, {score1:"+=16", score2:"+=18", score3:"+=20", roundProps:"score", onUpdate:updateHandler, ease:Linear.easeNone});
}
function updateHandler() {
scoreDisplay.forEach(function(display, key) {
var score = scoreDisplay[key].id;
display.innerHTML = game[score];
});
}
add20();
https://jsfiddle.net/hundma4g/
Related
I am trying to deploy my first javascript application, which is a Chrome extension.
This simply generates random passwords and stores it with the url of current active tab.
App runs fine on local but after deploying it to Chrome, I got this error:
Uncaught TypeError: Cannot read properties of null (reading 'length')
index.js:65 (anonymous function)
I am a beginner, so any kind of criticism about my code is highly appreciated.
Thank you so much.
function render() {
*line65* **if(passwords.length === 0)** {
document.getElementById("saved-passwords-container").style.display= "none";
} else {
document.getElementById("saved-passwords-container").style.display= "unset";
}
let list = ""
**for (let i = 0; i < passwords.length; i++)** {
list += `<div class="saved-password-line"><span>${passwords[i]}</span></br></br><span class="link"><a target='_blank'href='${links[i]}'>${links[i]}</a></span></div>`
}
document.getElementById("passwords-el").innerHTML = list
}
Here is the full index.js file:
var characters = [];
for (var i=32; i<127; i++)
characters.push(String.fromCharCode(i));
for( var i = 0; i < characters.length; i++){
if ( characters[i] === '<') {
characters.splice(i, 1);
i--;
}
}
for( var i = 0; i < characters.length; i++){
if ( characters[i] === '>') {
characters.splice(i, 1);
i--;
}
}
let pw1El = document.getElementById("pw1-el")
let pw1 = ""
let passwords = []
passwords = JSON.parse(localStorage.getItem("savedPasswords"))
let links = []
links = JSON.parse(localStorage.getItem("savedLinks"))
render()
document.getElementById("char-count-el").value = 20
document.getElementById("gen-btn").addEventListener("click", function() {
var charCount = document.getElementById("char-count-el").value
pw1 = ""
for(let i = 0; i < charCount; i++) {
let randomIndex = Math.floor(Math.random() * characters.length)
pw1 += (characters[randomIndex])
}
pw1El.textContent = pw1
})
document.getElementById("save-btn").addEventListener("click", function() {
passwords.push(pw1El.innerText)
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
links.push(tabs[0].url)
})
localStorage.setItem("savedPasswords", JSON.stringify(passwords))
localStorage.setItem("savedLinks", JSON.stringify(links))
render()
})
function render() {
**if(passwords.length === 0)** {
document.getElementById("saved-passwords-container").style.display= "none";
} else {
document.getElementById("saved-passwords-container").style.display= "unset";
}
let list = ""
**for (let i = 0; i < passwords.length; i++)** {
list += `<div class="saved-password-line"><span>${passwords[i]}</span></br></br><span class="link"><a target='_blank'href='${links[i]}'>${links[i]}</a></span></div>`
}
document.getElementById("passwords-el").innerHTML = list
}
document.getElementById("clear-btn").addEventListener("click", function() {
passwords = []
links = []
localStorage.setItem("savedPasswords", JSON.stringify(passwords))
localStorage.setItem("savedLinks", JSON.stringify(links))
render()
})
document.getElementById("copy-btn").addEventListener("click", function() {
var input = document.getElementById("pw1-el").textContent;
navigator.clipboard.writeText(input);
alert("Copied Text: " + input);
})
index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="index.css">
</head>
<body>
<div class="container">
<h1>Generate a</br>random password</h1>
<p>Never use an unsecure password again.</p>
<hr>
<div>
<label for="char-count-el">Character Count:</label>
<input type="number" id="char-count-el">
<button id="gen-btn"><span>Generate password</span></button>
</div>
<div>
<label>Your Password:</label>
<div class="pw-container">
<span class="password-line" id="pw1-el">...</span>
<button class="side-btn" id="save-btn">SAVE</button>
<button class="side-btn" id="copy-btn">COPY</button>
</div>
</div>
<div id="saved-passwords-container">
<hr>
<label>Saved Passwords:</label>
<div class="pw-container">
<div id="passwords-el">...</div>
<button class="side-btn" id="clear-btn">CLEAR</button>
</div>
</div>
</div>
<script src="index.js"></script>
</body>
</html>
index.css
body {
padding: 0;
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
background-color: #ffffff;
color: white;
display: flex;
justify-content: center;
align-items: center;
}
h1::first-line {
color: white;
}
h1 {
color: #00ffaa;
margin-bottom: 5px;
line-height: 1;
}
label {
font-size: 11px;
display: block;
color: #D5D4D8;
margin-top: 10px;
}
input {
height: 38px;
border-radius: 5px;
border: none;
width: 70px;
padding: 0px 10px;
text-align: center;
background-color: #D5D4D8;
margin-right: 20px;
font-size: 14px;
}
.container {
background: #1F2937;
margin: 0;
padding: 10px 30px 40px;
width: 100%;
min-width: 500px;
box-shadow: 0px 10px 30px 10px #2640644b;
display: flex;
flex-direction: column;
}
.pw-container {
display: flex;
border-radius: 5px;
background-color: #3e4f66;
padding: 10px;
margin-top: 10px;
}
.password-line {
color: #00ffaa;
font-size: 16px;
padding: 5px 10px;
margin-top: 0px;
flex-grow: 1;
flex: 1 1 1;
min-width: 0;
word-wrap: break-word;
white-space: pre-wrap;
word-break: break-word;
}
#passwords-el {
padding-right: 30px;
flex-grow: 1;
flex: 1 1 0;
min-width: 0;
word-wrap: break-word;
white-space: pre-wrap;
word-break: break-word;
}
.saved-password-line {
color: #D5D4D8;
font-size: 14px;
padding: 10px 15px;
border-bottom: solid 1px #d5d4d814;
border-radius: 5px;
margin-bottom: 10px;
line-height: 0.9;
}
a {
color: #d5d4d872;
text-decoration: underline;
}
.side-btn {
font-size: 12px;
width: 60px;
border: none;
background: none;
color: #D5D4D8;
padding: 5px 10px;
border-radius: 5px;
justify-self: flex-end;
}
.side-btn:hover {
background-color: #ffffff28 ;
}
#gen-btn {
color: #ffffff;
background: #0EBA80;
text-transform: capitalize;
text-align: center;
width: 200px;
height: 40px;
padding: 10px 10px;
border: none;
border-radius: 5px;
margin-bottom: 10px;
margin-top: 10px;
transition: all 0.5s;
box-shadow: 0px 0px 30px 5px #0eba8135
}
#gen-btn:hover {
box-shadow: 0px 0px 30px 10px #0eba8157
}
#gen-btn span {
cursor: pointer;
display: inline-block;
position: relative;
transition: 0.5s;
}
#gen-btn span:after {
content: '\279c';
position: absolute;
opacity: 0;
top: 0;
right: -20px;
transition: 0.5s;
}
#gen-btn:hover span {
padding-right: 25px;
}
#gen-btn:hover span:after {
opacity: 1;
right: 0;
}
p {
color: #D5D4D8;
margin-top: 0px;
}
hr {
border-width: 1px 0px 0px 0px;
border-color: #95959576;
margin: 15px 0;
}
manifest.json
{
"manifest_version": 3,
"version": "1.0",
"name": "Password Generator",
"action": {
"default_popup": "index.html",
"default_icon": "icon.png"
},
"permissions": [
"tabs"
]
}
I solved it.
I understand that (please correct me if I'm wrong)
if the local storage is empty, it does not return an empty array when parsed.
Apparently, when I do:
passwords = JSON.parse(localStorage.getItem("savedPasswords"))
passwords is no longer an array.
I instead use:
passwords.push(JSON.parse(localStorage.getItem("savedPasswords")))
But that just pushes a nested array inside passwords.
So I added a for loop, and used an if statement to address the initial error:
let locSavedPasswords = localStorage.getItem("savedPasswords")
if(locSavedPasswords !== null) {
for( var i = 0; i < (JSON.parse(locSavedPasswords)).length; i++){
passwords.push(JSON.parse(locSavedPasswords)[i])
}}
Initially, savedPasswords won't exist in localStorage, so localStorage.getItem('savedPasswords') will return null.
You then do JSON.parse(null), which doesn't immediately crash because null is first coerced to a string and becomes 'null' which is then JSON-parsed and turns back to null since the string with contents null is valid JSON.
But you then do .length on it and crash.
The solution is to handle the case where the item is not yet set and handle it like it was a JSON-stringified empty array. You can do so for example using the nullish coalescing operator ??:
let passwords = JSON.parse(localStorage.getItem("savedPasswords") ?? '[]')
Or, you can keep initializing it with [] as you did before but wrap the assignment with the actual value in a condition:
let passwords = []
const json = localStorage.getItem('savedPasswords')
if (json !== null) {
passwords = JSON.parse(json)
}
Personally, what I like to do for structured data in localStorage is something like this, which also handles the case that other things like invalid JSON somehow got stored there (without bricking the application):
let passwords = []
try {
const data = JSON.parse(localStorage.getItem('savedPasswords'))
if (Array.isArray(data)) passwords = data
} catch {}
"230:45 Uncaught TypeError: Cannot read properties of undefined (reading 'shouldStopExecution')"
I got the following error can you fix it. I am trying to add HTML, CSS, and javascript on the same page.
I found this code in codepen i am trying to solve the issue but it's not working anymore...
But javascript not working here...
<div class="wrapper">
<div class="poll-box">
<div class="poll-container">
<div class="poll-question">Do You Love to Play FreeFire?</div>
<div class="poll-panel row mt-30">
<div class="btn poll-panel-btn" aria-role="button" data-result="0" data-vote="0"> <span>Yes</span></div>
<div class="btn poll-panel-btn" aria-role="button" data-result="0" data-vote="1"> <span>No</span></div>
</div>
</div>
</div>
</div>
<style>* {
box-sizing: border-box;
}
body {
background: #1b1b1b;
margin: 0;
}
.wrapper {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.mt-30 {
margin: 30px 0 0 0;
}
.row, .column {
display: flex;
}
.row {
flex-direction: row;
}
.column {
flex-direction: column;
}
.btn:not([disabled]) {
cursor: pointer;
}
.poll-box {
background: linear-gradient(#803af7, #500cc4);
border-radius: 3px;
box-shadow: 0px 5px 11px -7px #000;
text-align: center;
}
.poll-container {
padding: 25px 30px;
position: relative;
}
.poll-question {
width: max-content;
max-width: 700px;
color: #FFF;
font-family: "Poppins", sans-serif;
}
.poll-panel.poll-voted {
overflow: hidden;
border-radius: 50px;
}
.poll-panel.poll-voted .poll-panel-btn.--user-choice {
background: #FFF;
color: #000;
}
.poll-panel.poll-voted .poll-panel-btn.--user-choice:hover {
color: #000;
background: #FFF;
}
.poll-panel.poll-voted .poll-panel-btn {
background: #676464;
color: #FFF;
border-radius: 0;
margin: 0;
border: 0;
position: relative;
}
.poll-panel.poll-voted .poll-panel-btn:hover {
color: #FFF;
background: #676464;
}
.poll-panel.poll-voted .poll-panel-btn:after {
content: attr(data-result);
font-size: 9px;
display: block;
opacity: 0.5;
animation: slideWithFade 0.2s ease;
}
.poll-panel.poll-voted .poll-panel-btn:active {
transform: inherit;
}
.poll-panel.poll-voted .poll-panel-btn span {
display: block;
}
.poll-panel {
width: 100%;
}
.poll-panel-btn {
padding: 7px 10px;
font-family: "Roboto", sans-serif;
font-size: 0.7rem;
width: 100%;
border-radius: 50px;
border: 1px solid #FFF;
margin: 0 20px;
color: #FFF;
transition: 0.15s cubic-bezier(0.17, 0.67, 0.79, 1.24);
}
.poll-panel-btn:hover {
background: #FFF;
color: #000;
}
.poll-panel-btn:active {
transform: scale(0.95);
}
#keyframes slideWithFade {
0% {
opacity: 0;
transform: translateY(10px);
}
100% {
opacity: 1;
}
}</style>
<script>// POLL PLUGIN
class poll {
constructor(question, answers, options) {
const defaultOptions = {};
this.options = Object.assign({}, defaultOptions, options);
this.history = [];
this.possibleAnswers = answers;
}
clear() {
this.history = [];
}
get results() {
let numberOfVotes = this.history.length,
votesResults = [];
Object.keys(this.possibleAnswers).forEach(answerId => {
let answerIdCounter = 0;
let voters = [];
this.history.forEach(vote => {
if (answerId == vote.id) {
answerIdCounter++;
voters.push(vote.name);
}
});
let percentOfAllVotes = answerIdCounter / numberOfVotes * 100;
let formatedPercent = isNaN(percentOfAllVotes) ?
0 :
parseFloat(percentOfAllVotes).
toFixed(3).
slice(0, -1);
votesResults.push({
votes: answerIdCounter,
voters: voters,
percent: formatedPercent });
});
return votesResults;
}
vote(answerId, name = "Anonymouse") {
if (this.possibleAnswers[answerId]) {
let getCurrentDate = new Date().toLocaleString();
this.history.push({ id: answerId, name: name, date: getCurrentDate });
return true;
} else throw new Error("Incorrect answer's id");
}}
// Plugin: https://codepen.io/badurski/pen/RJvJQZ
const q1 = new poll("Will Poland win the footboal match?", {
0: { title: "Yes" },
1: { title: "No" } });
// Add some randome votes
for (let i = 0; i < 20; i++) {if (window.CP.shouldStopExecution(0)) break;
q1.vote(Math.floor(Math.random() * (1 - 0 + 1)) + 0);
}
// Poll interface script
window.CP.exitedLoop(0);let pollButtons = document.querySelectorAll('.poll-panel-btn'),
pollPanel = document.querySelector('.poll-panel');
pollButtons.forEach(button => {
button.onclick = () => {
if (button.getAttribute('disabled') != 'disabled') {
q1.vote(button.dataset.vote);
pollPanel.classList.add('poll-voted');
button.classList.add('--user-choice');
pollButtons.forEach(b => {
b.setAttribute('disabled', 'disabled');
let percent = q1.results[b.dataset.vote].percent + '%';
b.style.width = percent;
b.dataset.result = percent;
});
}
};
});</script>
In codepen everything is separated but in your HTML you should put the scripts before the divs.
Something like:
<script>
//blabla.yourscripts - you got it
</script>
<div class="wrapper">
<div class="poll-box">
<div class="poll-container">
<div class="poll-question">Do You Love to Play FreeFire?</div>
<div class="poll-panel row mt-30">
<div class="btn poll-panel-btn" aria-role="button" data-result="0" data-vote="0"> <span>Yes</span></div>
<div class="btn poll-panel-btn" aria-role="button" data-result="0" data-vote="1"> <span>No</span></div>
</div>
</div>
</div>
</div>
So just put the scripts before the stuff reading them.
You have included CP which is the CodePan component.
Please remove window.CP lines, then it will work:
window.CP.exitedLoop(0);
if (window.CP.shouldStopExecution(0)) break;
<script>
// POLL PLUGIN
class poll {
constructor(question, answers, options) {
const defaultOptions = {};
this.options = Object.assign({}, defaultOptions, options);
this.history = [];
this.possibleAnswers = answers;
}
clear() {
this.history = [];
}
get results() {
let numberOfVotes = this.history.length,
votesResults = [];
Object.keys(this.possibleAnswers).forEach(answerId => {
let answerIdCounter = 0;
let voters = [];
this.history.forEach(vote => {
if (answerId == vote.id) {
answerIdCounter++;
voters.push(vote.name);
}
});
let percentOfAllVotes = answerIdCounter / numberOfVotes * 100;
let formatedPercent = isNaN(percentOfAllVotes) ?
0 :
parseFloat(percentOfAllVotes).
toFixed(3).
slice(0, -1);
votesResults.push({
votes: answerIdCounter,
voters: voters,
percent: formatedPercent });
});
return votesResults;
}
vote(answerId, name = "Anonymouse") {
if (this.possibleAnswers[answerId]) {
let getCurrentDate = new Date().toLocaleString();
this.history.push({ id: answerId, name: name, date: getCurrentDate });
return true;
} else throw new Error("Incorrect answer's id");
}}
// Plugin: https://codepen.io/badurski/pen/RJvJQZ
const q1 = new poll("Will Poland win the footboal match?", {
0: { title: "Yes" },
1: { title: "No" } });
// Add some randome votes
for (let i = 0; i < 20; i++) {
q1.vote(Math.floor(Math.random() * (1 - 0 + 1)) + 0);
}
// Poll interface script
let pollButtons = document.querySelectorAll('.poll-panel-btn'),
pollPanel = document.querySelector('.poll-panel');
pollButtons.forEach(button => {
button.onclick = () => {
if (button.getAttribute('disabled') != 'disabled') {
q1.vote(button.dataset.vote);
pollPanel.classList.add('poll-voted');
button.classList.add('--user-choice');
pollButtons.forEach(b => {
b.setAttribute('disabled', 'disabled');
let percent = q1.results[b.dataset.vote].percent + '%';
b.style.width = percent;
b.dataset.result = percent;
});
}
};
});
</script>
I have got a problem at the coding project I am doing, as I formatted the numbers to be shown nicer, I ran into a problem. The webpage when it loads shows NaN. undefined in the total income/expenses at the top. I can't figure out what is the problem.
//Budget controller
var budgetController = (function() {
var Expense = function(id, description, value) {
this.id = id;
this.description = description;
this.value = value;
this.percentage = -1;
};
Expense.prototype.calcPercentage = function(totalIncome) {
if (totalIncome > 0) {
this.percentage = Math.round((this.value / totalIncome) * 100);
} else {
this.percentage = -1;
}
};
Expense.prototype.getPercentage = function() {
return this.percentage;
};
var Income = function(id, description, value) {
this.id = id;
this.description = description;
this.value = value;
};
var calculateTotal = function(type) {
var sum = 0;
data.allItems[type].forEach(function(cur) {
sum = sum + cur.value;
});
data.totals[type] = sum;
};
var data = {
allItems: {
exp: [],
inc: []
},
totals: {
exp: 0,
inc: 0
},
budget: 0,
percentage: -1
};
return {
addItem: function(type, des, val) {
var newItem, ID;
//create new iD
if (data.allItems[type].length > 0) {
ID = data.allItems[type][data.allItems[type].length - 1].id + 1;
} else {
ID = 0;
}
//CREATe new item, if it is inc or exp
if (type === 'exp') {
newItem = new Expense(ID, des, val);
} else if (type === 'inc') {
newItem = new Income(ID, des, val);
}
// Push all items into data structure and return the new element
data.allItems[type].push(newItem);
return newItem;
},
deleteItem: function(type, id) {
var ids, index;
ids = data.allItems[type].map(function(current) {
return current.id;
});
index = ids.indexOf(id);
if (index !== -1) {
data.allItems[type].splice(index, 1);
}
},
calculateBudget: function() {
// calculate the total income and expenses
calculateTotal('exp');
calculateTotal('inc');
// calculate the budget: income - expenses
data.budget = data.totals.inc - data.totals.exp;
if (data.totals.inc > 0) {
data.percentage = Math.round((data.totals.exp / data.totals.inc) * 100);
} else {
data.percentage = -1;
}
},
calculatePercentages: function() {
data.allItems.exp.forEach(function(cur) {
cur.calcPercentage(data.totals.inc);
});
},
getPercentages: function() {
var allPerc = data.allItems.exp.map(function(cur) {
return cur.getPercentage();
});
return allPerc;
},
getBudget: function() {
return {
budget: data.budget,
totalInc: data.totals.inc,
totalExp: data.totals.exp,
percentage: data.percentage
};
}
};
})();
// UI Controller
var UIController = (function() {
var DOMstrings = {
inputType: '.add__type',
inputDescription: '.add__description',
inputValue: '.add__value',
inputBtn: '.add__btn',
incomeContainer: '.income__list',
expensesContainer: '.expenses__list',
budgetLabel: '.budget__value',
incomeLabel: '.budget__income--value',
expensesLabel: '.budget__expenses--value',
percentageLabel: '.budget__expenses--percentage',
container: '.container',
expensesPercLabel: '.item__percentage',
dateLabel: '.budget__title--month'
};
var formatNumber = function(num, type) {
var numSplit, int, dec, type;
/* + or - befofe a number
on 2 decimals
comma seperating thousands
*/
num = Math.abs(num);
num = num.toFixed(2);
numSplit = num.split('.');
int = numSplit[0];
if (int.length > 3) {
int = int.substr(0, int.length - 3) + ',' + int.substr(int.length - 3, 3); //input 23510, output 23,510
}
dec = numSplit[1];
return (type === 'exp' ? '-' : '+') + ' ' + int + '.' + dec;
};
var nodeListForEach = function(list, callback) {
for (var i = 0; i < list.length; i++) {
callback(list[i], i);
}
};
return {
getInput: function() {
return {
type: document.querySelector(DOMstrings.inputType).value, //will be either inc or exp
description: document.querySelector(DOMstrings.inputDescription).value,
value: parseFloat(document.querySelector(DOMstrings.inputValue).value)
};
},
addListItem: function(obj, type) {
var html, newHtml, element;
// Create HTML string with placeholder text
if (type === 'inc') {
element = DOMstrings.incomeContainer;
html = '<div class="item clearfix" id="inc-%id%"> <div class="item__description">%description%</div><div class="right clearfix"><div class="item__value">%value%</div><div class="item__delete"><button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button></div></div></div>';
} else if (type === 'exp') {
element = DOMstrings.expensesContainer;
html = '<div class="item clearfix" id="exp-%id%"><div class="item__description">%description%</div><div class="right clearfix"><div class="item__value">%value%</div><div class="item__percentage">21%</div><div class="item__delete"><button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button></div></div></div>';
}
// Replace the placeholder text with some actual data
newHtml = html.replace('%id%', obj.id);
newHtml = newHtml.replace('%description%', obj.description);
newHtml = newHtml.replace('%value%', formatNumber(obj.value, type));
// Insert the HTML into the DOM
document.querySelector(element).insertAdjacentHTML('beforeend', newHtml);
},
deleteListItem: function(selectorID) {
var el = document.getElementById(selectorID);
el.parentNode.removeChild(el);
},
clearFields: function() {
var fields, fieldsArr;
fields = document.querySelectorAll(
DOMstrings.inputDescription + ',' + DOMstrings.inputValue
);
fieldsArr = Array.prototype.slice.call(fields);
fieldsArr.forEach(function(current, index, array) {
current.value = "";
});
fieldsArr[0].focus();
},
displayBudget: function(obj) {
var type;
obj.budget > 0 ? type = 'inc' : type = 'exp';
document.querySelector(DOMstrings.budgetLabel).textContent = formatNumber(obj.budget, type);
document.querySelector(DOMstrings.incomeLabel).textContent = formatNumber(obj.totalInc, 'inc');
document.querySelector(DOMstrings.expensesLabel).textContent = formatNumber(obj.totalExp, 'exp');
if (obj.percentage > 0) {
document.querySelector(DOMstrings.percentageLabel).textContent = obj.percentage + '%';
} else {
document.querySelector(DOMstrings.percentageLabel).textContent = '---';
}
},
displayPercentages: function(percentages) {
var fields = document.querySelectorAll(DOMstrings.expensesPercLabel);
nodeListForEach(fields, function(current, index) {
if (percentages[index] > 0) {
current.textContent = percentages[index] + '%';
} else {
current.textContent = '---';
}
});
},
getDOMstrings: function() {
return DOMstrings;
}
};
})();
// App Controller - global
var controller = (function(budgetCtrl, UICtrl) {
var setupEventListeners = function() {
var DOM = UICtrl.getDOMstrings();
document.querySelector(DOM.inputBtn).addEventListener('click', ctrlAddItem);
document.addEventListener('keypress', function(event) {
if (event.keyCode === 13 || event.which === 13) {
ctrlAddItem();
}
});
document.querySelector(DOM.container).addEventListener('click', ctrlDeleteItem);
};
var updateBudget = function() {
// 1. Calculate the budget
budgetCtrl.calculateBudget();
// 2. Return the budget
var budget = budgetCtrl.getBudget();
// 3. Display the budget on the UI
UICtrl.displayBudget(budget);
};
var updatePercentages = function() {
// 1. Calculate percentages
budgetCtrl.calculatePercentages();
// 2. Read percentages from the budget controller
var percentages = budgetCtrl.getPercentages();
// 3. Update the UI with the new percentages
UICtrl.displayPercentages(percentages);
};
var ctrlAddItem = function() {
var input, newItem;
// 1. Get the field input data
input = UICtrl.getInput();
if (input.description !== "" && !isNaN(input.value) && input.value > 0) {
// 2. Add the item to the budget controller
newItem = budgetCtrl.addItem(input.type, input.description, input.value);
// 3. Add the item to the UI
UICtrl.addListItem(newItem, input.type);
// 4. Clear the fields
UICtrl.clearFields();
// 5. Calculate and update budget
updateBudget();
// 6. Calculate and update percentages
updatePercentages();
}
};
var ctrlDeleteItem = function(event) {
var itemID, splitID, type, ID;
itemID = event.target.parentNode.parentNode.parentNode.parentNode.id;
if (itemID) {
//inc-1
splitID = itemID.split('-');
type = splitID[0];
ID = parseInt(splitID[1]);
// 1. delete the item from the data structure
budgetCtrl.deleteItem(type, ID);
// 2. Delete the item from the UI
UICtrl.deleteListItem(itemID);
// 3. Update and show the new budget
updateBudget();
// 4. Calculate and update percentages
updatePercentages();
}
};
return {
init: function() {
console.log('App has started');
UICtrl.displayBudget({
budget: 0,
totalIncome: 0,
totalExpenses: 0,
percentage: -1
});
setupEventListeners();
}
};
})(budgetController, UIController);
controller.init();
/**********************************************
*** GENERAL
**********************************************/
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.clearfix::after {
content: "";
display: table;
clear: both;
}
body {
color: #555;
font-family: Open Sans;
font-size: 16px;
position: relative;
height: 100vh;
font-weight: 400;
}
.right {
float: right;
}
.red {
color: #FF5049 !important;
}
.red-focus:focus {
border: 1px solid #FF5049 !important;
}
/**********************************************
*** TOP PART
**********************************************/
.top {
height: 40vh;
background-image: linear-gradient(rgba(0, 0, 0, 0.35), rgba(0, 0, 0, 0.35)), url(back.png);
background-size: cover;
background-position: center;
position: relative;
}
.budget {
position: absolute;
width: 350px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: #fff;
}
.budget__title {
font-size: 18px;
text-align: center;
margin-bottom: 10px;
font-weight: 300;
}
.budget__value {
font-weight: 300;
font-size: 46px;
text-align: center;
margin-bottom: 25px;
letter-spacing: 2px;
}
.budget__income,
.budget__expenses {
padding: 12px;
text-transform: uppercase;
}
.budget__income {
margin-bottom: 10px;
background-color: #28B9B5;
}
.budget__expenses {
background-color: #FF5049;
}
.budget__income--text,
.budget__expenses--text {
float: left;
font-size: 13px;
color: #444;
margin-top: 2px;
}
.budget__income--value,
.budget__expenses--value {
letter-spacing: 1px;
float: left;
}
.budget__income--percentage,
.budget__expenses--percentage {
float: left;
width: 34px;
font-size: 11px;
padding: 3px 0;
margin-left: 10px;
}
.budget__expenses--percentage {
background-color: rgba(255, 255, 255, 0.2);
text-align: center;
border-radius: 3px;
}
/**********************************************
*** BOTTOM PART
**********************************************/
/***** FORM *****/
.add {
padding: 14px;
border-bottom: 1px solid #e7e7e7;
background-color: #f7f7f7;
}
.add__container {
margin: 0 auto;
text-align: center;
}
.add__type {
width: 55px;
border: 1px solid #e7e7e7;
height: 44px;
font-size: 18px;
color: inherit;
background-color: #fff;
margin-right: 10px;
font-weight: 300;
transition: border 0.3s;
}
.add__description,
.add__value {
border: 1px solid #e7e7e7;
background-color: #fff;
color: inherit;
font-family: inherit;
font-size: 14px;
padding: 12px 15px;
margin-right: 10px;
border-radius: 5px;
transition: border 0.3s;
}
.add__description {
width: 400px;
}
.add__value {
width: 100px;
}
.add__btn {
font-size: 35px;
background: none;
border: none;
color: #28B9B5;
cursor: pointer;
display: inline-block;
vertical-align: middle;
line-height: 1.1;
margin-left: 10px;
}
.add__btn:active {
transform: translateY(2px);
}
.add__type:focus,
.add__description:focus,
.add__value:focus {
outline: none;
border: 1px solid #28B9B5;
}
.add__btn:focus {
outline: none;
}
/***** LISTS *****/
.container {
width: 1000px;
margin: 60px auto;
}
.income {
float: left;
width: 475px;
margin-right: 50px;
}
.expenses {
float: left;
width: 475px;
}
h2 {
text-transform: uppercase;
font-size: 18px;
font-weight: 400;
margin-bottom: 15px;
}
.icome__title {
color: #28B9B5;
}
.expenses__title {
color: #FF5049;
}
.item {
padding: 13px;
border-bottom: 1px solid #e7e7e7;
}
.item:first-child {
border-top: 1px solid #e7e7e7;
}
.item:nth-child(even) {
background-color: #f7f7f7;
}
.item__description {
float: left;
}
.item__value {
float: left;
transition: transform 0.3s;
}
.item__percentage {
float: left;
margin-left: 20px;
transition: transform 0.3s;
font-size: 11px;
background-color: #FFDAD9;
padding: 3px;
border-radius: 3px;
width: 32px;
text-align: center;
}
.income .item__value,
.income .item__delete--btn {
color: #28B9B5;
}
.expenses .item__value,
.expenses .item__percentage,
.expenses .item__delete--btn {
color: #FF5049;
}
.item__delete {
float: left;
}
.item__delete--btn {
font-size: 22px;
background: none;
border: none;
cursor: pointer;
display: inline-block;
vertical-align: middle;
line-height: 1;
display: none;
}
.item__delete--btn:focus {
outline: none;
}
.item__delete--btn:active {
transform: translateY(2px);
}
.item:hover .item__delete--btn {
display: block;
}
.item:hover .item__value {
transform: translateX(-20px);
}
.item:hover .item__percentage {
transform: translateX(-20px);
}
.unpaid {
background-color: #FFDAD9 !important;
cursor: pointer;
color: #FF5049;
}
.unpaid .item__percentage {
box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.1);
}
.unpaid:hover .item__description {
font-weight: 900;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:100,300,400,600" rel="stylesheet" type="text/css">
<link href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" type="text/css">
<link type="text/css" rel="stylesheet" href="style.css">
<title>Budgety</title>
</head>
<body>
<div class="top">
<div class="budget">
<div class="budget__title">
Available Budget in <span class="budget__title--month">%Month%</span>:
</div>
<div class="budget__value">+ 2,345.64</div>
<div class="budget__income clearfix">
<div class="budget__income--text">Income</div>
<div class="right">
<div class="budget__income--value">+ 4,300.00</div>
<div class="budget__income--percentage"> </div>
</div>
</div>
<div class="budget__expenses clearfix">
<div class="budget__expenses--text">Expenses</div>
<div class="right clearfix">
<div class="budget__expenses--value">- 1,954.36</div>
<div class="budget__expenses--percentage">45%</div>
</div>
</div>
</div>
</div>
<div class="bottom">
<div class="add">
<div class="add__container">
<select class="add__type">
<option value="inc" selected>+</option>
<option value="exp">-</option>
</select>
<input type="text" class="add__description" placeholder="Add description">
<input type="number" class="add__value" placeholder="Value">
<button class="add__btn"><i class="ion-ios-checkmark-outline"></i></button>
</div>
</div>
<div class="container clearfix">
<div class="income">
<h2 class="icome__title">Income</h2>
<div class="income__list">
<!--
<div class="item clearfix" id="income-0">
<div class="item__description">Salary</div>
<div class="right clearfix">
<div class="item__value">+ 2,100.00</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>
<div class="item clearfix" id="income-1">
<div class="item__description">Sold car</div>
<div class="right clearfix">
<div class="item__value">+ 1,500.00</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>
-->
</div>
</div>
<div class="expenses">
<h2 class="expenses__title">Expenses</h2>
<div class="expenses__list">
<!--
<div class="item clearfix" id="expense-0">
<div class="item__description">Apartment rent</div>
<div class="right clearfix">
<div class="item__value">- 900.00</div>
<div class="item__percentage">21%</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>
<div class="item clearfix" id="expense-1">
<div class="item__description">Grocery shopping</div>
<div class="right clearfix">
<div class="item__value">- 435.28</div>
<div class="item__percentage">10%</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>
-->
</div>
</div>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
The problem is that in the function formatNumber, the value num is not initialized at first time. For solving this, you can put a default value when the value of num is empty, like this:
var formatNumber = function(num = 0, type = '') {
var numSplit, int, dec, type;
/* + or - befofe a number
on 2 decimals
comma seperating thousands
*/
num = Math.abs(num);
num = num.toFixed(2);
numSplit = num.split('.');
int = numSplit[0];
if (int.length > 3) {
int = int.substr(0, int.length - 3) + ',' + int.substr(int.length - 3, 3); //input 23510, output 23,510
}
dec = numSplit[1];
return (type === 'exp' ? '-' : '+') + ' ' + int + '.' + dec;
};
I'm trying to use a Jquery movie seat selection plugin on my jsp website. The plugin works well and i can able to select the seat.
My problem is, since i don't know Jquery i could not able to print the user selected seat on my jsp page.
kindly help me to print the users selected seat on jsp page. So that i can use them to store on my derby database.
HTML
<div class="demo">
<div id="seat-map">
<div class="front">SCREEN</div>
</div>
<div class="booking-details">
<p>Seat: </p>
<ul id="selected-seats"></ul>
<p>Tickets: <span id="counter">0</span></p>
<p>Total: <b>Rs.<span id="total">0</span></b></p>
<input type="button" value="BUY" class="checkout-button"/>
<div id="legend"></div>
</div>
<div style="clear:both"></div>
Jquery :
</style>
<script>
var price = 120; //price
$(document).ready(function() {
var $cart = $('#selected-seats'), //Sitting Area
$counter = $('#counter'), //Votes
$total = $('#total'); //Total money
var sc = $('#seat-map').seatCharts({
map: [ //Seating chart
'aaaaaaaaaa',
'aaaaaaaaaa',
'aaaaaaaaaa',
'aaaaaaaaaa',
'aaaaaaaaaa',
'aaaaaaaaaa',
'aaaaaaaaaa',
'aaaaaaaaaa',
'aaaaaaaaaa',
],
naming : {
top : false,
getLabel : function (character, row, column) {
return column;
}
},
legend : { //Definition legend
node : $('#legend'),
items : [
[ 'a', 'available', 'Avail' ],
[ 'a', 'unavailable', 'Sold']
]
},
click: function () { //Click event
if (this.status() == 'available') { //optional seat
$('<li>R'+(this.settings.row+1)+' S'+this.settings.label+'</li>')
.attr('id', 'cart-item-'+this.settings.id)
.data('seatId', this.settings.id)
.appendTo($cart);
$counter.text(sc.find('selected').length+1);
$total.text(recalculateTotal(sc)+price);
return 'selected';
} else if (this.status() == 'selected') { //Checked
//Update Number
$counter.text(sc.find('selected').length-1);
//update totalnum
$total.text(recalculateTotal(sc)-price);
//Delete reservation
$('#cart-item-'+this.settings.id).remove();
//optional
return 'available';
} else if (this.status() == 'unavailable') { //sold
return 'unavailable';
} else {
return this.style();
}
}
});
//sold seat
sc.get(['1_2', '4_4','4_5','6_6','6_7','8_5','8_6','8_7','8_8', '10_1', '10_2']).status('unavailable');
});
//sum total money
function recalculateTotal(sc) {
var total = 0;
sc.find('selected').each(function () {
total += price;
});
return total;
}
</script>
CSS:
<style>
.front{width: 300px;margin: 5px 32px 45px 32px;background-color: #f0f0f0; color: #666;text-align: center;padding: 3px;border-radius: 5px;}
.booking-details {float: right;position: relative;width:200px;height: 450px; }
.booking-details h3 {margin: 5px 5px 0 0;font-size: 16px;}
.booking-details p{line-height:26px; font-size:16px; color:#999}
.booking-details p span{color:#666}
div.seatCharts-cell {color: #182C4E;height: 25px;width: 25px;line-height: 25px;margin: 3px;float: left;text-align: center;outline: none;font-size: 13px;}
div.seatCharts-seat {color: #fff;cursor: pointer;-webkit-border-radius:5px;- moz-border-radius:5px;border-radius: 5px;}
div.seatCharts-row {height: 35px;}
div.seatCharts-seat.available {background-color: #B9DEA0;}
div.seatCharts-seat.focused {background-color: #76B474;border: none;}
div.seatCharts-seat.selected {background-color: #E6CAC4;}
div.seatCharts-seat.unavailable {background-color: #472B34;cursor: not-allowed;}
div.seatCharts-container {border-right: 1px dotted #adadad;width: 400px;padding: 20px;float: left;}
div.seatCharts-legend {padding-left: 0px;position: absolute;bottom: 16px;}
ul.seatCharts-legendList {padding-left: 0px;}
.seatCharts-legendItem{float:left; width:90px;margin-top: 10px;line-height: 2;}
span.seatCharts-legendDescription {margin-left: 5px;line-height: 30px;}
.checkout-button {display: block;width:80px; height:24px; line- height:20px;margin: 10px auto;border:1px solid #999;font-size: 14px; cursor:pointer}
#selected-seats {max-height: 150px;overflow-y: auto;overflow-x: none;width: 200px;}
#selected-seats li{float:left; width:72px; height:26px; line-height:26px; border:1px solid #d3d3d3; background:#f7f7f7; margin:6px; font-size:14px; font- weight:bold; text-align:center}
</style>
Please Help!
Thanks.
I may suggest you to use the jQuery dialog plugin (dialog), plus jsPDF in order to produce a dialog on a print button containing a pdf version of the html related to your selected seat.
The result is like:
The snippet is:
var price = 120; //price
var sc;
//sum total money
function recalculateTotal(sc) {
var total = 0;
sc.find('selected').each(function () {
total += price;
});
return total;
}
$(function () {
var $cart = $('#selected-seats'), //Sitting Area
$counter = $('#counter'), //Votes
$total = $('#total'); //Total money
sc = $('#seat-map').seatCharts({
map: [ //Seating chart
'aaaaaaaaaa',
'aaaaaaaaaa',
'aaaaaaaaaa',
'aaaaaaaaaa',
'aaaaaaaaaa',
'aaaaaaaaaa',
'aaaaaaaaaa',
'aaaaaaaaaa',
'aaaaaaaaaa',
],
naming: {
top: false,
getLabel: function (character, row, column) {
return column;
}
},
legend: { //Definition legend
node: $('#legend'),
items: [
['a', 'available', 'Avail'],
['a', 'unavailable', 'Sold']
]
},
click: function () { //Click event
if (this.status() == 'available') { //optional seat
$('<li>R' + (this.settings.row + 1) + ' S' + this.settings.label + '</li>')
.attr('id', 'cart-item-' + this.settings.id)
.data('seatId', this.settings.id)
.appendTo($cart);
$counter.text(sc.find('selected').length + 1);
$total.text(recalculateTotal(sc) + price);
return 'selected';
} else if (this.status() == 'selected') { //Checked
//Update Number
$counter.text(sc.find('selected').length - 1);
//update totalnum
$total.text(recalculateTotal(sc) - price);
//Delete reservation
$('#cart-item-' + this.settings.id).remove();
//optional
return 'available';
} else if (this.status() == 'unavailable') { //sold
return 'unavailable';
} else {
return this.style();
}
}
});
//sold seat
sc.get(['1_2', '4_4', '4_5', '6_6', '6_7', '8_5', '8_6', '8_7', '8_8', '10_1', '10_2']).status('unavailable');
$(':button[value="PRINT"]').on('click', function(e) {
e.preventDefault();
if ($('#selected-seats li').length > 0) {
var doc = new jsPDF();
var specialElementHandlers = {
'#selected-seats': function(element, renderer){
return true;
}
};
doc.fromHTML($('#selected-seats').html(), 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
var uriPdf = doc.output('datauristring');
$('<div>').prop('id', '_currentDialog').add('<iframe id="_myPdf" type="application/pdf" src="' + uriPdf + '"></iframe>').dialog({
title: "Selected seat",
width: 600,
height: 800,
close: function (event, ui) {
$('#_currentDialog').remove();
}
});
} else {
alert('No selected seat to print!')
}
});
});
.front {
width: 300px;
margin: 5px 32px 45px 32px;
background-color: #f0f0f0;
color: #666;
text-align: center;
padding: 3px;
border-radius: 5px;
}
.booking-details {
float: right;
position: relative;
width: 200px;
height: 450px;
}
.booking-details h3 {
margin: 5px 5px 0 0;
font-size: 16px;
}
.booking-details p {
line-height: 26px;
font-size: 16px;
color: #999
}
.booking-details p span {
color: #666
}
div.seatCharts-cell {
color: #182C4E;
height: 25px;
width: 25px;
line-height: 25px;
margin: 3px;
float: left;
text-align: center;
outline: none;
font-size: 13px;
}
div.seatCharts-seat {
color: #fff;
cursor: pointer;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
div.seatCharts-row {
height: 35px;
}
div.seatCharts-seat.available {
background-color: #B9DEA0;
}
div.seatCharts-seat.focused {
background-color: #76B474;
border: none;
}
div.seatCharts-seat.selected {
background-color: #E6CAC4;
}
div.seatCharts-seat.unavailable {
background-color: #472B34;
cursor: not-allowed;
}
div.seatCharts-container {
border-right: 1px dotted #adadad;
width: 400px;
padding: 20px;
float: left;
}
div.seatCharts-legend {
padding-left: 0px;
position: absolute;
bottom: 16px;
}
ul.seatCharts-legendList {
padding-left: 0px;
}
.seatCharts-legendItem {
float: left;
width: 90px;
margin-top: 10px;
line-height: 2;
}
span.seatCharts-legendDescription {
margin-left: 5px;
line-height: 30px;
}
.checkout-button {
display: inline;
width: 80px;
height: 24px;
line-height: 20px;
margin: 10px auto;
border: 1px solid #999;
font-size: 14px;
cursor: pointer
}
#selected-seats {
max-height: 150px;
overflow-y: auto;
overflow-x: none;
width: 200px;
}
#selected-seats li {
float: left;
width: 72px;
height: 26px;
line-height: 26px;
border: 1px solid #d3d3d3;
background: #f7f7f7;
margin: 6px;
font-size: 14px;
font- weight: bold;
text-align: center
}
#_myPdf {
width: 100% !important;
}
<link href="js/jquery.seat-chart/jquery.seat-charts.css" rel="stylesheet">
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="js/jquery.seat-chart/jquery.seat-charts.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.min.js"></script>
<div class="demo">
<div id="seat-map">
<div class="front">SCREEN</div>
</div>
<div class="booking-details">
<p>Seat: </p>
<ul id="selected-seats"></ul>
<p>Tickets: <span id="counter">0</span></p>
<p>Total: <b>Rs.<span id="total">0</span></b></p>
<input type="button" value="BUY" class="checkout-button"/>
<input type="button" value="PRINT" class="checkout-button"/>
<div id="legend"></div>
</div>
<div style="clear:both"></div>
</div>
The function to print in the html with jquery is "html()" for example if you want to write in the div with the id legend you can do this:
$("#legend").html("<p>whatever you want to write</p>");
You can find more details on this page
w3schools tutorial
Hope it help
Hello I'm stuck on how to add category for my to do list. When you click on Button of category need change class name. I don't understand how to correctly write if/else statement when button is clicked.
plan how it need to work
Write task name
Choose Category
Add new task
May be somebody can help me out ore give some advice how to solve this problem!
Sorry for my english and if my question is to badly explained!
var toDoList = function() {
var addNewTask = function() {
var input = document.getElementById("taks-input").value,
itemTexts = input,
colA = document.getElementById('task-col-a').children.length,
colB = document.getElementById('task-col-b').children.length,
taskBoks = document.createElement("div"),
work = document.getElementById("work"),
Category = "color-2",
taskCount = 1;
if (work.onclick === true) {
var Category = "color";
}
taskBoks.className = "min-box";
taskBoks.innerHTML = '<div class="col-3 chack" id="task_' + (taskCount++) + '"><i class="fa fa-star"></i></div><div class="col-8 task-text" id="taskContent"><p>' + itemTexts + '</p><span id="time-now"></span></div><div class="col-1 ' + (Category) + '"></div>'
if (colB < colA) {
var todolist = document.getElementById("task-col-b");
} else {
var todolist = document.getElementById("task-col-a");
}
//todolist.appendChild(taskBoks);
todolist.insertBefore(taskBoks, todolist.childNodes[0]);
},
addButton = function() {
var btn2 = document.getElementById("add-task-box");
btn2.onclick = addNewTask;
};
addButton()
}
toDoList();
p {
padding: 20px 20px 20px 45px;
}
.chack {
background-color: #4c4b62;
height: 100%;
width: 40px;
}
.task-text {
background-color: #55566e;
height: 100%;
width: 255px;
}
.color {
width: 5px;
height: 100%;
background-color: #fdcd63;
float: right;
}
.color-2 {
width: 5px;
height: 100%;
background-color: red;
float: right;
}
.color-3 {
width: 5px;
height: 100%;
background-color: purple;
float: right;
}
.task {
height: 100px;
width: 300px;
border: 1px solid #fff;
float: left;
}
.chack,
.task-text {
float: left;
}
.add-new-task {
margin-bottom: 50px;
height: 80px;
width: 588px;
background-color: rgb(85, 86, 110);
padding-top: 30px;
padding-left: 15px;
}
.min-box {
height: 100px;
border-bottom: 1px solid #fff;
}
.center {
padding-top: 20px;
padding-left: 50px;
}
.fa-star {
padding-left: 14px;
padding-top: 100%;
}
#add-task-box {
float: right;
margin-right: 10px;
margin-top: -7px;
border: none;
background-color: rgb(255, 198, 94);
padding: 10px;
}
#taks-input {
height: 30px;
width: 350px;
margin-top: -7px;
}
.category {
margin-top: 10px;
}
<div class="container">
<div class="add-new-task">
<input type="text" id="taks-input">
<button id="add-task-box">Add New Task box</button>
<div class="category">
<button class="catBtn" id="work">Work</button>
<button class="catBtn" id="home">Home</button>
<button class="catBtn" id="other">Other</button>
</div>
</div>
<div class="lg-task" id="bigTask"></div>
<div class="task" id="task-col-a"></div>
<div class="task" id="task-col-b"></div>
</div>
you need to bind click event to your buttons and store that value in Category, so in you js add this
var toDoList = function() {
// set to default
var Category = "color-3";
// attach event to buttons
var catButtons = document.getElementsByClassName("catBtn");
// assign value based on event
var myCatEventFunc = function() {
var attribute = this.getAttribute("id");
if (attribute === 'work') {
Category = 'color';
} else if (attribute === 'home') {
Category = 'color-2';
}
};
for (var i = 0; i < catButtons.length; i++) {
catButtons[i].addEventListener('click', myCatEventFunc, false);
}
Demo: Fiddle
and remove this code from addNewTask function
if (work.onclick === true) {
var Category = "color";
}
It is a bit hard to understand what you are doing, what you are going for (a module of some kind?). You were not that far away from a working state.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Task</title>
<style>
p {
padding: 20px 20px 20px 45px;
}
.chack {
background-color: #4c4b62;
height: 100%;
width: 40px;
}
.task-text {
background-color: #55566e;
height: 100%;
width: 255px;
}
.color {
width: 5px;
height: 100%;
background-color: #fdcd63;
float: right;
}
.color-2 {
width: 5px;
height: 100%;
background-color: red;
float: right;
}
.color-3 {
width: 5px;
height: 100%;
background-color: purple;
float: right;
}
.task {
height: 100px;
width: 300px;
border: 1px solid #fff;
float: left;
}
.chack,
.task-text {
float: left;
}
.add-new-task {
margin-bottom: 50px;
height: 80px;
width: 588px;
background-color: rgb(85, 86, 110);
padding-top: 30px;
padding-left: 15px;
}
.min-box {
height: 100px;
border-bottom: 1px solid #fff;
}
.center {
padding-top: 20px;
padding-left: 50px;
}
.fa-star {
padding-left: 14px;
padding-top: 100%;
}
#add-task-box {
float: right;
margin-right: 10px;
margin-top: -7px;
border: none;
background-color: rgb(255, 198, 94);
padding: 10px;
}
#taks-input {
height: 30px;
width: 350px;
margin-top: -7px;
}
.category {
margin-top: 10px;
}
</style>
<script>
var toDoList = function() {
var addNewTask = function() {
var input = document.getElementById("taks-input").value,
itemTexts = input,
colA = document.getElementById('task-col-a').children.length,
colB = document.getElementById('task-col-b').children.length,
taskBoks = document.createElement("div"),
work = document.getElementById("work"),
Category = "color-2",
taskCount = 1;
if (work.onclick === true) {
Category = "color";
}
taskBoks.className = "min-box";
taskBoks.innerHTML = '<div class="col-3 chack" id="task_'
+ (taskCount++) +
'"><i class="fa fa-star"></i></div><div class="col-8 task-text" id="taskContent"><p>'
+ itemTexts +
'</p><span id="time-now"></span></div><div class="col-1 '
+ (Category) + '"></div>'
if (colB < colA) {
var todolist = document.getElementById("task-col-b");
} else {
var todolist = document.getElementById("task-col-a");
}
//todolist.appendChild(taskBoks);
todolist.insertBefore(taskBoks, todolist.childNodes[0]);
},
// I don't know what to do with that?
addButton = function() {
var btn2 = document.getElementById("add-task-box");
btn2.onclick = addNewTask();
};
// return the stuff you want to have public
return {
addNewTask:addNewTask
};
}
var f;
// wait until all HTML is loaded and put the stuff from above into the variable `f`
// you can call it with f.someFunction() in your case f.addNewTask()
window.onload = function(){
f = toDoList();
}
</script>
</head>
<body>
<div class="container">
<div class="add-new-task">
<input type="text" id="taks-input">
<button id="add-task-box" onclick="f.addNewTask()">Add New Task box</button>
<div class="category">
<button class="catBtn" id="work" >Work</button>
<button class="catBtn" id="home">Home</button>
<button class="catBtn" id="other">Other</button>
</div>
</div>
<div class="lg-task" id="bigTask"></div>
<div class="task" id="task-col-a"></div>
<div class="task" id="task-col-b"></div>
</div>
</body>
</html
I hope you understood what I did?