Currently I am working on a card voting system. I can get it to work properly in a jsfiddle but when i use microsoft visual studious and debug it, the cards do not display.
Here is my fiddle
http://jsfiddle.net/grahamwalsh/6RnXM/
and here is my code
Voting (Html)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Voting</title>
<script src="Scripts/jquery-2.1.1.js"></script>
<script src="Scripts/knockout-3.1.0.js"></script>
<script src="Voting.js"></script>
<script src="Voting.css"></script>
</head>
<body>
<div data-bind="foreach: items">
<div class="profile" data-bind="text: name, click: $parent.clicked, enable: active, css:{highlight: active()}"></div>
</div>
<hr>
<h2>Selected Card</h2>
<div data-bind="foreach: selectedItems">
<div data-bind="text: name"></div>
</div>
<input type="button" data-bind="click: save" value="Save">
</body>
</html>
Voting (CSS)
body {.profile {
width: 50px;
height: 80px;
color: black;
background-color:silver;
border: 1px solid black;
float: left;
line-height:80px;
text-align: center;
margin: 2px;
}
.highlight {
background: yellow !important;
border:1px solid #000;
color: black;
}
}
function Card(number) {
this.active = ko.observable(false);
this.name = ko.observable(number);
}
var model = function () {
var cards = [1, 2, 3, 5, 8, 13, 20, 40, 100];
for (var i = 0 ; i < cards.length ; i++)
cards[i] = new Card(cards[i]);
var items = ko.observableArray(cards)
var selectedItems = ko.computed(function () {
return _.filter(items(), function (item) {
return item.active();
});
})
var clicked = function (item) {
items().forEach(function (item) { item.active(false) });
item.active(!this.active());
};
var save = function () {
alert("sending items \n" + ko.toJSON(selectedItems()));
}
return {
items: items,
selectedItems: selectedItems,
save: save,
clicked: clicked
}
}
ko.applyBindings(model);
Voting (Js)
function Card(number) {
this.active = ko.observable(false);
this.name = ko.observable(number);
}
var model = function () {
var cards = [1, 2, 3, 5, 8, 13, 20, 40, 100];
for (var i = 0 ; i < cards.length ; i++)
cards[i] = new Card(cards[i]);
var items = ko.observableArray(cards)
var selectedItems = ko.computed(function () {
return _.filter(items(), function (item) {
return item.active();
});
})
var clicked = function (item) {
items().forEach(function (item) { item.active(false) });
item.active(!this.active());
};
var save = function () {
alert("sending items \n" + ko.toJSON(selectedItems()));
}
return {
items: items,
selectedItems: selectedItems,
save: save,
clicked: clicked
}
}
ko.applyBindings(model);
Related
Once a draggable element's been dropped into a valid target i.e the user's answered the question correctly s/he can move on to the next one. I'd like the next question to be positioned at the exact same place as the previous one. In order to do so I've created the newElement() function. But it's not working as it should be. I've tried to use different methods such as insertBefore() but the console keep throwing message like: "Uncaught DOMException: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node". appendChild() isn't working either. I know it's something to do with DOM manipulation but I haven't the foggiest how to go about solving this issue. Help please.
const questionQuiz = document.querySelector(".question");
const answerChoices = document.querySelector(".answerchoices");
const allChoices = Array.from(document.querySelector(".answerchoices").children);
const choiceA = document.querySelector(".choiceA");
const choiceB = document.querySelector(".choiceB");
const choiceC = document.querySelector(".choiceC");
const start = document.querySelector(".start");
const quizSection = document.querySelector(".quizSection");
const choices = document.querySelectorAll(".choice");
const answerSection = document.querySelector(".answerSection");
const counter = document.querySelector(".counter");
const timerBar = document.querySelector(".timerBar");
const finalScore = document.querySelector(".finalScore");
const parent = document.querySelector(".parent");
console.log(quizSection)
let questions = [
{
question: "How many Grand Slam men's singles titles has he won?",
choiceA: 10,
choiceB: 15,
choiceC: 20,
questionImg: "url(images/federer.jpeg)",
correctAnswer: 20,
},
{
question: "How many Formula One World Championship has he won?",
choiceA: 5,
choiceB: 7,
choiceC: 10,
questionImg: "url(images/hamilton.jpeg)",
correctAnswer: 7,
},
{
question: "How many NBA title has Lebron won?",
choiceA: 6,
choiceB: 3,
choiceC: 4,
questionImg: "url(images/LeBron.png)",
correctAnswer: 4,
},
{
question: "How many Ballon D'or has the Argentinina won?",
choiceA: 5,
choiceB: 6,
choiceC: 7,
questionImg: "url(images/LeBron.png)",
correctAnswer: 7,
},
]
let lastQuestion = questions.length - 1;
let activeQuestion = 0;
let count = 0;
let score = 0;
let x = 0;
let timeUp = 10;
let timerBarLength = 800;
let unitBar = timerBarLength / timeUp;
let dragged;
start.addEventListener("click", startQuiz)
function startQuiz() {
start.style.visibility = "hidden";
parent.style.visibility = "visible";
renderQuestion();
progressBar();
setInterval(timerBarFunction, 1000);
setInterval(counterFunction, 1000);
}
function timerBarFunction() {
if(count < timeUp) {
timerBar.style.width = `${count*unitBar}px`
count++;
} else {
count = 0;
}
}
function progressBar() {
for(var questionIndex = 0; questionIndex < questions.length; questionIndex++) {
answerSection.innerHTML += `<div class="progress-boxes" id=${questionIndex}></div>`
}
}
function counterFunction() {
if(x <= timeUp) {
counter.innerHTML = x;
x++;
} else {
x = 0;
nextQuestion();
wrongAnswer();
}
}
function renderQuestion() {
let q = questions[activeQuestion]
choiceA.innerHTML = q.choiceA;
choiceB.innerHTML = q.choiceB;
choiceC.innerHTML = q.choiceC;
questionQuiz.innerHTML = q.question;
// document.body.style.backgroundImage = q.questionImg
}
questionQuiz.addEventListener("drag", function(e) {
})
questionQuiz.addEventListener("dragstart", function(e) {
console.log("start");
dragged = e.target;
console.log(dragged.innerHTML)
});
questionQuiz.addEventListener("dragend", function() {
console.log('end')
});
allChoices.forEach((choice) => {
choice.addEventListener("dragover", dragOver)
});
allChoices.forEach(choice => {
choice.addEventListener("dragenter", dragEnter)
});
allChoices.forEach(choice => {
choice.addEventListener("dragleave", dragLeave)
});
allChoices.forEach(choice => {
choice.addEventListener("drop", drop)
})
function dragOver(e) {
e.preventDefault()
console.log("dragover")
}
function dragEnter(e) {
e.preventDefault();
console.log("dragenter");
}
function dragLeave() {
console.log("dragleave")
}
function drop(e) {
e.preventDefault()
if(parseInt(e.target.innerHTML) !== questions[activeQuestion].correctAnswer) {
wrongAnswer();
nextQuestion()
} else {
correctAnswer();
score++;
e.target.appendChild(dragged);
nextQuestion();
newElement();
}
}
function correctAnswer() {
document.getElementById(activeQuestion).style.backgroundColor = "green";
}
function wrongAnswer() {
document.getElementById(activeQuestion).style.backgroundColor = "red";
}
function nextQuestion() {
count = 0;
if(activeQuestion < lastQuestion) {
activeQuestion++
renderQuestion();
} else {
renderScore();
}
}
function renderScore() {
finalScore.innerHTML = score;
finalScore.style.visibility = "visible";
}
function newElement() {
let newDiv = document.createElement("div");
newDiv.setAttribute("class", "question");
newDiv.setAttribute("draggable", "true");
newDiv.innerHTML = questions[activeQuestion].question;
parent.appendChild(newDiv);
// document.body.insertBefore(newDiv, answerChoices.nextSibling);
}
body {
background-repeat: no-repeat;:
}
.answerchoices > *{
margin-bottom: 15px;
}
.answerSection {
display: grid;
grid-template-columns: repeat(4, 1fr);
justify-items: center;
}
.start {
width: 100px;
height: 100px;
border: 1px solid black;
}
.finalScore {
visibility: hidden;
}
.quizSection {
display: grid;
grid-template-columns: repeat(3, 1fr);
}
.question,
.answerchoices > *{
height: 100px;
width: 100px;
border: 1px black solid;
}
.progress-boxes {
height: 30px;
width: 30px;
color: grey;
background-color: grey;
margin: 10px;
}
.timerBar {
height: 5px;
/* width: 800px; */
color: blue;
background-color: purple;
border: 1px black solid;
}
.parent {
visibility: hidden;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="index.css">
<title>Drag And Drop</title>
</head>
<body>
<div class="parent">
<div class="quizSection">
<div class="question" draggable="true"></div>
<div class=answerchoices>
<div class="choiceA">choiceA</div>
<div class="choiceB">choiceB</div>
<div class="choiceC">choiceC</div>
</div>
</div>
<div class="answerSection"></div>
<div class="counter"></div>
<div class="timerBar"></div>
<div class="finalScore"></div>
</div>
<div class="start">Cick here to start quizz</div>
<script src="index.js" type="text/javascript"></script>
</body>
</html>
I am working on a autocomplete feature and to populate in on a list currently the list is just showing the results but I can't select them to add it to the input element.
Here is a sample of the code:
var search_terms = ['a', 'b', 'c'];
function autocompleteMatch(input) {
if (input == '') {
return [];
}
var reg = new RegExp(input);
return search_terms.filter(function(term) {
if (term.match(reg)) {
return term;
}
});
}
function showResults(val) {
res = document.getElementById("result");
res.innerHTML = '';
let list = '';
let terms = autocompleteMatch(val);
for (i = 0; i < terms.length; i++) {
list += '<li>' + terms[i] + '</li>';
}
res.innerHTML = '<ul>' + list + '</ul>';
}
<input type="text" class="form-control" placeholder="Explain in fewer words with the primary product key word (Eg: OneDrive sync issue, etc.)" name="post" required id="id_post" onKeyUp="showResults(this.value)">
<span class="fas fa-asterisk" style="font-size:12px;color:red;position:absolute; right:20px;top:12px;" id="asterix"></span>
<div id="result"></div>
Any advice to add the elements on list to the input. I've search for similar suggestions but I couldn't apply the answers to my code.
Edit: In my case the solutions posted here were not working because the calling of the script
<script type="text/javascript" src="app.js" charset="utf-8"></script>
was at the top. So it was failing with a Uncaught TypeError: Cannot read property 'addEventListener' of null. After moving <script> section to the end of the <body> suggested answers started to work.
Is this how it should work. I added an event listener to res that tests id a <li> was clicked. If so, the innerHTML of the <li> is inserted as value in the <input>. Using the dispatchEvent() I update the list as if it was a keyup event.
var search_terms = ['abc', 'abcde', 'abde'];
var res = document.getElementById("result");
var id_post = document.getElementById("id_post");
function autocompleteMatch(input) {
if (input == '') {
return [];
}
var reg = new RegExp(input)
return search_terms.filter(function(term) {
if (term.match(reg)) {
return term;
}
});
}
function showResults(val) {
let terms = autocompleteMatch(val);
list = terms.map(term => `<li>${term}</li>`).join('');
res.innerHTML = '<ul>' + list + '</ul>';
}
res.addEventListener('click', e => {
if(e.target.nodeName == "LI"){
id_post.value = e.target.innerHTML;
id_post.dispatchEvent(new Event('keyup'));
}
});
<input type="text" class="form-control" placeholder="Explain in fewer words with the primary product key word (Eg: OneDrive sync issue, etc.)" name="post" required id="id_post" onKeyUp="showResults(this.value)">
<div id="result"></div>
Considering your original code there are some missing details like autocomplete function and keyboard events (up/down/enter).
1) HTML
// form (autocomplete off) disables autocomplete integration with external tools like 1password
<form autocomplete="off">
<div class="autocomplete" id="autocomplete-container">
<input id="autocomplete-input" type="text" placeholder="Type Something...">
</div>
<input type="submit">
</form>
2) List of possible options (to make it dynamic, load the list before binding it to the autocomplete method)
const data = ["Aaa", "Aab", "Aac", "Abc", "Bbc", "Bbd", "Xpto", "Item1", "Item2", "SomethingElse"];
3) Autocomplete Functionality
const autocomplete = (container, inputElement, list) => {
var currentFocus = -1;
inputElement.addEventListener('input', () => {
var autocompleteText = inputElement.value;
hideList();
if (!autocompleteText) {
return false;
}
const autocompleteList = document.createElement('div');
autocompleteList.setAttribute('id', 'autocomplete-list');
autocompleteList.setAttribute('class', 'autocomplete-items');
container.appendChild(autocompleteList);
list.forEach((item, index) => {
if (
item.substr(0, autocompleteText.length).toUpperCase() ===
autocompleteText.toUpperCase()
) {
const tempId = `hiddenInput_${index}`;
const text = item.substr(0, autocompleteText.length);
const autocompleteMatch = document.createElement('div');
autocompleteMatch.innerHTML = `<strong>${text}</strong>`;
autocompleteMatch.innerHTML += item.substr(autocompleteText.length);
autocompleteMatch.innerHTML += `<input type='hidden' id='${tempId}' value='${item}'>`;
autocompleteMatch.addEventListener('click', (event) => {
const clickedElement = event.target.getElementsByTagName('input')[0];
inputElement.value = clickedElement.value;
hideList();
});
autocompleteList.appendChild(autocompleteMatch);
}
});
});
inputElement.addEventListener('keydown', function (e) {
const autoCompleteList = document.getElementById('autocomplete-list');
var autoCompleteDiv;
if (autoCompleteList) {
autoCompleteDiv = autoCompleteList.getElementsByTagName('div');
}
if (e.keyCode === 40) {
// KEY DOWN
currentFocus++;
addActive(autoCompleteDiv);
} else if (e.keyCode === 38) {
// KEY UP
currentFocus--;
addActive(autoCompleteDiv);
} else if (e.keyCode === 13) {
// ENTER
e.preventDefault();
if (currentFocus > -1 && autoCompleteDiv) {
autoCompleteDiv[currentFocus].click();
}
}
});
const addActive = (item) => {
if (!item) {
return false;
}
removeActive(item);
if (currentFocus >= item.length) {
currentFocus = 0;
}
if (currentFocus < 0) {
currentFocus = item.length - 1;
}
item[currentFocus].classList.add('autocomplete-active');
};
const removeActive = (autoCompleteItems) => {
Array.from(autoCompleteItems).forEach((item) => {
item.classList.remove('autocomplete-active');
});
};
const hideList = (element) => {
var autoCompleteItems =
document.getElementsByClassName('autocomplete-items');
if (autoCompleteItems && autoCompleteItems.length > 0) {
Array.from(autoCompleteItems).forEach((item) => {
if (element !== item && element !== inputElement) {
item.parentNode.removeChild(item);
}
});
}
};
document.addEventListener('click', (event) => hideList(event.target));
};
// this part binds the autocomplete with the HTML
window.addEventListener('load', function () {
const container = document.getElementById('autocomplete-container');
const inputElement = document.getElementById('autocomplete-input');
autocomplete(container, inputElement, data);
});
CSS
* { box-sizing: border-box; }
body {
font: 16px Arial;
}
.autocomplete {
display: inline-block;
position: relative;
width: 300px;
}
input {
border: 1px solid transparent;
background-color: #f1f1f1;
padding: 10px;
font-size: 16px;
}
input[type=text] {
background-color: #f1f1f1;
width: 100%;
}
input[type=submit] {
background-color: DodgerBlue;
color: #fff;
}
.autocomplete-items {
position: absolute;
border: 1px solid #d4d4d4;
border-bottom: none;
border-top: none;
z-index: 99;
top: 100%;
left: 0;
right: 0;
}
.autocomplete-items div {
padding: 10px;
cursor: pointer;
background-color: #fff;
border-bottom: 1px solid #d4d4d4;
}
.autocomplete-items div:hover {
background-color: #e9e9e9;
}
.autocomplete-active {
background-color: DodgerBlue !important;
color: #ffffff;
}
Based on W3School - How TO - Autocomplete
Live Version - Codesandbox
Try This Code
var searchTerms = ["OneDrive sync issue", "Abcde", "123456"];
var result = document.getElementById("result");
rul = document.createElement("ul");
result.appendChild(rul);
rul.classList.add("datalist");
for(var x = 0; x < searchTerms.length; x++ ){
rli = document.createElement("li");
rul.appendChild(rli);
rli.innerHTML = searchTerms[x];
rli.classList.add("d-none");
rli.addEventListener("click", function(){
document.getElementById("id_post").value = this.innerHTML;
this.classList.add("d-none");
});
}
function showResults(v){
var ListItems = rul.querySelectorAll("li");
for(var i = 0; i < ListItems.length; i++){
var c = ListItems[i].innerHTML.toLowerCase();
v = v.toLowerCase();
if(c.indexOf(v) > -1 && v !== ""){
ListItems[i].classList.remove("d-none");
}
else{
ListItems[i].classList.add("d-none");
}
}
}
.d-none{ display:none; }
.datalist li{ cursor:pointer; }
<input
type="text"
class="form-control"
placeholder="Explain in fewer words with the primary product key word (Eg: OneDrive sync issue, etc.)"
name="post"
required
id="id_post"
onKeyUp="showResults(this.value)">
<span
class="fas fa-asterisk"
style="font-size:12px;color:red;position:absolute; right:20px;top:12px;"
id="asterix"></span>
<div id="result"></div>
I am working from the color-swatch chart example in dc.js. My chart (source) renders the size of its given to render data length value. All I want is for it to change on overviewChart filter update.
So no selection:
On selection:
Yet I want is to be much smaller and changed according to overviewChart selection.
Here is my source code:
class dcChart {
constructor(parent, groupByKeyName, valueKeyName, group) {
this._group = null;
this._dimension = null;
this._groupByKeyIdx = groupByKeyName;
this._valueKeyName = valueKeyName;
this._root = d3.select(parent);
dc.registerChart(this, group);
}
cf(data) {
this._cf = data;
return this;
}
dimension(data) {
this._dimension = data;
return this;
}
group(data) {
this._group = data;
return this;
}
render() {
console.log("called once");
this.redraw();
}
redraw() {
this._root.html(this._dimension.hasCurrentFilter() + " " + this._group.all().length)
console.log(this._dimension.hasCurrentFilter())
console.log(this._group.all())
}
}
function loadStockData(stock, callback) {
d3.csv('https://bost.ocks.org/mike/cubism/intro/stocks/' + stock + '.csv').then(function(rows) {
rows = rows.map(function(d) {
return [d3.timeParse(d.Date), +d.Open];
}).filter(function(d) {
return d[1];
}).reverse();
var date = rows[0][0],
compare = rows[400][1],
value = rows[0][1],
values = [],
indices = [];
rows.forEach(function(d, i) {
values.push(value = (d[1] - compare) / compare);
indices.push(i);
});
callback({
'stock': stock,
'values': values,
'indices': indices
});
});
}
var promises = [];
['AAPL', 'GOOG', 'MSFT'].forEach(function(stock) {
promises.push(new Promise(function(resolve, reject) {
var r = loadStockData(stock, resolve);
}));
});
Promise.all(promises).then(function(stocks) {
console.log(stocks);
var data = [];
for (var i = 0; i < stocks.length; i++) {
for (var j = 0; j < stocks[i].indices.length; j++) {
data.push({
'idx': stocks[i].indices[j],
'name': stocks[i].stock,
'value': stocks[i].values[j]
})
}
}
var ndx, runDimension, runGroup, overviewRunDimension, overviewRunGroup;
ndx = crossfilter(data);
console.log(666);
console.log(ndx.groupAll());
runDimension = ndx.dimension(function(d) {
return [d.name, d.idx];
});
runGroup = runDimension.group().reduceSum(function(d) {
return d.value;
});
var runHCDimension = ndx.dimension(function(d) {
return [d.name, d.idx];
});
var runHCGroup = runHCDimension.group().reduceSum(function(d) {
return d.value;
});
var myChart = new dcChart("#test-hc", 1, 2);
myChart.cf(ndx)
.dimension(runHCDimension)
.group(runHCGroup);
var overviewChart = dc.seriesChart("#test-overview");
overviewChart
.width(768)
.height(100)
.chart(function(c) {
return dc.lineChart(c).curve(d3.curveCardinal);
})
.x(d3.scaleLinear().domain([0, 1]))
.brushOn(true)
.xAxisLabel("Values")
.clipPadding(10)
.dimension(runDimension)
.group(runGroup)
.seriesAccessor(function(d) {
return "Stock: " + d.key[0];
})
.keyAccessor(function(d) {
return d.key[1];
})
.valueAccessor(function(d) {
return d.value;
});
dc.renderAll();
});
body {
margin: 0;
padding: 0;
}
.horizon {
border-top: solid 1px #000;
border-bottom: solid 1px #000;
overflow: hidden;
position: relative;
}
.horizon + .horizon {
border-top: none;
}
.horizon canvas {
display: block;
image-rendering: pixelated;
}
.horizon .title,
.horizon .value {
bottom: 0;
line-height: 30px;
margin: 0 6px;
position: absolute;
font-family: sans-serif;
text-shadow: 0 1px 0 rgba(255,255,255,.5);
white-space: nowrap;
}
.horizon .title {
left: 0;
}
.horizon .value {
right: 0;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>dc.js - Custom Chart Example</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="//dc-js.github.io/dc.js/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="//unpkg.com/dc#4/dist/style/dc.css" />
<script src="//d3js.org/d3.v5.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/crossfilter2/1.4.4/crossfilter.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/dc/3.2.1/dc.min.js"></script>
<script src="//npmcdn.com/d3-horizon-chart/build/d3-horizon-chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.js"></script>
</head>
<body>
<div class="container">
<div id="test-overview"></div>
<br />
<div id="test-hc"></div>
</div>
</body>
</html>
So how one can get all the dimension data values filtered on another dc.js chart
update?
I am trying to get my cards to display 2 different boxes for the cards. If I hover just right with inspector I can see both cards are there, but I am having difficulty separating the two side by side. I am mostly trying to follow a tutorial but it has you do a lot of the work on your own, and I don't want to advance until I have this completely ready for the next task it gives me. Any help is greatly appreciated
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>
War Cards!
</title>
<style>
.icard
{
position: absolute;
padding: 10px;
height: 200px;
width: 150px;
border: 1px solid black;
border-radius: 15px;
background-color: white;
display: inline-block;
top: 0;
left: 0;
}
.hand
{
position: relative;
}
.players
{
float: left;
width: 49%;
min-height: 300px;
border: 1px solid black;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="start"></div>
<div id="message"></div>
<div id="board">
<div id="player1" class="players">
<div class="score"></div>
<div class="hand"></div>
</div>
<div id="player2">
<div class="score"></div>
<div class="hand"></div>
</div>
</div>
<div id="action">
<button id="btnBattle" type="button" class="btn">
Fight!
</button>
</div>
</div>
<script src="js/jquery-3.3.1.min.js">
</script>
<script>
$('document').ready(function() {
var suits = ["spades", "hearts", "clubs", "diams"];
var cardFace = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"];
var cards = [];
var players = [[], []];
var firstRun = true;
var gameOver = false;
var fightButton = document.querySelector("#btnBattle");
var p1 = document.querySelector('#player1 .hand');
var p2 = document.querySelector('#player2 .hand');
fightButton.addEventListener('click', battle);
function battle()
{
if (firstRun)
{
firstRun = false;
buildCards();
shuffleArray(cards);
dealCards(cards);
}
attack();
console.log('Works');
}
function attack()
{
if(!gameOver)
{
var card1 = players[0].shift();
var card2 = players[1].shift();
var pot = [card1, card2]
p1.innerHTML = showCard(card1, 0);
p2.innerHTML = showCard(card2, 0)
// Check Winners
// Update Scores
}
}
function showCard(c, p)
{
var move = p * 40;
var bgColor = (c.icon == 'H' || c.icon == 'D') ? 'red' : 'black';
var bCard = '<div class="icard" style="color:'+ bgColor +'">' + c.num + ' &' + c.suit + ';</div>';
console.log(c, move);
return bCard;
}
function buildCards()
{
cards = [];
for (s in suits)
{
var suitNew = suits[s][0].toUpperCase();
for(n in cardFace)
{
var card = {
suit:suits[s],
num:cardFace[n],
cardValue:parseInt(n) +2,
icon:suitNew
}
cards.push(card);
}
}
console.log(cards);
}
function dealCards(array)
{
for(var i = 0; i < array.length; i++)
{
// swaps between remainder 0 and 1, which signifies player[0 OR 1], and then pushes that onto parameter,(array), which
// is cards which is an array, at the index of for loop [i]
var m = i % 2;
players[m].push(array[i])
}
console.log(players)
}
//
// function dealCards(array)
// {
// for(var i = 0; i < array.length; i++)
// {
// if(i % 2 === 0 )
// {
// players[0].push(array[i]);
// }
// else
// {
// players[1].push(array[i]);
// }
//
// }
// console.log(players);
// }
//
function shuffleArray(array)
{
for(var x = array.length -1; x > 0; x--)
{
var ii = Math.floor(Math.random() * (x + 1))
var temp = array[x];
array[x] = array[ii];
array[ii] = temp;
}
console.log(cards);
return array;
}
});
</script>
</body>
</html>
I think you missed to add the players class to the player 2 element.
<div id="player2" class="players">
https://jsfiddle.net/zkw9s4an/
Add css to the player 2 div to move it margin left by the amount you need.
#player2
{
margin-left:10%;
}
Refer this.
I have four nodes, their ids are 1, 2, 3, 4; 1 and 2 are parent nodes and 3 is a child node. Edges go from 1 to 3, 2 to 3. Fourth node id 4 has no connections. Please anyone help me to save the node and connections correctly. Right now when I create a node, a json file gets saved. The file contains nodes, their coordinates and connections, but the latter are saved incorrectly.
body, select {
font: 14pt sans;
}
#mynetwork {
width: 800px;
height: 500px;
border: 1px solid green;
}
table.legend_table {
font-size: 11px;
border-width:1px;
border-color:#d3d3d3;
border-style:solid;
}
table.legend_table,td {
border-width:1px;
border-color:#d3d3d3;
border-style:solid;
padding: 2px;
}
div.table_content {
width:80px;
text-align:center;
}
div.table_description {
width:100px;
}
#operation {
font-size:28px;
}
#label {
font-size:14px;
}
#network-popUp {
display:none;
position:absolute;
top:50px;
right:150px;
z-index:9;
width:400px;
height:200px;
background-color: #f9f9f9;
border-style:solid;
border-width:3px;
border-color: #5394;
padding:10px;
text-align: center;
font-size: 11px;
}
<head>
<meta charset="utf-8">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.js">
</script>
<script type="text/javascript" src="http://visjs.org/dist/vis.js"> </script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.css">
<script type="text/javascript">
var nodes = null;
var edges = null;
var network = null;
// randomly create some nodes and edges
var data = {};
var seed = 2;
function setDefaultLocale() {
var defaultLocal = navigator.language;
var select = document.getElementById('locale');
select.selectedIndex = 0; // set fallback value
for (var i = 0, j = select.options.length; i < j; ++i) {
if (select.options[i].getAttribute('value') === defaultLocal) {
select.selectedIndex = i;
break;
}
}
}
function destroy() {
if (network !== null) {
network.destroy();
network = null;
}
}
function draw() {
destroy();
nodes = [];
edges = [];
// create a network
var container = document.getElementById('mynetwork');
var options = {
layout: {randomSeed:seed}, // just to make sure the layout is the same when the locale is changed
locale: document.getElementById('locale').value,
manipulation: {
addNode: function (data, callback) {
// filling in the popup DOM elements
document.getElementById('operation').innerHTML = "Add Node";
document.getElementById('node-id').value = data.id;
document.getElementById('node-label').value = data.label;
document.getElementById('saveButton').onclick = saveData.bind(this, data, callback);
document.getElementById('cancelButton').onclick = clearPopUp.bind();
document.getElementById('network-popUp').style.display = 'block';
},
editNode: function (data, callback) {
// filling in the popup DOM elements
document.getElementById('operation').innerHTML = "Edit Node";
document.getElementById('node-id').value = data.id;
document.getElementById('node-label').value = data.label;
document.getElementById('saveButton').onclick = saveData.bind(this, data, callback);
document.getElementById('cancelButton').onclick = cancelEdit.bind(this,callback);
document.getElementById('network-popUp').style.display = 'block';
},
addEdge: function (data, callback) {
if (data.from == data.to) {
var r = confirm("Do you want to connect the node to itself?");
if (r == true) {
callback(data);
}
}
else {
callback(data);
}
}
}
};
network = new vis.Network(container, data, options);
}
function clearPopUp() {
document.getElementById('saveButton').onclick = null;
document.getElementById('cancelButton').onclick = null;
document.getElementById('network-popUp').style.display = 'none';
}
function savedataandedge () {
var nodes = objectToArray(network.getPositions());
nodes.forEach(addConnections);
var exportValue = JSON.stringify(nodes, undefined, 2);
let dataStr = JSON.stringify(exportValue.replace(/\r?\n|\r?\"/g,''));
let dataUri = 'data:application/json,'+encodeURIComponent(dataStr);
let exportFileDefaultName = 'testingG.json';
let linkElement = document.createElement('a');
linkElement.setAttribute('href',dataUri);
linkElement.setAttribute('download',exportFileDefaultName);
linkElement.click();
}
function objectToArray(obj) {
return Object.keys(obj).map(function (key) {
obj[key].id = key;
return obj[key];
});
}
function addConnections(elem, index) {
elem.connections = network.getConnectedNodes(index);
}
function cancelEdit(callback) {
clearPopUp();
callback(null);
}
function saveData(data,callback) {
data.id = document.getElementById('node-id').value;
data.label = document.getElementById('node-label').value;
clearPopUp();
callback(data);
savedataandedge ();
}
function init() {
setDefaultLocale();
draw();
}
</script>
</head>
<body onload="init();">
<h2>Editing the nodes and edges (localized)</h2>
<p style="width: 700px; font-size:14px; text-align: justify;">
The localization is only relevant to the manipulation buttons.
</p>
<p>
<label for="locale">Select a locale:</label>
<select id="locale" onchange="draw();">
<option value="en">en</option>
<option value="de">de</option>
<option value="es">es</option>
<option value="it">it</option>
<option value="nl">nl</option>
<option value="pt-br">pt</option>
<option value="ru">ru</option>
</select>
</p>
<div id="network-popUp">
<span id="operation">node</span> <br>
<table style="margin:auto;"><tr>
<td>id</td><td><input id="node-id" value="new value" /></td>
</tr>
<tr>
<td>label</td><td><input id="node-label" value="new value" /></td>
</tr></table>
<input type="button" value="save" id="saveButton" />
<input type="button" value="cancel" id="cancelButton" />
</div>
<br />
<div id="mynetwork"></div>
</body>
</html>
Actually, this snippet is the vis.js's manupulation example with only few lines added.
When I create nodes and edges like these (node labeled "one" has id of 1 etc):
I get JSON file like this:
"[{ x: -255, y: -230, id: 1, connections: [] },
{ x: -69, y: -226, id: 2, connections: [ 3 ] },
{ x: -144, y: -108, id: 3, connections: [ 3 ] },
{ x: -6, y: -150, id: 4, connections: [ 1, 2 ] }]"
but should be (note the wrong connections):
"[{ x: -255, y: -230, id: 1, connections: [ 3 ] },
{ x: -69, y: -226, id: 2, connections: [ 3 ] },
{ x: -144, y: -108, id: 3, connections: [ 1, 2 ] },
{ x: -6, y: -150, id: 4, connections: [ ] }]"
Well, this is somewhat simple. The relevant bit is this:
function savedataandedge () {
var nodes = objectToArray(network.getPositions());
nodes.forEach(addConnections);
var exportValue = JSON.stringify(nodes, undefined, 2);
let dataStr = JSON.stringify(exportValue.replace(/\r?\n|\r?\"/g,''));
let dataUri = 'data:application/json,'+encodeURIComponent(dataStr);
let exportFileDefaultName = 'testingG.json';
let linkElement = document.createElement('a');
linkElement.setAttribute('href',dataUri);
linkElement.setAttribute('download',exportFileDefaultName);
linkElement.click();
}
and this:
function addConnections(elem, index) {
elem.connections = network.getConnectedNodes(index);
}
You are using nodes.forEach which applies your addConnections for each node and gives it arguments: elem, index where index is starts from 0, so its given value becomes 0, 1, 2, 3 which is not the id of the corresponding node and get your connections shifted. The whole approach of using indices is wrong, but can be easily fixed: just use actual ids:
function addConnections(node, index) {
node.connections = network.getConnectedNodes(node.id);
}
(I've tested this and it works as you expect)