I am currently working on making a grid of squares for a tile map. I have it set up so clicking on a tile changes its state to explored from unexplored. I am attempting to have it so that dragging with the mouse down will change the state of all underlying tiles, however I can't seem to get it to work.
I have tried using mousedown and mouseup events to set a down boolean value which I then check inside of a mouseover. I have tried going about this in several ways (i.e. the commented out code). The current code will work for clicking but I really want to be able to do a drag to change multiples feature.
var tableString;
var width = 35;
var height = 15;
var cells = [];
var localX;
var localY;
function cell(x, y, c) {
positionX = x;
positionY = y;
category = c;
}
function createMap() {
for (var i = 0; i < height; i++) {
var row = [];
for (var j = 0; j < width; j++) {
let c = new cell();
c.category = "unexplored";
c.positionX = j;
c.positionY = i;
row.push(c);
}
cells.push(row);
}
}
function drawMap() {
tableString = "<table draggable='false'>";
for (var i = 0; i < height; i++) {
tableString += "<tr draggable='false'>";
for (var j = 0; j < width; j++) {
tableString += '<td draggable="false" class="' + cells[i][j].category + '" data-row="' + j + '" data-column="' + i + '"></td>';
}
tableString += "</tr>";
}
tableString += "</table>";
$("#mainContainer").html(tableString);
console.log("drew it");
}
function updateCellCategory(x, y, c) {
cells[x][y].category = c;
drawMap();
}
$(document).ready(function() {
createMap();
drawMap();
// var down = false;
// $(document,"td").mousedown(function () {
// down = true;
// })
// $(document,"td").mouseup(function () {
// down = false;
// });
// $(document,"td").on('mouseover','td',function () {
// if (down) {
// console.log("hovering and holding");
// localX = $(this).attr("data-row");
// localY = $(this).attr("data-column");
// updateCellCategory(localY, localX, "explored");
// }
// });
});
// $(document).on('mousedown',"td, documen",(function () {
// down = true;
// console.log(down);
// }));
// $(document).on('mouseup',"*",(function () {
// down = false;
// console.log(down);
// }));
// $(document).on('mouseover','td',function () {
// if (down) {
// console.log("hovering and holding");
// localX = $(this).attr("data-row");
// localY = $(this).attr("data-column");
// updateCellCategory(localY, localX, "explored");
// }
// });
$("*").delegate('td', 'click', function() {
localX = $(this).attr("data-row");
localY = $(this).attr("data-column");
updateCellCategory(localY, localX, "explored");
});
html,
body {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px;
}
#mainContainer {
max-width: 100%;
max-height: 90%;
width: 100%;
height: 90%;
display: flex;
align-items: center;
justify-content: center;
}
td {
width: 25px;
height: 25px;
border: .05px solid black;
}
.explored {
background-color: lightblue;
}
.unexplored {
background-color: lightcoral;
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<div id="mainContainer">
</div>
</body>
</html>
The main issue I found when working on this is that some of the commented code works sometimes, but the second a drag event happens on a td the code breaks and the mouseup is not recognized causing the mouse cursur to continue affecting tiles even though the mouse was not held down.
OK. Using the click event is not what you want, since that involves pressing the mouse and releasing it.
Instead use, the mousemove, mousedown and mouseup events. Also, keep track of whether the mouse is down or not using a variable.
var tableString;
var width = 35;
var height = 15;
var cells = [];
var localX;
var localY;
var mouseDown = false;
function cell(x, y, c) {
positionX = x;
positionY = y;
category = c;
}
function createMap() {
for (var i = 0; i < height; i++) {
var row = [];
for (var j = 0; j < width; j++) {
let c = new cell();
c.category = "unexplored";
c.positionX = j;
c.positionY = i;
row.push(c);
}
cells.push(row);
}
}
function drawMap() {
tableString = "<table draggable='false'>";
for (var i = 0; i < height; i++) {
tableString += "<tr draggable='false'>";
for (var j = 0; j < width; j++) {
tableString += '<td draggable="false" class="' + cells[i][j].category + '" data-row="' + j + '" data-column="' + i + '"></td>';
}
tableString += "</tr>";
}
tableString += "</table>";
$("#mainContainer").html(tableString);
//console.log("drew it");
}
function updateCellCategory(x, y, c) {
cells[x][y].category = c;
drawMap();
}
$(document).ready(function() {
createMap();
drawMap();
});
$("*").on("mousedown", 'td', function()
{
mouseDown = true;
});
$(document).on("mouseup", function()
{
mouseDown = false;
});
$("*").on("mousemove", 'td', function()
{
if(!mouseDown)
return;
localX = $(this).attr("data-row");
localY = $(this).attr("data-column");
updateCellCategory(localY, localX, "explored");
});
html,
body {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px;
}
#mainContainer {
max-width: 100%;
max-height: 90%;
width: 100%;
height: 90%;
display: flex;
align-items: center;
justify-content: center;
}
td {
width: 25px;
height: 25px;
border: .05px solid black;
}
.explored {
background-color: lightblue;
}
.unexplored {
background-color: lightcoral;
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<div id="mainContainer">
</div>
</body>
</html>
You can check whether or not the mouse is down using the event parameter of the event handler. Look at the last few lines of the snippet.
var tableString;
var width = 35;
var height = 15;
var cells = [];
var localX;
var localY;
function cell(x, y, c) {
positionX = x;
positionY = y;
category = c;
}
function createMap() {
for (var i = 0; i < height; i++) {
var row = [];
for (var j = 0; j < width; j++) {
let c = new cell();
c.category = "unexplored";
c.positionX = j;
c.positionY = i;
row.push(c);
}
cells.push(row);
}
}
function drawMap() {
tableString = "<table draggable='false'>";
for (var i = 0; i < height; i++) {
tableString += "<tr draggable='false'>";
for (var j = 0; j < width; j++) {
tableString += '<td draggable="false" class="' + cells[i][j].category + '" data-row="' + j + '" data-column="' + i + '"></td>';
}
tableString += "</tr>";
}
tableString += "</table>";
$("#mainContainer").html(tableString);
console.log("drew it");
}
function updateCellCategory(x, y, c) {
cells[x][y].category = c;
drawMap();
}
$(document).ready(function() {
createMap();
drawMap();
// var down = false;
// $(document,"td").mousedown(function () {
// down = true;
// })
// $(document,"td").mouseup(function () {
// down = false;
// });
// $(document,"td").on('mouseover','td',function () {
// if (down) {
// console.log("hovering and holding");
// localX = $(this).attr("data-row");
// localY = $(this).attr("data-column");
// updateCellCategory(localY, localX, "explored");
// }
// });
});
// $(document).on('mousedown',"td, documen",(function () {
// down = true;
// console.log(down);
// }));
// $(document).on('mouseup',"*",(function () {
// down = false;
// console.log(down);
// }));
// $(document).on('mouseover','td',function () {
// if (down) {
// console.log("hovering and holding");
// localX = $(this).attr("data-row");
// localY = $(this).attr("data-column");
// updateCellCategory(localY, localX, "explored");
// }
// });
$("*").delegate('td', 'mousedown', function() {
localX = $(this).attr("data-row");
localY = $(this).attr("data-column");
updateCellCategory(localY, localX, "explored");
});
$("*").delegate('td', 'mouseenter', function(event) {
if (event.buttons) {
localX = $(this).attr("data-row");
localY = $(this).attr("data-column");
updateCellCategory(localY, localX, "explored");
}
event.stopPropagation();
});
html,
body {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px;
}
#mainContainer {
max-width: 100%;
max-height: 90%;
width: 100%;
height: 90%;
display: flex;
align-items: center;
justify-content: center;
}
td {
width: 25px;
height: 25px;
border: .05px solid black;
}
.explored {
background-color: lightblue;
}
.unexplored {
background-color: lightcoral;
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<div id="mainContainer">
</div>
</body>
</html>
Related
Recently I've been looking at different projects and trying to modify them to try and understand the JS code much better. Recently I came across this lotto game from code pen. So I thought to try to make it to a game where you had coins as lives, then you get some stars based on how many numbers you got right.
The thing that I am struggling at is trying to loop the code on the click of a button. Currently the code is restarting the game by recalling its own link, in this case I just used my index.html as replacement for the href just to work on it for now. I want to change this because it doesn't let me consume all my coins (lives) without refreshing the page.
I tried putting everything in a function instead of calling it through the DOM being loaded. I then called that function when the dom has loaded, then after each draw I tried calling it again by using another button but it doesn't work. Tried changing the href to the function but that doesn't work as well. I also tried a few other things but I cannot make a work around this. Any help is appreciated! I'm still learning Javascript, so please pardon my question.
The code is not owned by me, I am just playing around with it, here's the original codepen link. https://codepen.io/EwaTrojanowskaGrela/pen/KmJMWb
// Declaration of scores and lives
var stars = 0;
var coins = 5;
// End of comment
// For redeclaration in innerHTML
var starsEarned;
// End of comment
// For displaying current score
document.getElementById("star-count").innerHTML = stars;
document.getElementById("coin-count").innerHTML = coins;
// End of comment
document.addEventListener("DOMContentLoaded", function(e){
var body = document.querySelector("body");
var section = document.querySelector("section");
var articleLotto = document.querySelector(".lotto");
var articleBalls = document.querySelector(".balls");
var numbers = [];
var balls = document.getElementsByClassName("ball");
var drawnNums = [];
var chosenByMachine = [];
function createNumberBoard(number){
console.log("I work");
var board = document.createElement("div");
board.classList.add("board");
articleLotto.appendChild(board);
for( var i = 0; i<number; i ++){
var boardEl = document.createElement("button");
boardEl.classList.add("boardEl");
board.appendChild(boardEl);
}
var boardEls = document.getElementsByClassName("boardEl");
for( var i =0; i<boardEls.length; i++){
boardEls[i].setAttribute("data-number", i+1);
var dataNumber = boardEls[i].getAttribute("data-number");
var number = parseInt(dataNumber, 10);
numbers.push(number);
boardEls[i].textContent = number;
}
}
createNumberBoard(49);
var board = document.querySelector(".board");
var boardEls = document.querySelectorAll(".boardEl");
function drawNumbers(){
//boardEls.forEach(boardEl => boardEl.addEventListener("click", selectNums));
for (var i = 0; i<boardEls.length; i++){
boardEls[i].addEventListener("click", selectNums);
}
function selectNums(){
var number = parseInt(this.dataset.number, 10);
if(this.hasAttribute("data-number")){
drawnNums.push(number);
this.removeAttribute("data-number");
this.classList.add("crossedOut");
}
if(drawnNums.length=== 6){
//boardEls.forEach( boardEl => boardEl.removeAttribute("data-number"));
//boardEls.forEach(boardEl => boardEl.addEventListener("click", makeAlert));
for ( var i = 0; i<boardEls.length; i++){
boardEls[i].removeAttribute("data-number");
boardEls[i].addEventListener("click", makeAlert);
}
var startDraw = document.querySelector(".startDraw");
if(startDraw === null){ // you have to prevent creating the button if it is already there!
createButtonForMachineDraw();
} else {
return;
}
}
}
return drawnNums;
}
drawNumbers();
function makeAlert() {
var alertBox = document.createElement("div");
board.appendChild(alertBox);
alertBox.classList.add("alertBox");
alertBox.textContent = "You can only choose 6!";
setTimeout(function() {
alertBox.parentNode.removeChild(alertBox);
}, 1500);
}
function machineDraw(){
for( var i =0; i<6; i++){
var idx = Math.floor(Math.random() * numbers.length)
chosenByMachine.push(numbers[idx]);
/*a very important line of code which prevents machine from drawing the same number again
*/
numbers.splice(idx,1);
console.log(numbers)
/*this line of code allows to check if numbers are taken out*/
}
var btnToRemove = document.querySelector(".startDraw");
btnToRemove.classList.add("invisible");
/* why not remove it entirely? because it might then be accidentally created if for some reason you happen to try to click on board!!! and you may do that*/
return chosenByMachine;
}
//machineDraw();
function createButtonForMachineDraw(){
var startDraw = document.createElement("button");
startDraw.classList.add("startDraw");
section.appendChild(startDraw);
startDraw.textContent ="Release the balls";
startDraw.addEventListener("click", machineDraw);
startDraw.addEventListener("click", compareArrays);
}
function compareArrays(){
for( var i =0; i<balls.length; i++) {
balls[i].textContent = chosenByMachine[i];
(function() {
var j = i;
var f = function(){
balls[j].classList.remove("invisible");
balls[j].classList.add("ball-align");
}
setTimeout(f, 1000*(j+1));
})();
}
var common =[];
var arr1 = chosenByMachine;
var arr2 = drawnNums;
for(var i = 0; i<arr1.length; i++){
for(var j= 0; j<arr2.length; j++){
if(arr1[i]===arr2[j]){
common.push(arr1[i]);
}
}
}
console.log(arr1, arr2, common); /* you can monitor your arrays in console*/
function generateResult(){
// Deduction of coins once draw started
coins = coins - 1;
// End of comment
var resultsBoard = document.createElement("article");
section.appendChild(resultsBoard);
var paragraph = document.createElement("p");
resultsBoard.appendChild(paragraph);
resultsBoard.classList.add("resultsBoard");
resultsBoard.classList.add("invisible");
if(common.length === 0){
paragraph.textContent ="Oh no! You got " + common.length + " Star!";
starsEarned = stars + common.length;
return starsEarned;
} else if(common.length === 1){
paragraph.textContent ="You got " + common.length + " Star!";
starsEarned = stars + common.length;
return starsEarned;
} else if(common.length === 2){
paragraph.textContent ="You got " + common.length + " Stars!";
starsEarned = stars + common.length;
return starsEarned;
} else if(common.length === 3) {
paragraph.textContent ="You got " + common.length + " Stars!";
starsEarned = stars + common.length;
return starsEarned;
} else if(common.length === 4){
paragraph.textContent ="You got " + common.length + " Stars!";
starsEarned = stars + common.length;
return ststarsEarnedars;
} else if(common.length === 5){
paragraph.textContent ="You got " + common.length + " Stars!";
starsEarned = stars + common.length;
return starsEarned;
}
else if(common.length===6){
paragraph.textContent ="A true winner! You got " + common.length + " Stars!";
stars = stars + common.length;
return starsEarned;
}
// Returning of new coins
return coins;
// End of comment
}
setTimeout(function() {
makeComebackBtn();
document.querySelector(".resultsBoard").classList.remove("invisible"); //well, you cannot acces this outside the code
// Displaying of new scores
stars = stars + starsEarned;
document.getElementById("coin-count").innerHTML = coins;
document.getElementById("star-count").innerHTML = stars;
// End of comment
}, 8000);
generateResult();
}
function makeComebackBtn(){
var comebackBtn = document.createElement("a");
comebackBtn.classList.add("comebackBtn");
section.appendChild(comebackBtn);
comebackBtn.textContent ="Go again"
comebackBtn.setAttribute("href", "index.html");
}
})
body {
padding: 0 15%;
}
.game-container {
height: auto;
background-color:#424B54;
font-family: "Allerta", sans-serif;
margin: 0;
max-width: 425px;
height: 750px;
/* padding: 0 2%; */
box-sizing: border-box;
}
section {
margin: 0 auto;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: auto;
padding-bottom: 15px;
}
h1,
p {
width: 100%;
text-align: center;
color: #FF6663;
text-shadow: 3px 3px #A20202;
font-family: "Bungee", cursive;
}
h1 {
font-size: 35px;
margin: 0;
}
p {
font-size: 30px;
margin: 0;
}
h3 {
color: #FF6663;
text-align: center;
text-shadow: 2px 2px #A20202;
font-size: 25px;
margin-bottom: 5px;
}
article {
height: 90%;
width: 250px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
margin-bottom: 1rem;
}
.scores {
width: 100%;
}
.coins,
.stars{
display: flex;
align-items: center;
gap: .5rem;
}
.score-icons {
color: #F6BD60;
font-size: 3rem;
}
.scores span {
color: white;
}
#star-count,
#coin-count{
font-size: 1.5 rem;
}
.invisible {
display: none;
}
.ball-align {
display: flex;
justify-content: center;
align-items: center;
}
.board {
position: relative;
background-color: #FF6663;
width: 13.125rem;
height: 13.125rem;
border: 1px solid #FF6663;
display: flex;
flex-wrap: wrap;
justify-content: space-around;
align-items: center;
}
.boardEl {
background-color: #E8F7EE;
width: 28px;
height: 28px;
color: #000000;
text-align: center;
font-size: 15px;
border: none;
}
.crossedOut {
background-color: #424B54;
color: #F7EDE2;
}
.startDraw {
background: #FF6663;
border: none;
font-size: 1.3rem;
font-weight: bolder;
color: #ffffff;
padding: 0.5rem 1rem;
margin: 0 auto;
border-radius: .5rem;
padding: .5rem 1rem;
}
.ball {
width: 2rem;
height: 2rem;
border-radius: 50%;
line-height: 2;
color: #efefef;
font-weight: bold;
text-align: center;
}
.ball:nth-of-type(2n) {
align-self: flex-end;
}
.ball:nth-of-type(2n + 1) {
align-self: flex-start;
}
.ball:first-of-type {
background-color: gold;
border: 1px solid #ccac00;
}
.ball:nth-of-type(2) {
background-color: hotpink;
border: 1px solid #ff369b;
}
.ball:nth-of-type(3) {
background-color: teal;
border: 1px solid #004d4d;
}
.ball:nth-of-type(4) {
background-color: #009900;
border: 1px solid #006600;
}
.ball:nth-of-type(5) {
background-color: #339999;
border: 1px solid #267373;
}
.ball:last-of-type {
background-color: #ff6633;
border: 1px solid #ff4000;
}
#ballContainer {
background-color: inherit;
border-bottom: none;
display: flex;
align-items: center;
gap: 0.1rem;
}
.resultsBoard {
margin-top: .5rem;
text-align: center;
width: 100%;
}
.resultsBoard p {
color: #F6BD60;
font-size: 2rem;
font-family: "Allerta", sans-serif;
text-shadow: none;
}
.comebackBtn {
line-height: 2;
margin-top: 2rem;
font-size: 1.3rem;
text-align: center;
background-color: #FF6663;
text-decoration: none;
color: #ffffff;
padding: .3rem 1rem;
border-radius: .3rem;
text-transform: uppercase;
}
.alertBox {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 3;
color: #ffffff;
background-color: #FF6663;
text-align: center;
line-height: 210px;
}
<!DOCTYPE html>
<html lang="eng-ENG">
<head>
<meta charset="UTF-8">
<title>lotto</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Allerta|Bungee" rel="stylesheet">
<link href='https://unpkg.com/boxicons#2.1.2/css/boxicons.min.css' rel='stylesheet'>
</head>
<body>
<main>
<div class="game-container">
<section>
<h1>Lottery</h1>
<div class="scores">
<div class="coins">
<i class='score-icons bx bxs-star'></i><span id="star-count"></span>
</div>
<div class="stars">
<i class='score-icons bx bx-coin'></i><span id="coin-count"></span>
</div>
</div>
<article class="lotto">
<h3>Pick 6 numbers:</h3>
</article>
<article class="balls">
<div id="ballContainer">
<div class="ball invisible"></div>
<div class="ball invisible"></div>
<div class="ball invisible"></div>
<div class="ball invisible"></div>
<div class="ball invisible"></div>
<div class="ball invisible"></div>
</div>
</article>
</section>
</div>
</main>
<script type="text/javascript" src="index.js"></script>
<!--<script type="text/javascript" src="js/app2.js"></script>-->
</body>
</html>
[UPDATED]
I've tried and modified the js script code and no need to save values in local storage. And in addition, no need to refresh page to reload game state. I implemented in JSFiddle here
var stars = 0;
var coins = 5;
var starsEarned = 0;
// For displaying current score
document.getElementById("star-count").innerHTML = stars;
document.getElementById("coin-count").innerHTML = coins;
document.addEventListener("DOMContentLoaded", function(e){
var body = document.querySelector("body");
var section = document.querySelector("section");
var articleLotto = document.querySelector(".lotto");
var articleBalls = document.querySelector(".balls");
var numbers = [];
var balls = document.getElementsByClassName("ball");
var drawnNums = [];
var chosenByMachine = [];
var board;
var boardEls;
function createNumberBoard(number){
console.log("I work");
numbers = [];
drawnNums = [];
chosenByMachine = [];
var board = document.createElement("div");
board.classList.add("board");
articleLotto.appendChild(board);
for( var i = 0; i<number; i ++){
var boardEl = document.createElement("button");
boardEl.classList.add("boardEl");
board.appendChild(boardEl);
}
var boardEls = document.getElementsByClassName("boardEl");
for( var i =0; i<boardEls.length; i++){
boardEls[i].setAttribute("data-number", i+1);
var dataNumber = boardEls[i].getAttribute("data-number");
var number = parseInt(dataNumber, 10);
numbers.push(number);
boardEls[i].textContent = number;
}
}
createNumberBoard(49);
board = document.querySelector(".board");
boardEls = document.querySelectorAll(".boardEl");
function drawNumbers(){
//boardEls.forEach(boardEl => boardEl.addEventListener("click", selectNums));
for (var i = 0; i<boardEls.length; i++){
boardEls[i].addEventListener("click", selectNums);
}
function selectNums(){
var number = parseInt(this.dataset.number, 10);
if(this.hasAttribute("data-number")){
drawnNums.push(number);
this.removeAttribute("data-number");
this.classList.add("crossedOut");
}
if(drawnNums.length=== 6){
//boardEls.forEach( boardEl => boardEl.removeAttribute("data-number"));
//boardEls.forEach(boardEl => boardEl.addEventListener("click", makeAlert));
for ( var i = 0; i<boardEls.length; i++){
boardEls[i].removeAttribute("data-number");
boardEls[i].addEventListener("click", makeAlert);
}
var startDraw = document.querySelector(".startDraw");
if(startDraw === null){ // you have to prevent creating the button if it is already there!
createButtonForMachineDraw();
} else {
return;
}
}
}
return drawnNums;
}
drawNumbers();
function makeAlert() {
var alertBox = document.createElement("div");
board.appendChild(alertBox);
alertBox.classList.add("alertBox");
alertBox.textContent = "You can only choose 6!";
setTimeout(function() {
alertBox.parentNode.removeChild(alertBox);
}, 1500);
}
function machineDraw(){
for( var i =0; i<6; i++){
var idx = Math.floor(Math.random() * numbers.length)
chosenByMachine.push(numbers[idx]);
/*a very important line of code which prevents machine from drawing the same number again
*/
numbers.splice(idx,1);
/* console.log(numbers) */
/*this line of code allows to check if numbers are taken out*/
}
var btnToRemove = document.querySelector(".startDraw");
btnToRemove.classList.add("invisible");
/* why not remove it entirely? because it might then be accidentally created if for some reason you happen to try to click on board!!! and you may do that*/
return chosenByMachine;
}
//machineDraw();
function createButtonForMachineDraw(){
var startDraw = document.createElement("button");
startDraw.classList.add("startDraw");
section.appendChild(startDraw);
startDraw.textContent ="Release the balls";
startDraw.addEventListener("click", machineDraw);
startDraw.addEventListener("click", compareArrays);
}
function compareArrays(){
for( var i =0; i<balls.length; i++) {
balls[i].textContent = chosenByMachine[i];
(function() {
var j = i;
var f = function(){
balls[j].classList.remove("invisible");
balls[j].classList.add("ball-align");
}
setTimeout(f, 1000*(j+1));
})();
}
var common =[];
var arr1 = chosenByMachine;
var arr2 = drawnNums;
for(var i = 0; i<arr1.length; i++){
for(var j= 0; j<arr2.length; j++){
if(arr1[i]===arr2[j]){
common.push(arr1[i]);
}
}
}
/* console.log(arr1, arr2, common) */; /* you can monitor your arrays in console*/
function generateResult(){
// Deduction of coins once draw started
coins = coins - 1;
// End of comment
var resultsBoard = document.createElement("article");
section.appendChild(resultsBoard);
var paragraph = document.createElement("p");
resultsBoard.appendChild(paragraph);
resultsBoard.classList.add("resultsBoard");
resultsBoard.classList.add("invisible");
if(common.length === 0){
paragraph.textContent ="Oh no! You got " + common.length + " Star!";
starsEarned = stars + common.length;
return starsEarned;
} else if(common.length === 1){
paragraph.textContent ="You got " + common.length + " Star!";
starsEarned = stars + common.length;
return starsEarned;
} else if(common.length === 2){
paragraph.textContent ="You got " + common.length + " Stars!";
starsEarned = stars + common.length;
return starsEarned;
} else if(common.length === 3) {
paragraph.textContent ="You got " + common.length + " Stars!";
starsEarned = stars + common.length;
return starsEarned;
} else if(common.length === 4){
paragraph.textContent ="You got " + common.length + " Stars!";
starsEarned = stars + common.length;
return ststarsEarnedars;
} else if(common.length === 5){
paragraph.textContent ="You got " + common.length + " Stars!";
starsEarned = stars + common.length;
return starsEarned;
}
else if(common.length===6){
paragraph.textContent ="A true winner! You got " + common.length + " Stars!";
stars = stars + common.length;
return starsEarned;
}
// Returning of new coins
return coins;
// End of comment
}
setTimeout(function() {
makeComebackBtn();
document.querySelector(".resultsBoard").classList.remove("invisible"); //well, you cannot acces this outside the code
// Displaying of new scores
stars = starsEarned;
document.getElementById("coin-count").innerHTML = coins;
document.getElementById("star-count").innerHTML = stars;
// End of comment
}, 8000);
generateResult();
}
function makeComebackBtn(){
var comebackBtn = document.createElement("a");
comebackBtn.classList.add("comebackBtn");
section.appendChild(comebackBtn);
comebackBtn.textContent ="Go again";
if (coins === 0) {
comebackBtn.addEventListener("click", function () {
alert("You ran out of coins");
});
} else {
comebackBtn.addEventListener("click", function () {
const board_ = document.querySelector(".board");
board_.parentNode.removeChild(board_);
const startDraw_ = document.querySelector(".startDraw");
startDraw_.parentNode.removeChild(startDraw_);
for( let i=0; i<balls.length; i++) {
balls[i].classList.add("invisible");
balls[i].classList.remove("ball-align");
}
const resultsBoard_ = document.querySelector(".resultsBoard");
resultsBoard_.parentNode.removeChild(resultsBoard_);
createNumberBoard(49);
board = document.querySelector(".board");
boardEls = document.querySelectorAll(".boardEl");
drawNumbers();
const comebackBtn_ = document.querySelector(".comebackBtn");
comebackBtn_.parentNode.removeChild(comebackBtn_);
});
}
}
})
You need to save the values of stars and coins to localStorage using localStorage.setItem("stars", stars) or sessionStorage and get the values again at beginning of each turn.
Also initialize value of variable starsEarned = 0 and check condition of number of coins when reload the page. If run out of coins, alert player.
You can see following code I modified from your
// Declaration of scores and lives
var stars = Number(localStorage.getItem("stars")) || 0;
var coins = Number(localStorage.getItem("coins")) || 5;
// End of comment
// For redeclaration in innerHTML
var starsEarned = 0;
// End of comment
// For displaying current score
document.getElementById("star-count").innerHTML = stars;
document.getElementById("coin-count").innerHTML = coins;
// End of comment
document.addEventListener("DOMContentLoaded", function(e){
var body = document.querySelector("body");
var section = document.querySelector("section");
var articleLotto = document.querySelector(".lotto");
var articleBalls = document.querySelector(".balls");
var numbers = [];
var balls = document.getElementsByClassName("ball");
var drawnNums = [];
var chosenByMachine = [];
function createNumberBoard(number){
console.log("I work");
var board = document.createElement("div");
board.classList.add("board");
articleLotto.appendChild(board);
for( var i = 0; i<number; i ++){
var boardEl = document.createElement("button");
boardEl.classList.add("boardEl");
board.appendChild(boardEl);
}
var boardEls = document.getElementsByClassName("boardEl");
for( var i =0; i<boardEls.length; i++){
boardEls[i].setAttribute("data-number", i+1);
var dataNumber = boardEls[i].getAttribute("data-number");
var number = parseInt(dataNumber, 10);
numbers.push(number);
boardEls[i].textContent = number;
}
}
createNumberBoard(49);
var board = document.querySelector(".board");
var boardEls = document.querySelectorAll(".boardEl");
function drawNumbers(){
//boardEls.forEach(boardEl => boardEl.addEventListener("click", selectNums));
for (var i = 0; i<boardEls.length; i++){
boardEls[i].addEventListener("click", selectNums);
}
function selectNums(){
var number = parseInt(this.dataset.number, 10);
if(this.hasAttribute("data-number")){
drawnNums.push(number);
this.removeAttribute("data-number");
this.classList.add("crossedOut");
}
if(drawnNums.length=== 6){
//boardEls.forEach( boardEl => boardEl.removeAttribute("data-number"));
//boardEls.forEach(boardEl => boardEl.addEventListener("click", makeAlert));
for ( var i = 0; i<boardEls.length; i++){
boardEls[i].removeAttribute("data-number");
boardEls[i].addEventListener("click", makeAlert);
}
var startDraw = document.querySelector(".startDraw");
if(startDraw === null){ // you have to prevent creating the button if it is already there!
createButtonForMachineDraw();
} else {
return;
}
}
}
return drawnNums;
}
drawNumbers();
function makeAlert() {
var alertBox = document.createElement("div");
board.appendChild(alertBox);
alertBox.classList.add("alertBox");
alertBox.textContent = "You can only choose 6!";
setTimeout(function() {
alertBox.parentNode.removeChild(alertBox);
}, 1500);
}
function machineDraw(){
for( var i =0; i<6; i++){
var idx = Math.floor(Math.random() * numbers.length)
chosenByMachine.push(numbers[idx]);
/*a very important line of code which prevents machine from drawing the same number again
*/
numbers.splice(idx,1);
/* console.log(numbers) */
/*this line of code allows to check if numbers are taken out*/
}
var btnToRemove = document.querySelector(".startDraw");
btnToRemove.classList.add("invisible");
/* why not remove it entirely? because it might then be accidentally created if for some reason you happen to try to click on board!!! and you may do that*/
return chosenByMachine;
}
//machineDraw();
function createButtonForMachineDraw(){
var startDraw = document.createElement("button");
startDraw.classList.add("startDraw");
section.appendChild(startDraw);
startDraw.textContent ="Release the balls";
startDraw.addEventListener("click", machineDraw);
startDraw.addEventListener("click", compareArrays);
}
function compareArrays(){
for( var i =0; i<balls.length; i++) {
balls[i].textContent = chosenByMachine[i];
(function() {
var j = i;
var f = function(){
balls[j].classList.remove("invisible");
balls[j].classList.add("ball-align");
}
setTimeout(f, 1000*(j+1));
})();
}
var common =[];
var arr1 = chosenByMachine;
var arr2 = drawnNums;
for(var i = 0; i<arr1.length; i++){
for(var j= 0; j<arr2.length; j++){
if(arr1[i]===arr2[j]){
common.push(arr1[i]);
}
}
}
/* console.log(arr1, arr2, common) */; /* you can monitor your arrays in console*/
function generateResult(){
// Deduction of coins once draw started
coins = coins - 1;
// End of comment
var resultsBoard = document.createElement("article");
section.appendChild(resultsBoard);
var paragraph = document.createElement("p");
resultsBoard.appendChild(paragraph);
resultsBoard.classList.add("resultsBoard");
resultsBoard.classList.add("invisible");
if(common.length === 0){
paragraph.textContent ="Oh no! You got " + common.length + " Star!";
starsEarned = stars + common.length;
return starsEarned;
} else if(common.length === 1){
paragraph.textContent ="You got " + common.length + " Star!";
starsEarned = stars + common.length;
return starsEarned;
} else if(common.length === 2){
paragraph.textContent ="You got " + common.length + " Stars!";
starsEarned = stars + common.length;
return starsEarned;
} else if(common.length === 3) {
paragraph.textContent ="You got " + common.length + " Stars!";
starsEarned = stars + common.length;
return starsEarned;
} else if(common.length === 4){
paragraph.textContent ="You got " + common.length + " Stars!";
starsEarned = stars + common.length;
return ststarsEarnedars;
} else if(common.length === 5){
paragraph.textContent ="You got " + common.length + " Stars!";
starsEarned = stars + common.length;
return starsEarned;
}
else if(common.length===6){
paragraph.textContent ="A true winner! You got " + common.length + " Stars!";
stars = stars + common.length;
return starsEarned;
}
// Returning of new coins
return coins;
// End of comment
}
setTimeout(function() {
makeComebackBtn();
document.querySelector(".resultsBoard").classList.remove("invisible"); //well, you cannot acces this outside the code
// Displaying of new scores
stars = starsEarned;
document.getElementById("coin-count").innerHTML = coins;
document.getElementById("star-count").innerHTML = stars;
localStorage.setItem("stars", stars);
localStorage.setItem("coins", coins);
// End of comment
}, 8000);
generateResult();
}
function makeComebackBtn(){
var comebackBtn = document.createElement("a");
comebackBtn.classList.add("comebackBtn");
section.appendChild(comebackBtn);
comebackBtn.textContent ="Go again";
if (coins === 0) {
comebackBtn.setAttribute("onClick", "alert('You ran out of coins')");
} else {
comebackBtn.setAttribute("onClick", "window.location.reload();");
}
}
})
<!doctype html>
<html>
<head>
<title>Get home</title>
<style>
table {
border-collapse: collapse;
}
td {
border: solid 1px #888;
width: 30px;
height: 30px;
font-family: sans-serif;
font-size: calc(30px/4.0 + 1px);
text-align: center;
}
.cell0 {
background: #88ff99;
}
.cell1 {
background: #116615;
}
.player {
background: #e11;
}
.home {
background: white;
}
.status {
font-size: 15pt;
font-family: Arial;
}
</style>
<script>
// Will be initialised to a 2-dimensional array
var gameBoard = [];
// Size of game
var size = 10;
// Current fuel and supply
var fuel = 20;
var supply = 0;
// Current position of player (start in the bottom-right)
var positionX = size - 1;
var positionY = size - 1;
// Whether we are playing the game
var playing = true;
// Use this function to make a move where x and y represent the direction of
// a move, e.g.
// move(-1, 0) means going left
// move(1, 0) means going right
// move(0, -1) means going up
// move(0, 1) means going down
function move(x, y) {
//
if (positionX + x < size && positionX + x >= 0 &&
positionY + y < size && positionY + y >= 0) {
// Move is within the board
}
}
// Use this function to update the status
function updateStatus() {
document.getElementById("fuel").innerHTML = fuel;
document.getElementById("store").innerHTML = supply;
}
function setup() {
// Set the gameboard to be empty
gameBoard = [];
var board = document.getElementById("board");
for (var i = 0; i < size; i++) {
// Create a new row of the game
var htmlRow = document.createElement("tr");
board.appendChild(htmlRow);
var row = []
for (var j = 0; j < size; j++) {
// Chose a random type of cell
var type = Math.round(Math.random());
var cell = document.createElement("td");
cell.className = "cell" + type;
// Add the cell to the row
htmlRow.appendChild(cell);
row.push(cell);
}
gameBoard.push(row);
}
// Setup the player
gameBoard[size-1][size-1].className = "player";
// Setup the home
gameBoard[0][0].className = "home";
gameBoard[0][0].innerHTML = "HOME";
// Register the listener and update the state
updateStatus();
document.body.addEventListener("keydown", keyEvent);
}
</script>
</head>
<body onLoad="setup();">
<div class="status">Fuel: <span id="fuel"></div>
<div class="status">Store: <span id="store"></div>
<table id="board"></table>
<div class="status" id="outcome"></div>
</body>
</html>
I'm creating a simple game on HTML, and I can't think of how to get the move function to work, while it automatically updates the game and the map, is anyone able to help. I'm new to coding and I genuinely cant fathom what code to put in to make the move function work, whether it be using arrow keys or creating buttons to make the entity move.
Without making too many changes to the way you have things set up, I added a function that will add the "player" class to elements based on "wsad" or arrow key presses.
<!doctype html>
<html>
<head>
<title>Get home</title>
<style>
table {
border-collapse: collapse;
}
td {
border: solid 1px #888;
width: 30px;
height: 30px;
font-family: sans-serif;
font-size: calc(30px/4.0 + 1px);
text-align: center;
}
.cell0 {
background: #88ff99;
}
.cell1 {
background: #116615;
}
.player {
background: #e11;
}
.home {
background: white;
}
.status {
font-size: 15pt;
font-family: Arial;
}
</style>
<script>
// Will be initialised to a 2-dimensional array
var gameBoard = [];
// Size of game
var size = 10;
// Current fuel and supply
var fuel = 20;
var supply = 0;
// Current position of player (start in the bottom-right)
var positionX = size - 1;
var positionY = size - 1;
// Whether we are playing the game
var playing = true;
function move(direction) {
let x = positionX;
let y = positionY;
switch (direction) {
case "left":
x--;
break;
case "right":
x++;
break;
case "up":
y--;
break;
case "down":
y++;
break;
}
const validMove =
x < size &&
x >= 0 &&
y < size &&
y >= 0;
if (!validMove) return console.error(
"What are you trying to do?" + "\n" +
"Break the implied rules of a game?" + "\n" +
"I expect more from you" + "\n" +
"That's a wall you dummy!"
);
positionX = x;
positionY = y;
gameBoard[y][x].classList.add("player");
}
// Use this function to update the status
function updateStatus() {
document.getElementById("fuel").innerText = fuel;
document.getElementById("store").innerText = supply;
}
function keyEvent(e) {
const keyMoveDict = {
"ArrowLeft": "left",
"ArrowRight": "right",
"ArrowUp": "up",
"ArrowDown": "down",
"a": "left",
"d": "right",
"w": "up",
"s": "down",
}
const movement = keyMoveDict[e.key];
if (movement) move(movement);
}
function setup() {
// Set the gameboard to be empty
gameBoard = [];
var board = document.getElementById("board");
for (var i = 0; i < size; i++) {
// Create a new row of the game
var htmlRow = document.createElement("tr");
board.appendChild(htmlRow);
var row = []
for (var j = 0; j < size; j++) {
// Chose a random type of cell
var type = Math.round(Math.random());
var cell = document.createElement("td");
cell.className = "cell" + type;
// Add the cell to the row
htmlRow.appendChild(cell);
row.push(cell);
}
gameBoard.push(row);
}
// Setup the player
gameBoard[size-1][size-1].className = "player";
// Setup the home
gameBoard[0][0].className = "home";
gameBoard[0][0].innerHTML = "HOME";
// Register the listener and update the state
updateStatus();
document.body.addEventListener("keydown", keyEvent);
}
</script>
</head>
<body onLoad="setup();">
<div class="status">Fuel: <span id="fuel"></span></div>
<div class="status">Store: <span id="store"></span></div>
<table id="board"></table>
<div class="status" id="outcome"></div>
</body>
</html>
I have a dynamic group of n by m divs to form a grid. The items in this grid can be selected. The end result which I am hoping to achieve is to be able to combine and split the selected divs.
I have managed to get the divs to show correctly and select them, storing their id's in a list. Is there a way I could combine the selected divs, keeping the ones around it in their place?
#(Html.Kendo().Window()
.Name("window") //The name of the window is mandatory. It specifies the "id" attribute of the widget.
.Title("Dashboard Setup") //set the title of the window
.Content(#<text>
<div id="divSetup">
<div class="dvheader">
<b>Dashboard Setup</b>
</div>
<div>
<p>Enter the number of columns and rows of dashboard elements. This will create an empty dashboard with a set number of items which can be filled with KPI charts.</p>
<br />
<div class="dvform">
<table>
<tr style="margin-bottom: 15px;">
<td>
#Html.Label("Number of Columns: ")
</td>
<td>
<input type="number" name="NumColumns" id="NoColumns" min="1" max="20" />
</td>
</tr>
<tr style="margin-bottom: 15px;">
<td>
#Html.Label("Number of Rows: ")
</td>
<td>
<input type="number" name="NumRows" id="NoRows" min="1" max="20" />
</td>
</tr>
</table>
</div>
</div>
<div style="float: right">
<button id="btnSave" class="k-primary">Save</button>
<button id="btnClose">Close</button>
</div>
</div>
</text>)
.Draggable() //Enable dragging of the window
.Resizable() //Enable resizing of the window
.Width(600) //Set width of the window
.Modal(true)
.Visible(false)
)
<div id="dashboard">
</div>
<button id="combine" title="Combine">Combine</button>
<script>
$(document).ready(function () {
debugger;
$("#window").data("kendoWindow").open();
$("#btnClose").kendoButton({
click: close
});
$("#btnSave").kendoButton({
click: Save
});
$("#combine").kendoButton();
});
var array = [];
function clicked(e)
{
debugger;
var selectedDiv = "";
var x = document.getElementsByClassName('column')
for (var i = 0; i < x.length; i++)
{
if (x[i].id == e.id)
{
x[i].classList.add("selected");
array.push(x[i]);
}
}
for (var x = 0; x < array.length - 1; x++) {
array[x].classList.add("selected");
}
}
function close() {
$("#window").hide();
}
function Save()
{
debugger;
var col = document.getElementById("NoColumns").value;
var row = document.getElementById("NoRows").value;
for (var x = 1; x <= row; x++)
{
debugger;
document.getElementById("dashboard").innerHTML += '<div class="row">';
debugger;
for (var i = 1; i <= col; i++)
{
document.getElementById("dashboard").innerHTML += '<div onclick="clicked(this)" id="Row ' + x + ' Col ' + i + '" class="column">' + i + '</div>';
}
document.getElementById("dashboard").innerHTML += '</div>';
}
}
<style>
.selected {
background-color: #226fa3;
transition: background-color 0.4s ease-in, border-color 0.4s ease-in;
color: #ffffff;
}
#dashboard {
width: 80%;
margin: auto;
background-color: grey;
padding: 20px;
}
* {
box-sizing: border-box;
}
/* Create three equal columns that floats next to each other */
.column {
float: left;
padding: 20px;
border: 1px black solid;
}
/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}
Below is an image of the selected blocks I would like to combine into one, while keeping it's place
If you were using a table it would be much easier, for div's, I can think of a solution if the style position is absolute, maybe it would help you start at least.
<div id="container"></div>
<button id="combine" title="Combine" disabled="disabled">Combine</button>
<div id="output"></div>
the script:
<script>
var cc;
function group() {
var xx = $(".selected").map(function () { return $(this).attr("data-x"); }).get();
var yy = $(".selected").map(function () { return $(this).attr("data-y"); }).get();
this.minX = Math.min.apply(Math, xx);
this.minY = Math.min.apply(Math, yy);
this.maxX = Math.max.apply(Math, xx);
this.maxY = Math.max.apply(Math, yy);
this.selectedCount = $(".selected").length;
this.CorrectGroup = function () {
var s = this.selectedCount;
return s == this.cellsCount() && s > 1;
}
this.width = function () {
return this.maxX - this.minX + 1;
}
this.height = function () {
return this.maxY - this.minY + 1;
}
this.cellsCount = function () {
return this.width() * this.height();
}
}
function cell(x, y, g) {
this.x = x;
this.y = y;
this.g = g;
this.spanX = 1;
this.spanY = 1;
this.visible = true;
var cellWidth = 80;
var cellHeight = 50;
this.div = function () {
var output = jQuery('<div/>');
output.attr('id', 'y' + y + 'x' + x);
output.attr('data-x', x);
output.attr('data-y', y);
output.attr('style', this.left() + this.top() + this.width() + this.height());
output.addClass('clickable');
output.html('(y=' + y + ' x=' + x + ')')
return output;
}
this.left = function () {
return 'left:' + (x * cellWidth) + 'px;';
}
this.top = function () {
return 'top:' + (100 + y * cellHeight) + 'px;';
}
this.width = function () {
return 'width:' + (this.spanX * cellWidth) + 'px;';
}
this.height = function () {
return 'height:' + (this.spanY * cellHeight) + 'px;';
}
}
function cells(xx, yy) {
this.CellWidth = xx;
this.CellHeight = yy;
this.CellList = [];
for (var y = 0; y < yy; y++)
for (var x = 0; x < xx; x++) {
this.CellList.push(new cell(x, y, 1));
}
this.findCell = function (xx, yy) {
return this.CellList.find(function (element) {
return (element.x == xx && element.y == yy);
});
}
this.displayCells = function (container) {
container.html('');
for (var y = 0; y < yy; y++)
for (var x = 0; x < xx; x++) {
var cell = this.findCell(x, y);
if (cell.visible)
cell.div().appendTo(container);
}
}
}
$(document).ready(function () {
$('#combine').click(function () {
$(".selected").each(function () {
var x = $(this).data('x');
var y = $(this).data('y');
var cell = cc.findCell(x, y);
cell.visible = false;
cell.g = 'y';
});
var first = $(".selected").first();
var xx = $(first).data('x');
var yy = $(first).data('y');
var cell = cc.findCell(xx, yy);
var g = new group();
cell.visible = true;
cell.g = xx + '_' + yy;
cell.spanX = g.width();
cell.spanY = g.height();
cc.displayCells($('#container'));
});
//make divs clickable
$('#container').on('click', 'div', function () {
$(this).toggleClass('selected');
if (CheckIfSelectedAreGroupable())
$('#combine').removeAttr("disabled");
else
$('#combine').attr("disabled", "disabled");
});
cc = new cells(12, 10);
cc.displayCells($('#container'));
});
function CheckIfSelectedAreGroupable() {
var g = new group();
return g.CorrectGroup();
}
</script>
Style:
<style>
.selected {
background-color: #226fa3 !important;
transition: background-color 0.4s ease-in, border-color 0.4s ease-in;
color: #ffffff;
}
.clickable {
border: 1px solid lightgray;
margin: 0px;
padding: 0px;
background-color: lightyellow;
position: absolute;
}
</style>
Im starting the divs by the following line, you can hock your form to trigger something similar.
cc = new cells(12, 10);
the combine button will not activate if you dont select a correct group, a rectangle shape selection.
the split will not be hard too but I did not have time to put it together, if this solution help, I can update it for the split.
Note: I wrote this quickly so its not optimized.
to try the solution use :
jsfiddle
The demo created is to illustrate the working of the logic described below -
I have created 4x4 tiles using JavaScript instead of hard coding into html
Code highlight the columns one by one in a infinite loop which is achieved by setInterval(colScan,1000)
When user press the mouse on html body, it changes the column scan --> row scan in the selected column which is also achieved by setInterval(rowScan,1000)
When user clicks again on the html body, it changes the row scan --> col scan
Problem:
No matter what, colScan is always activated which you can see in the console log that the column is always increasing.
When user clicks the second time it doesn't reset to column scan.
part of the code where I think the problem is occurring
createtiles();
var k = 0,
m = 0,
selected_col = "",
mousePressed = false,
col_scan = true,
row_scan = false;
scanSelector();
function scanSelector() {
if (col_scan) {
setInterval(colScan, 1000);
} else if (row_scan) {
setInterval(rowScan, 1000);
}
}
document.body.onmousedown = function() {
mousePressed = true;
}
function colScan() {
if (k > 2) k = 0;
else k++;
console.log("col " + k);
var col = ".j_" + k;
$(".tiles").removeClass('highlighter');
$(col).addClass('highlighter');
if (mousePressed) {
mousePressed = false;
col_scan = false;
row_scan = true;
selected_col = col;
scanSelector();
}
}
function rowScan() {
if (m > 2) m = 0;
else m++;
console.log("row " + m);
var row = selected_col + (".i_" + m);
$(".tiles").removeClass('highlighter');
$(row).addClass('highlighter');
if (mousePressed) {
mousePressed = false;
col_scan = true;
row_scan = false;
selected_col = "";
scanSelector();
}
}
function createtiles() {
for (var i = 0; i < 4; i++) {
for (var j = 0; j < 4; j++) {
var divTile = $('<div>', {
class: 'tiles ' + ("j_" + j) + " " + ("i_" + i)
});
divTile.appendTo('.comtile');
}
}
}
DEMO -> https://codepen.io/xblack/pen/BdGzYx
createtiles();
var k = 0,
m = 0,
selected_col = "",
mousePressed = false,
col_scan = true,
row_scan = false;
scanSelector();
function scanSelector() {
if (col_scan) {
setInterval(colScan, 1000);
} else if (row_scan) {
setInterval(rowScan, 1000);
}
}
document.body.onmousedown = function() {
mousePressed = true;
}
function colScan() {
if (k > 2) k = 0;
else k++;
console.log("col " + k);
var col = ".j_" + k;
$(".tiles").removeClass('highlighter');
$(col).addClass('highlighter');
if (mousePressed) {
mousePressed = false;
col_scan = false;
row_scan = true;
selected_col = col;
scanSelector();
}
}
function rowScan() {
if (m > 2) m = 0;
else m++;
console.log("row " + m);
var row = selected_col + (".i_" + m);
$(".tiles").removeClass('highlighter');
$(row).addClass('highlighter');
if (mousePressed) {
mousePressed = false;
col_scan = true;
row_scan = false;
selected_col = "";
scanSelector();
}
}
function createtiles() {
for (var i = 0; i < 4; i++) {
for (var j = 0; j < 4; j++) {
var divTile = $('<div>', {
class: 'tiles ' + ("j_" + j) + " " + ("i_" + i)
});
divTile.appendTo('.comtile');
}
}
}
html,
body {
margin: 0px;
padding: 0px;
height: 100%;
min-height: 100%;
overflow: hidden;
font-family: 'Roboto', sans-serif;
background: white;
}
* {
box-sizing: border-box!important;
}
.conatiner {
display: grid;
grid-template-columns: 1fr;
grid-template-rows: 1fr;
grid-template-area: "menu" "comContent";
}
.menu {
grid-area: menu;
height: 5vh;
padding: 2vh;
}
.comtile {
grid-area: comContent;
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-rows: auto;
grid-gap: 0.5vh;
height: 95vh;
padding: 2vh;
}
.tiles {
background: #F7F7F7;
border-radius: 0.4vh;
border: 1px solid #EEEBEB;
}
.highlighter {
box-shadow: 0 0 4px rgba(0, 0, 0, 0.15);
transition: box-shadow 0.3s cubic-bezier(0.38, -0.76, 0, 1.69);
border: 1px solid silver;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="container">
<div class="menu">MAIN MENU</div>
<div class="comtile"></div>
</div>
You need to make the following changes:
Replace setInterval with setTimeout for reasons stated by #ASDFGerte.
function scanSelector() {
if (col_scan) {
// Replace setInterval with setTimeout
setTimeout(colScan, 1000);
} else i f (row_scan) {
// Replace setInterval with setTimeout
setTimeout(rowScan, 1000);
}
}
Move the scanSelector() lines in rowScan and colScan. The change is the same for both methods, I will only show the change in rowScan.
function rowScan() {
if (m > 2) m = 0;
else m++;
console.log("row " + m);
var row = selected_col + (".i_" + m);
$(".tiles").removeClass('highlighter');
$(row).addClass('highlighter');
if (mousePressed) {
mousePressed = false;
col_scan = true;
row_scan = false;
selected_col = "";
// Remove this line
// scanSelector();
}
// Because you're no longer using setInterval you need to call
// this method after each timeout.
scanSelector();
}
Every time you were calling scanSelector() it would create another interval. The initial interval will highlight the columns, after the first click you have two intervals running side-by-side: the original interval and an interval to highlight rows. After each click you're only adding intervals.
You could store the interval ID, the result of setInterval and clear this interval when you change from column to row highlight and vice versa. The easier solution is moving from setInterval to setTimeout as outlined in the changed I've shown you above.
Im trying to create a program for one of my games(details not needed) nevertheless I can move around aside elements written in the code
<aside draggable="true" class="dragme" data-item="0">One</aside>
but if I create it at runtime(via button click) it gives me this error in the console
Uncaught TypeError: Cannot read property 'style' of undefined
Here is my full code anybody have ideas?
<!DOCTYPE HTML>
<html>
<head>
<style>
aside {
position: absolute;
left: 0;
top: 0;
width: 200px;
background: rgba(255, 255, 255, 1);
border: 2px solid rgba(0, 0, 0, 1);
border-radius: 4px;
padding: 8px;
}
.second {
left: 100px;
top: 100px;
}
body, html {
min-height: 100vh;
}
body{
width:700px;
height:700px;
}
</style>
</head>
<body ondragover="drag_over(event)" ondrop="drop(event)">
<div class="ControlPanel">
<button onclick="CreateNew('item1')">Item1</button>
</div>
<aside draggable="true" class="dragme" data-item="0">One</aside>
<script>
var dataNum = 0;
function CreateNew(item){
if(item == "item1"){
dataNum += 1;
var asi = document.createElement("ASIDE");
asi.setAttribute("draggable",true);
asi.setAttribute("class","dragme second");
asi.setAttribute("data-item",dataNum);
asi.setAttribute("style","left: 347px; top: 82px;");
document.body.appendChild(asi);
}
}
function drag_start(event) {
var style = window.getComputedStyle(event.target, null);
event.dataTransfer.setData("text/plain", (parseInt(style.getPropertyValue("left"), 10) - event.clientX) + ',' + (parseInt(style.getPropertyValue("top"), 10) - event.clientY) + ',' + event.target.getAttribute('data-item'));
}
function drag_over(event) {
event.preventDefault();
return false;
}
function drop(event) {
var offset = event.dataTransfer.getData("text/plain").split(',');
var dm = document.getElementsByClassName('dragme');
dm[parseInt(offset[2])].style.left = (event.clientX + parseInt(offset[0], 10)) + 'px';
dm[parseInt(offset[2])].style.top = (event.clientY + parseInt(offset[1], 10)) + 'px';
event.preventDefault();
return false;
}
var dm = document.getElementsByClassName('dragme');
for (var i = 0; i < dm.length; i++) {
dm[i].addEventListener('dragstart', drag_start, false);
document.body.addEventListener('dragover', drag_over, false);
document.body.addEventListener('drop', drop, false);
}
</script>
</body>
</html>
You are registering the event listener only once during the page load. Therefore, when you create a new element, you need to re-register the events for the newly created elements too.
<script>
var dataNum = 0;
function CreateNew(item){
if(item == "item1"){
dataNum += 1;
var asi = document.createElement("ASIDE");
asi.setAttribute("draggable",true);
asi.setAttribute("class","dragme second");
asi.setAttribute("data-item",dataNum);
asi.setAttribute("style","left: 347px; top: 82px;");
document.body.appendChild(asi);
registerDragMe(); // --> Add this
}
}
function drag_start(event) {
var style = window.getComputedStyle(event.target, null);
event.dataTransfer.setData("text/plain", (parseInt(style.getPropertyValue("left"), 10) - event.clientX) + ',' + (parseInt(style.getPropertyValue("top"), 10) - event.clientY) + ',' + event.target.getAttribute('data-item'));
}
function drag_over(event) {
event.preventDefault();
return false;
}
function drop(event) {
var offset = event.dataTransfer.getData("text/plain").split(',');
var dm = document.getElementsByClassName('dragme');
dm[parseInt(offset[2])].style.left = (event.clientX + parseInt(offset[0], 10)) + 'px';
dm[parseInt(offset[2])].style.top = (event.clientY + parseInt(offset[1], 10)) + 'px';
event.preventDefault();
return false;
}
// create a wrapper function
function registerDragMe(){
var dm = document.getElementsByClassName('dragme');
for (var i = 0; i < dm.length; i++) {
dm[i].addEventListener('dragstart', drag_start, false);
document.body.addEventListener('dragover', drag_over, false);
document.body.addEventListener('drop', drop, false);
}
}
registerDragMe();
</script>
Working example : https://jsfiddle.net/jcLjr70y/