jQuery animation doesn't work with SAPUI5 - javascript

I'm constructing a tree-view that slides out based on the buttons the user clicks in the preceding column. I get this error when I click on the first column of buttons:
Uncaught TypeError: $(...).effect is not a function
at runEffect1 (test:39)
at HTMLDivElement.<anonymous> (test:66)
at HTMLDivElement.dispatch (jquery-dbg.js:4737)
at HTMLDivElement.c3.handle (jquery-dbg.js:4549)
How do I fix it? These functions worked when I used vanilla JavaScript and without the SAPUI5 imported, but using jQuery now gives problems. I need to use SAPUI5 with jQuery. Also, the snippet doesn't work due to adding SAPUI5.
$(document).ready(function() {
$(function() {
// run the currently selected effect
function runEffect1() {
var selectedEffect = "slide";
var options = {};
/* Hide the columns so that they can slide into display*/
$("#column_2").hide();
$("#column_3").hide();
$("#column_4").hide();
// Run the effect
$("#column_2").effect(selectedEffect, options, 450, function() {
$("#column_3").effect(selectedEffect, options, 450, function() {
$("#column_4").effect(selectedEffect, options, 450, callback);
});
});
};
// Callback function to bring a hidden box back
function callback() {
setTimeout(function() {
$("#effect").removeAttr("style").hide().fadeIn();
}, 100);
};
// Set effect from select menu value
$("#column_1").on("click", function() {
runEffect1();
return false;
});
$("#column_2").on("click", function() {
runEffect2();
return false;
});
});
});
function myFunction2(e) {
test = e;
console.log(e);
jQuery("#column_2").html("");
jQuery("#column_2").html("<span style='color:#FFFFFF'> GL Accounts </span>");
jQuery("#column_3").html("");
jQuery("#column_3").html("<span style='color:#FFFFFF'> GL Name </span>");
jQuery("#column_4").html("");
jQuery("#column_4").html("<span style='color:#FFFFFF'> GL Balance </span>");
jQuery("#column_5").html("");
for (var prop3 in array0) {
jQuery("#column_2").append('<div class="col-md-auto"> <button type="button" id=' + prop3 + ' class="list-group-item" onclick="myFunction4(this.id)">test</button></div>');
jQuery("#column_3").append('<div class="col-md-auto"> <button type="button" id=' + prop3 + ' class="list-group-item" onclick="myFunction4(this.id)">test1</button></div>');
jQuery("#column_4").append('<div class="col-md-auto"> <button type="button" id=' + prop3 + ' class="list-group-item" onclick="myFunction4(this.id)">test2</button></div>');
}
for (var prop2 in array17) {
jQuery("#column_4").append('<div class="col-md-auto"> <button type="button" id=' + prop2 + ' class="list-group-item" onclick="myFunction2(this.id)">test3</button></div>');
}
}
function myFunction4(e) {
test = e;
console.log(e);
jQuery("#column_5").html("");
jQuery("#column_5").html("<span style='color:#FFFFFF'> Breakdown </span>");
for (var prop5 in array11) {
jQuery("#column_5").append('<div class="col-md-auto"> <button type="button" id=' + prop5 + ' class="list-group-item" onclick="myFunction5(this.id)">test4</button></div>');
}
}
function myFunction5(e) {
test = e;
console.log(e);
window.open("", "", "width=500,height=500");
}
sap.ui.getCore().attachInit(function() {
console.log("SAPUI5 modules loaded....")
jQuery("#column_1").html("");
jQuery("#column_1").html("<span style='color:#FFFFFF'> Account Group </span>");
for (var prop in array2) {
jQuery("#column_1").append('<div class="col-md-auto"> <button type="button" id=' + prop + ' class="list-group-item" onclick="myFunction2(this.id)">test0</button></div>');
}
});
#import url(https://fonts.googleapis.com/css?family=Roboto:300);
.login-page {
width: 360px;
padding: 8% 0 0;
margin: auto;
}
.form {
position: relative;
z-index: 1;
background: #FFFFFF;
max-width: 360px;
margin: 0 auto 100px;
padding: 45px;
text-align: center;
box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24);
}
.form input {
font-family: "Roboto", sans-serif;
outline: 0;
background: #f2f2f2;
width: 100%;
border: 0;
margin: 0 0 15px;
padding: 15px;
box-sizing: border-box;
font-size: 14px;
}
.form button {
font-family: "Roboto", sans-serif;
text-transform: uppercase;
outline: 0;
background: #4778b7;
width: 100%;
border: 0;
padding: 15px;
color: #FFFFFF;
font-size: 14px;
-webkit-transition: all 0.3 ease;
transition: all 0.3 ease;
cursor: pointer;
}
.form button:hover,
.form button:active,
.form button:focus {
background: #7ac1db;
}
.form .message {
margin: 15px 0 0;
color: #b3b3b3;
font-size: 12px;
}
.form .message a {
color: #4CAF50;
text-decoration: none;
}
.form .register-form {
display: none;
}
.container {
position: relative;
z-index: 1;
max-width: 300px;
margin: 0 auto;
}
.container:before,
.container:after {
content: "";
display: block;
clear: both;
}
.container .info {
margin: 50px auto;
text-align: center;
}
.container .info h1 {
margin: 0 0 15px;
padding: 0;
font-size: 36px;
font-weight: 300;
color: #1a1a1a;
}
.container .info span {
color: #4d4d4d;
font-size: 12px;
}
.container .info span a {
color: #000000;
text-decoration: none;
}
.container .info span .fa {
color: #EF3B3A;
}
body {
background: #4778b7;
/* fallback for old browsers */
background: -webkit-linear-gradient(right, #4778b7, #4778b7);
background: -moz-linear-gradient(right, #4778b7, #4778b7);
background: -o-linear-gradient(right, #4778b7, #4778b7);
background: linear-gradient(to left, #4778b7, #4778b7);
font-family: "Roboto", sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
<html>
<head>
<meta http-equiv='X-UA-Compatible' content='IE=edge' />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://sapui5.hana.ondemand.com/resources/sap-ui-core.js" id="sap-ui-bootstrap" data-sap-ui-xx-bindingSyntax="complex" data-sap-ui-libs="sap.m" data-sap-ui-theme="sap_bluecrystal">
</script>
</head>
<body class='sapUiBody'>
<div id='content'></div>
<div id="grid" class="container-fluid">
<div class="row no-gutter">
<div class="col-md-2">
<div id="column_1">
<div class="list-group"></div>
<div class='col-md-auto'>
<button type='button' id=1 class='list-group-item'>test</button>
</div>
</div>
</div>
<div class="col-md-2 ">
<div id="column_2">
<div class="list-group"></div>
</div>
</div>
<div class="col-md-2 ">
<div id="column_3">
<div class="list-group"></div>
</div>
</div>
<div class="col-md-2 ">
<div id="column_4">
<div class="list-group"></div>
</div>
</div>
<div class="col-md-2">
<div id="column_5">
<div class="list-group"></div>
</div>
</div>
</div>
</div>
</body>
</html>

it was sap-ui-core.js causing problem; using jQuery noConflict.
$.noConflict();
$(document).ready(function() {
...
});

Normally you don't need the following code in your HTML, because they are duplicated
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
And where did you place the js code? The $(document).ready(function(){ one. It must be place after the all of the js library.

Related

JavaScript animations not working (no button flash) and no audio when button clicked

I am working on an online boot camp project and could not get my code to create the proper animation. When I press one of the colored buttons, it should flash, but nothing happens. I downloaded the solution file and it also does not work.
I also tried adding:
console.log(userClickedPattern);
playSound(userChosenColor);
to the bottom of the:
$("#btn").click(function(){}
but that did not seem to make a difference.
What am I doing wrong?
var buttonColors = ["red", "blue", "green", "Yellow"];
var gamePattern = [];
var userClickedPattern = [];
$("#btn").click(function() {
var userChosenColor = $(this).attr("id");
userClickedPattern.push(userChosenColor);
playSound(userChosenColor);
animatePress(userChosenColor);
});
function nextSequence() {
var randomNumber = Math.floor(Math.random() * 4);
var randomChosenColor = buttonColors[randomNumber];
gamePattern.push(randomChosenColor);
$("#" + randomChosenColor).fadeIn(100).fadeOut(100).fadeIn(100);
playSound(randomChosenColor);
}
function playSound(name) {
var audio = new Audio("sounds/" + name + ".mp3");
audio.play();
}
function animatePress(currentColor) {
$("#" + currentColor).addClass("pressed");
setTimeout(function() {
$("#" + currentColor).removeClass("pressed");
}, 100);
}
body {
text-align: center;
background-color: #011F3F;
}
#level-title {
font-family: 'Press Start 2P', cursive;
font-size: 3rem;
margin: 5%;
color: #FEF2BF;
}
.container {
display: block;
width: 50%;
margin: auto;
}
.btn {
margin: 25px;
display: inline-block;
height: 200px;
width: 200px;
border: 10px solid black;
border-radius: 20%;
}
.game-over {
background-color: red;
opacity: 0.8;
}
.red {
background-color: red;
}
.green {
background-color: green;
}
.blue {
background-color: blue;
}
.yellow {
background-color: yellow;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Simon</title>
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Press+Start+2P" rel="stylesheet">
</head>
<body>
<h1 id="level-title">Press A Key to Start</h1>
<div class="container">
<div class="row">
<div type="button" id="green" class="btn green"></div>
<div type="button" id="red" class="btn red"></div>
</div>
<div class="row">
<div type="button" id="yellow" class="btn yellow"></div>
<div type="button" id="blue" class="btn blue"></div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="game.js" charset="utf-8"></script>
</body>
</html>
You forgot to define class pressed also your selector for the buttons was wrong #btn instead of .btn
var buttonColors = ["red", "blue", "green", "Yellow"];
var gamePattern = [];
var userClickedPattern = [];
$(".btn").click(function() {
var userChosenColor = $(this).attr("id");
userClickedPattern.push(userChosenColor);
playSound(userChosenColor);
animatePress(userChosenColor);
});
function nextSequence() {
var randomNumber = Math.floor(Math.random() * 4);
var randomChosenColor = buttonColors[randomNumber];
gamePattern.push(randomChosenColor);
$("#" + randomChosenColor).fadeIn(100).fadeOut(100).fadeIn(100);
playSound(randomChosenColor);
}
function playSound(name) {
var audio = new Audio("sounds/" + name + ".mp3");
audio.play();
}
function animatePress(currentColor) {
$("#" + currentColor).addClass("pressed");
setTimeout(function() {
$("#" + currentColor).removeClass("pressed");
}, 100);
}
body {
text-align: center;
background-color: #011F3F;
}
#level-title {
font-family: 'Press Start 2P', cursive;
font-size: 3rem;
margin: 5%;
color: #FEF2BF;
}
.container {
display: block;
width: 50%;
margin: auto;
}
.btn {
margin: 25px;
display: inline-block;
height: 200px;
width: 200px;
border: 10px solid black;
border-radius: 20%;
}
.game-over {
background-color: red;
opacity: 0.8;
}
.red {
background-color: red;
}
.green {
background-color: green;
}
.blue {
background-color: blue;
}
.yellow {
background-color: yellow;
}
.pressed {
border: 2px solid red;
background: black;
opacity: 0.2;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<title>Simon</title>
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Press+Start+2P" rel="stylesheet">
<h1 id="level-title">Press A Key to Start</h1>
<div class="container">
<div class="row">
<div type="button" id="green" class="btn green"></div>
<div type="button" id="red" class="btn red"></div>
</div>
<div class="row">
<div type="button" id="yellow" class="btn yellow"></div>
<div type="button" id="blue" class="btn blue"></div>
</div>
</div>

How to print out dynamic items from array to the DOM

I am stuck in a logical problem.
I have an array where i am stacking items with array.push() where came up from a user's Input.
Problem is now:
How can i print these items to the DOM? ATM i am doing this,
function getInput(operator, description, value) {
// SAVE IN INCOME IF "+" IS CHOOSEN (DEFAULT)
if (addType.value == 'inc') {
let op = incomeArr['operator'] = operator;
let des = incomeArr['description'] = description;
let val = incomeArr['value'] = value;
incomeArr.push([op, des, val]);
return incomeArr;
}
}
Creating a associative array in the getInput();
First attempt to print this data into the DOM looked like this:
function printToDOM(item) {
// every function call should run this once to update the UI
const incomeList = document.querySelector('.income__list');
const expenseList = document.querySelector('.expenses__list');
let incomeItemSpan = `<span> ${item.description}: ${item.value} </span></br>`;
let expenseItemSpan = `<span> ${item.description}: ${item.value} </span> </br>`;
for (var i = 0; i < expenseArr.length; i++) {
incomeItemSpan;
incomeList.append(incomeItemSpan);
}
}
My problem here is that my forLoop index condition is messing up because of the "everytime function call" the value which is printed out will be printed twice in the next function call of this. the index start again at 0 and even with a out of function loop counter this will not work.
[![gave-input][1]][1]
So the next attempt was:
function printToDOM(item) {
// every function call should run this once to update the UI
const incomeList = document.querySelector('.income__list');
const expenseList = document.querySelector('.expenses__list');
let incomeItemSpan = `<span> ${item.description}: ${item.value} </span></br>`;
let expenseItemSpan = `<span> ${item.description}: ${item.value} </span> </br>`;
incomeArr.forEach(() => {
incomeList.innerHTML = incomeItemSpan;
});
}
i tried it with a forEach and the problem here is, i have absolutely no idea how to print out the incomeItemSpan without a innerHTML. I want a list of items in the DOM which are stacked from top down, every line is a new item from the array like i would use item.append(), but HTML wont work in a append().
How can i do this?
/* TODO:
- Add Eventlistener for Submit a +/- Value
- if + {add 1. into INCOME section} + Set INCOME in header to the amount
of all incomes added
if - {same like if+ just for -}
- create a update DOM function to update the visualisation of the calculations
- INCOME AND EXPENSES should be a Array
- add a prototype function to remove entrys from INCOME and EXPENSES, use
indexOf to get the index item and remove with array.splice().
- calc every expense with INCOME to get a % value of how much this entry is
% related to the max INCOME
*/
// VARS:
let addType = document.querySelector('.add__type');
let description = document.querySelector('.add__description');
let addValue = document.querySelector('.add__value');
let incomeArr = [];
let expenseArr = [];
// EVENTLISTENER Constructor:
function EventListner(selector, listner, fnt) {
this.selector = selector;
this.listner = listner;
this.fnt = fnt;
document.querySelector(selector).addEventListener(listner, fnt);
};
// getInput VALUES FROM USER Constructor:
function getInput(operator, description, value) {
// SAVE IN INCOME IF "+" IS CHOOSEN (DEFAULT)
if (addType.value == 'inc') {
let op = incomeArr['operator'] = operator;
let des = incomeArr['description'] = description;
let val = incomeArr['value'] = value;
incomeArr.push([op, des, val]);
// TODO: WHAT AFTER SAVING?
return incomeArr;
}
// SAVE IN EXPENSE IF "-" IS CHOOSEN
if (addType.value == 'exp') {
let op = expenseArr['operator'] = operator;
let des = expenseArr['description'] = description;
let val = expenseArr['value'] = value;
expenseArr.push([op, des, val]);
// TODO: WHAT AFTER SAVING?
return expenseArr;
}
};
// STUCK AS FUCK!
function printToDOM(item) {
// every function call should run this once to update the UI
const incomeList = document.querySelector('.income__list');
const expenseList = document.querySelector('.expenses__list');
let incomeItemSpan = `<span> ${item.description}: ${item.value} </span></br>`;
let expenseItemSpan = `<span> ${item.description}: ${item.value} </span> </br>`;
incomeArr.forEach(() => {
incomeList.innerHTML = incomeItemSpan;
});
// for (var i = 0; i < incomeArr.length; i++) {
// console.log([i]);
// incomeItemSpan;
// incomeList.append(incomeItemSpan);
// }
// console.log(incomeItemSpan);
//
// incomeList.append(expenseArr);
// incomeArr.toString();
// expenseArr.toString();
// incomeList.innerHTML = incomeItemSpan;
};
const main = (function() {
// EVENTLISTENERS
const clickListener = new EventListner('.add__btn', 'click', () => {
if (description.value == '' || addValue.value == '') {
// MAKE SURE DESCRIPTION AND VALUE IS NOT EMPTY
alert('description and value can\'t be empty');
return;
}
getInput(addType.value, description.value, addValue.value);
});
const enterKeyListener = new EventListner('.add__value', 'keypress', (e) => {
let testArray = [];
for (var i = 0; i < testArray.length; i++) {
testArray[i] = [i];
console.log(testArray[i]);
}
testArray.push('item');
if (e.keyCode == 13) {
if (description.value == '' || addValue.value == '') {
// MAKE SURE DESCRIPTION AND VALUE IS NOT EMPTY
alert('description and value can\'t be empty');
return;
}
// ON ENTER SAVE VALUES IN AN ARRAY
// IF PLUS INTO incomeArr, ON MINUS INTO expenseArr
// getInput(addType.value, description.value, addValue.value);
printToDOM(getInput(addType.value, description.value, addValue.value));
}
});
}());
//
/**********************************************
*** 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">+ 0</div>
<div class="budget__income clearfix">
<div class="budget__income--text">Income</div>
<div class="right">
<div class="budget__income--value">+ 0</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">- 0</div>
<div class="budget__expenses--percentage">0%</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"></div>
<div class="right clearfix">
<div class="item__value"></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>
Is that exactly what you're looking for?
const arr = new Array();
function addList() {
const el = document.querySelector("input[name=user]")
const val = el.value
arr.push(val);
el.value = null;
return false;
}
function showList() {
for (let i = 0; i < arr.length; i++) {
const listElement = document.createElement("li");
listElement.textContent = arr[i]
document.body.appendChild(listElement);
}
}
<form onsubmit="return addList()">
<input type="text" name="user">
<button>Add list item</button>
</form><br>
<button class="showList" onclick="showList()">Show list</button>
<ul class="list"></ul>
For creating a list of items, create a ordered/unordered list then append each item to this list in forEach and finally set the html to ordered//unordered list.
Example:
var ol=$('<ol></ol>');
incomeArr.forEach(() => {
ol.append($('<li></li>').text(`${item.description}: ${item.value}`));
});
$('#display').html(ol);

Dividing a website into 3 sections -> 1 horizontally and 2 vertically below

i have a Sidebar on the left of the Screen. I can toggle it by pressing a button. On the right I have the content.
I want to place the button on a horizontal bar on the top. The sidebar seems to cover this bar so I can not see the button.
This is my current code:
The Html File:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>
</title>
</head>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
<script src="MainController.js"></script>
<link rel="stylesheet" type="text/css" href="MainStyle.css">
<body onload="InitDocument()">
<div id="topBar">
<button id="btnNavToggle" type="button" onclick="ToggleNavbar()">Menu</button>
</div>
<div id="container">
<div id="sideNav">
<button type="button" onclick="NewEntry()">+</button>
<p>test</p>
</div>
<div id="mainArea">
<p>Title:</p>
<input id="titleInputField" type="text">
<p>Text:</p>
<textarea id="textArea"> </textarea>
<p></p>
<button type="button" onclick="SaveEntry()">Save</button>
</div>
</div>
</body>
</html>
The Css File:
body{
background-color: #EEEEEE;
color: #000000;
}
* {
margin: 0;
padding: 0;
}
#sideNav {
height: 100%;
width: 0;
position: fixed;
z-index: 1;
top: 0;
left: 0;
overflow-x: hidden;
background-color: #333333;
color: #EEEEEE;
}
The Js File:
var navIsOpen = true;
function InitDocument(){ // Initialization
ToggleNavbar();
}
function ToggleNavbar(){ // show - hide the navbar
var sideNavWidth = "0px";
var mainAreaWidth = "0px";
if (navIsOpen)
{
sideNavWidth = "200px";
mainAreaWidth = "200px";
}
$("#sideNav").width(sideNavWidth);
$("#mainArea").css('margin-left',mainAreaWidth);
navIsOpen = !navIsOpen;
}
function SaveEntry(){ // save the entry
var txtTitle = $("#titleInputField").val();
var txtField = $("#textArea").val();
alert(txtTitle + "#" + txtField);
}
function NewEntry() { // create a new entry
alert("neuer Eintrag");
}
This is what I want to archieve
It seems I just have to fix the CSS to get it done.
I added margin-top:0; to your topBar and removed top: 0; from your sideNav.
Try this:
var navIsOpen = true;
function InitDocument(){ // Initialization
ToggleNavbar();
}
function ToggleNavbar(){ // show - hide the navbar
var sideNavWidth = "0px";
var mainAreaWidth = "0px";
if (navIsOpen)
{
sideNavWidth = "200px";
mainAreaWidth = "200px";
}
$("#sideNav").width(sideNavWidth);
$("#mainArea").css('margin-left',mainAreaWidth);
navIsOpen = !navIsOpen;
}
function SaveEntry(){ // save the entry
var txtTitle = $("#titleInputField").val();
var txtField = $("#textArea").val();
alert(txtTitle + "#" + txtField);
}
function NewEntry() { // create a new entry
alert("neuer Eintrag");
}
body{
background-color: #EEEEEE;
color: #000000;
}
*{
margin: 0;
padding: 0;
}
#topBar {
margin-top:0;
background-color: navy;
}
#sideNav {
height: 100%;
width: 0;
position: fixed;
z-index: 1;
left: 0;
overflow-x: hidden;
background-color: #333333;
color: #EEEEEE;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>
</title>
</head>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
<script src="MainController.js"></script>
<link rel="stylesheet" type="text/css" href="MainStyle.css">
<body onload="InitDocument()">
<div id="topBar">
<button id="btnNavToggle" type="button" onclick="ToggleNavbar()">Menu</button>
</div>
<div id="container">
<div id="sideNav">
<button type="button" onclick="NewEntry()">+</button>
<p>test</p>
</div>
<div id="mainArea">
<p>Title:</p>
<input id="titleInputField" type="text">
<p>Text:</p>
<textarea id="textArea"> </textarea>
<p></p>
<button type="button" onclick="SaveEntry()">Save</button>
</div>
</div>
</body>
</html>
Try this:
var navIsOpen = true;
function InitDocument(){ // Initialization
ToggleNavbar();
}
function ToggleNavbar(){ // show - hide the navbar
var sideNavWidth = "0px";
var mainAreaWidth = "0px";
if (navIsOpen)
{
sideNavWidth = "200px";
mainAreaWidth = "200px";
}
$("#sideNav").width(sideNavWidth);
$("#mainArea").css('margin-left',mainAreaWidth);
navIsOpen = !navIsOpen;
}
function SaveEntry(){ // save the entry
var txtTitle = $("#titleInputField").val();
var txtField = $("#textArea").val();
alert(txtTitle + "#" + txtField);
}
function NewEntry() { // create a new entry
alert("neuer Eintrag");
}
body{
background-color: #EEEEEE;
color: #000000;
}
* {
margin: 0;
padding: 0;
}
#main {
display: flex;
flex-direction: column;
}
#sideNav {
height: 100%;
width: 0;
position: fixed;
z-index: 1;
top: 50px;
left: 0;
overflow-x: hidden;
background-color: #333333;
color: #EEEEEE;
}
#topBar {
position: fixed;
display: inline-block;
width: 100%;
height: 50px;
background-color: red;
}
#container {
display: flex;
padding-top: 50px;
flex: 1;
flex-direction: row;
}
<html>
<head>
<meta charset="utf-8" />
<title>
</title>
</head>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
<script src="MainController.js"></script>
<link rel="stylesheet" type="text/css" href="MainStyle.css">
<body onload="InitDocument()">
<div id="main">
<div id="topBar">
<button id="btnNavToggle" type="button" onclick="ToggleNavbar()">Menu</button>
</div>
<div id="container">
<div id="sideNav">
<button type="button" onclick="NewEntry()">+</button>
<p>test</p>
</div>
<div id="mainArea">
<p>Title:</p>
<input id="titleInputField" type="text">
<p>Text:</p>
<textarea id="textArea"> </textarea>
<p></p>
<button type="button" onclick="SaveEntry()">Save</button>
</div>
</div>
</div>
</body>
</html>
Take a look flex-box concepts
Checkout this example of using the new HTML5 semantic elements.
http://www.w3schools.com/html/html5_semantic_elements.asp
I have taken most of the example elements from the link above and created a simple HTML5 page.
You can add/remove/modify any of the section below by removing the HTML or removing/adding additional CSS properties.
var toggleButton = document.getElementById('toggle-button');
var pageWrapper = document.getElementsByClassName('wrapper')[0];
toggleButton.addEventListener('click', function() {
toggleClass(pageWrapper, 'toggle-hidden')
});
function toggleClass(el, className) {
if (el.classList) {
el.classList.toggle(className);
} else {
var classes = el.className.split(' ');
var existingIndex = classes.indexOf(className);
if (existingIndex >= 0) classes.splice(existingIndex, 1);
else classes.push(className);
el.className = classes.join(' ');
}
}
header, footer {
width: 100%;
text-align: center;
background: #DDD;
padding: 0.25em !important;
}
.title {
font-weight: bold;
font-size: 2.25em;
margin-bottom: 0.5em;
}
.subtitle {
font-size: 1.5em;
font-style: italic;
}
.wrapper {
background: #EEE;
}
nav {
text-align: center;
background: #CCC;
padding: 0.25em !important;
}
aside {
float: left;
top: 0;
width: 12em;
height: 100%;
padding: 0.25em !important;
}
aside a {
display: block;
text-decoration: none;
margin-bottom: 0.5em;
}
aside a:before {
content: '➢ ';
}
article, section {
margin-left: 12em !important;
background: #FFF;
padding: 0.25em !important;
}
/* Default HTML4 typography styles */
h1 { font-size: 2.00em !important; margin: 0.67em 0 !important; }
h2 { font-size: 1.50em !important; margin: 0.75em 0 !important; }
h3 { font-size: 1.17em !important; margin: 0.83em 0 !important; }
h5 { font-size: 0.83em !important; margin: 1.50em 0 !important; }
h6 { font-size: 0.75em !important; margin: 1.67em 0 !important; }
h1, h2, h3, h4, h5, h6 { font-weight: bolder !important; }
p { font-size: 1.00em !important; margin: 1em 0 !important; }
#toggle-button {
display: block;
position: absolute;
width: 5em;
height: 5em;
line-height: 1.5em;
text-align: center;
}
.wrapper.toggle-hidden aside {
display: none;
width: 0;
}
.wrapper.toggle-hidden article, .wrapper.toggle-hidden section {
margin-left: 0 !important;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css" rel="stylesheet"/>
<header>
<button id="toggle-button">Toggle<br />Sidebar</button>
<div class="title">What Does WWF Do?</div>
<div class="subtitle">WWF's mission:</div>
</header>
<div class="wrapper">
<nav>
HTML |
CSS |
JavaScript |
jQuery
</nav>
<aside>
<h1>Links</h1>
HTML
CSS
JavaScript
jQuery
</aside>
<section>
<h1>WWF</h1>
<p>The World Wide Fund for Nature (WWF) is....</p>
</section>
<article>
<h1>What Does WWF Do?</h1>
<p>WWF's mission is to stop the degradation of our planet's natural environment,
and build a future in which humans live in harmony with nature.</p>
</article>
</div>
<footer>
<p>Posted by: Hege Refsnes</p>
<p>Contact information: someone#example.com.</p>
</footer>

I am trying to insert a chunk of html code dynamically with Javascript reading smaple json, but unable to do so

Went through a few questions on stackoverflow but could not solve the error.
The intention is to modify and add html to the main document reading a JSON structure.
Uncaught TypeError: Cannot read property 'appendChild' of undefined
Update 1:-
Typo was corrected, marked in code.
Defer was introduced at script load in head section, this makes sure the entire document is loaded before the script starts execution.
Here I am trying to read a JSON, and then looping across its content to add to my main html document.
var json={
"fruit":[
{
"fruitname":"Apple",
"location":"data/png/apple.png",
"quantity":"25",
"price":"2"
},
{
"fruitname":"Mango",
"location":"data/png/mango.png",
"quantity":"35",
"price":"3"
}
]
};
//var cards = document.getElementsByClassName("content"); -- corrected typo
var cards = document.getElementById("content");
var fruits = json.fruit;
//alert(fruits.length);
//alert(fruits[1].fruitname);
for (var i = 0; i < fruits.length; i++) {
var cardelement=document.createElement('div');
cardelement.className = 'card';
// alert(cardelement);
cards.appendChild(cardelement);
var object = document.createElement('div');
object.className = 'object';
// alert(object);
cardelement.appendChild(object);
var image = document.createElement('img');
image.setAttribute("src", fruits[i].location);
object.appendChild(image);
var objectback = document.createElement('div');
objectback.className = 'object-back';
cardelement.appendChild(objectback);
var backfruit = document.createElement('div');
backfruit.className = 'back-fruit';
backfruit.innerHTML = fruits[i].fruitname;
objectback.appendChild(backfruit);
var backprice = document.createElement('div');
backprice.className = 'back-price';
backprice.innerHTML = fruits[i].price + "$ per unit";
objectback.appendChild(backprice);
var backquantity = document.createElement('div');
backquantity.className = 'back-quantity';
backquantity.innerHTML = "In Stock " + fruits[i].quantity + " units";
objectback.appendChild(backquantity);
}
*
{
margin: 0 0;
border: none;
text-align:center
}
#header
{
background-color: #F44336;
font-family: 'Bungee Shade', cursive;
font-size: 30px;
height: 20%
}
#footer
{
font-family: 'Roboto', sans-serif;
position: fixed;
height: 80%;
width: 100%
}
#content
{
width: 75%;
height: 100%;
border-right: thick solid #F44336;
float: left;
text-align: left;
overflow: scroll
}
#cart
{
background-color:#3F51B5;
width: 25%;
border-bottom: thick dashed #F44336;
float: right
}
.card
{
display:inline-block;
width: 100px;
height: 100px;
margin: 40px;
padding: 20px;
box-shadow: -1px 9px 20px 4px #000000;
border: 5px solid #F44336;
border-radius: 26px 26px 26px 26px;
transition: all .2s ease-in-out
}
.object .object-back
{
display:block;
position:static
}
.object-back
{
display: none
}
.object img
{
height: 100px;
width: 100px
}
.back-fruit
{
font-size: 20px;
padding-bottom: 5px;
margin-bottom: 10px;
border-bottom: thin solid
}
.back-price
{
font-size: 12px;
padding-bottom: 5px
}
.back-quantity
{
font-size: 10px;
padding-bottom: 10px
}
.back-pluscart
{
font-size: 15px;
background-color: #F44336;
width: auto
}
.back-pluscart img
{
height: 30px;
width: 30px
}
.card:hover
{
box-shadow: -1px 9px 46px 11px #000000
}
.card:hover .object
{
display: none
}
.card:hover .object-back
{
display:inline-block;
opacity: 1
}
<!DOCTYPE html>
<html>
<head>
<title> The Shopkeeper </title>
<link href="https://fonts.googleapis.com/css?family=Bungee+Shade" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<link rel = "stylesheet" type = "text/css" href = "style/style.css" />
<script type="text/javascript" src="logic/core.js" defer></script>
<meta name="viewport" content="width=device-width">
</head>
<body>
<div id="base">
<div id="header">
<h1> Fruitkart </h1>
</div>
<div id="footer">
<div id="content">
<!--
<div class="card">
<div class="object">
<img src="data/png/apple.png" />
</div>
<div class="object-back">
<div class="back-fruit">Apple</div>
<div class="back-price">2$ per unit</div>
<div class="back-quantity">In Stock 25 pieces </div>
<div class="back-pluscart"> <img src="data/png/cart.png" /> </div>
</div>
</div>
-->
</div>
<div id="cart">
django
is a big boy
</div>
</div>
</div>
</body>
</html>
Why was content undefined
You try to get content by ClassName
var cards = document.getElementsByClassName("content")[0];
But find content in your html:
<div id="content">
Notice that the ID is content. Either change it to class="content" or change the previous code to document.getElementByID("content");
Two issues:
There is no element with class content. On the other hand there is an element with that id. So you probably want to do:
document.getElementById("content");
The script runs too soon -- the elements are not loaded yet when it runs. Either put the script just before the closing </body> tag, or put the code inside an event handler, like
window.addEventListener('DOMContentLoaded', function() {
// your code
});
You are trying to access an element with class name content var cards =document.getElementsByClassName("content")[0]; & there is no class named content
You can modify your code like this ,
var cards = document.getElementById("content");
var json={
"fruit":[
{
"fruitname":"Apple",
"location":"data/png/apple.png",
"quantity":"25",
"price":"2"
},
{
"fruitname":"Mango",
"location":"data/png/mango.png",
"quantity":"35",
"price":"3"
}
]
};
var cards = document.getElementById("content");
var fruits = json.fruit;
//alert(fruits.length);
//alert(fruits[1].fruitname);
for (var i = 0; i < fruits.length; i++) {
var cardelement=document.createElement('div');
cardelement.className = 'card';
// alert(cardelement);
cards.appendChild(cardelement);
var object = document.createElement('div');
object.className = 'object';
// alert(object);
cardelement.appendChild(object);
var image = document.createElement('img');
image.setAttribute("src", fruits[i].location);
object.appendChild(image);
var objectback = document.createElement('div');
objectback.className = 'object-back';
cardelement.appendChild(objectback);
var backfruit = document.createElement('div');
backfruit.className = 'back-fruit';
backfruit.innerHTML = fruits[i].fruitname;
objectback.appendChild(backfruit);
var backprice = document.createElement('div');
backprice.className = 'back-price';
backprice.innerHTML = fruits[i].price + "$ per unit";
objectback.appendChild(backprice);
var backquantity = document.createElement('div');
backquantity.className = 'back-quantity';
backquantity.innerHTML = "In Stock " + fruits[i].quantity + " units";
objectback.appendChild(backquantity);
}
*
{
margin: 0 0;
border: none;
text-align:center
}
#header
{
background-color: #F44336;
font-family: 'Bungee Shade', cursive;
font-size: 30px;
height: 20%
}
#footer
{
font-family: 'Roboto', sans-serif;
position: fixed;
height: 80%;
width: 100%
}
#content
{
width: 75%;
height: 100%;
border-right: thick solid #F44336;
float: left;
text-align: left;
overflow: scroll
}
#cart
{
background-color:#3F51B5;
width: 25%;
border-bottom: thick dashed #F44336;
float: right
}
.card
{
display:inline-block;
width: 100px;
height: 100px;
margin: 40px;
padding: 20px;
box-shadow: -1px 9px 20px 4px #000000;
border: 5px solid #F44336;
border-radius: 26px 26px 26px 26px;
transition: all .2s ease-in-out
}
.object .object-back
{
display:block;
position:static
}
.object-back
{
display: none
}
.object img
{
height: 100px;
width: 100px
}
.back-fruit
{
font-size: 20px;
padding-bottom: 5px;
margin-bottom: 10px;
border-bottom: thin solid
}
.back-price
{
font-size: 12px;
padding-bottom: 5px
}
.back-quantity
{
font-size: 10px;
padding-bottom: 10px
}
.back-pluscart
{
font-size: 15px;
background-color: #F44336;
width: auto
}
.back-pluscart img
{
height: 30px;
width: 30px
}
.card:hover
{
box-shadow: -1px 9px 46px 11px #000000
}
.card:hover .object
{
display: none
}
.card:hover .object-back
{
display:inline-block;
opacity: 1
}
<!DOCTYPE html>
<html>
<head>
<title> The Shopkeeper </title>
<link href="https://fonts.googleapis.com/css?family=Bungee+Shade" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<link rel = "stylesheet" type = "text/css" href = "style/style.css" />
<script type="text/javascript" src="logic/core.js" ></script>
<meta name="viewport" content="width=device-width">
</head>
<body>
<div id="base">
<div id="header">
<h1> Fruitkart </h1>
</div>
<div id="footer">
<div id="content">
<!--
<div class="card">
<div class="object">
<img src="data/png/apple.png" />
</div>
<div class="object-back">
<div class="back-fruit">Apple</div>
<div class="back-price">2$ per unit</div>
<div class="back-quantity">In Stock 25 pieces </div>
<div class="back-pluscart"> <img src="data/png/cart.png" /> </div>
</div>
</div>
-->
</div>
<div id="cart">
django
is a big boy
</div>
</div>
</div>
</body>
</html>

javascript is will not run

I am trying to create a simple vote/poll program with javascript, I have tried to run it on xammp to see if it needed to be executed on a web server with no success. Do I need to include any script js files apart from vote.js like jquery or something? I am not sure.
Can someone help Thanks.
html
<!DOCTYPE html>
<html>
<head>
<title>Vote</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="vote.js"></script>
</head>
<body>
<div class="content">
<h3 class="title">Who's better ?</h3>
<ul>
<li class="option" id="option_1">
Messi
<p class="score" id="score_1">0</p>
<div class="progressbar">
</div>
</li>
<li class="option" id="option_2">
Ronaldo
<p class="score" id="score_2">0</p>
<div class="progressbar">
</div>
</li>
</ul>
</div>
</body>
</html>
css
.content {
background-color: #5C5C5C;
height: 500px;
width: 600px;
font-family: CorpidRegular,Arial,Helvetica,sans-serif;
color: #fff;
font-weight: normal;
font-size: 1.5rem;
}
.progressbar_1 {
width: 400px;
border-radius: 0px;
margin-left: 100px;
}
.progressbar_2 {
width: 400px;
border-radius: 0px;
margin-left: 100px;
}
h3{
text-align: center;
padding: 40px;
margin: 0px;
font-weight: normal;
}
ul{
list-style-type: none;
display: inline;
padding: 0px;
}
.option:first-child {
background: blue;
}
.option {
background: black;
}
li{
margin: 0px;
padding: 0px;
text-align: center;
color: #fff;
cursor: pointer;
}
li:hover {
color: yellow;
}
js
var totalVotes = 0;
$('.option').click(function() {
var $this = $(this);
// store voting value in data-voting
if (!$this.data('voting'))
$this.data('voting', 0);
var voting = parseInt($this.data('voting'), 10);
voting++;
totalVotes++;
$this.data('voting', voting);
updateProgressBars();
});
function updateProgressBars()
{
$('.option').each(function()
{
var $this = $(this);
var voting = parseInt($(this).data('voting'), 10);
var pct = Math.round((voting / totalVotes) * 100);
if (isNaN(voting)) voting = 0;
if (isNaN(pct)) pct = 0;
$this.find('progressbar').progressbar({value: pct});
$this.find('.score').html(voting + ' of ' + totalVotes + ' (' + pct + '%)');
});
}
You only close html tag, didin't open tag

Categories

Resources