This code is executing on all instances of .flow-hold and not just the div below the .title-hold with text that matches the ==.
The reason for this is I need to change the ranges that I use for each of the gauge1, gauge2, gauge3 instances. I have tried $('.flow-hold').next(function(){
but this is not working either......many thanx in advance
$('.title-hold').each(function() {
if ($(this).text() == 'gauge1') {
$('.flow-hold').each(function() {
if (parseInt($(this).text()) >= 0.0 && ($(this).text()) <= 100.0) {
$(this).css("background-color", "green");
} else if (parseInt($(this).text()) >= 101.0 && ($(this).text()) <= 200.0) {
$(this).css("background-color", "yellow");
} else if (parseInt($(this).text()) >= 300.0 && ($(this).text()) <= 400.0) {
$(this).css("background-color", "red");
} else {
$(this).css("background-color", "purple");
}
});
} else {
//do nothing
}
});
$('.title-hold').each(function() {
if ($(this).text() == 'gauge2') {
$('.flow-hold').each(function() {
if (parseInt($(this).text()) >= 0.0 && ($(this).text()) <= 250.0) {
$(this).css("background-color", "orange");
} else if (parseInt($(this).text()) >= 251.0 && ($(this).text()) <= 345.0) {
$(this).css("background-color", "pink");
} else if (parseInt($(this).text()) >= 346.0 && ($(this).text()) <= 800.0) {
$(this).css("background-color", "brown");
} else {
$(this).css("background-color", "purple");
}
});
} else {
//do nothing
}
});
.title-hold {
width: 100%;
background: #000;
clear: both;
text-align: center;
color: #fff;
font-size: 18px;
}
.flow-hold {
width: 50%;
float: left;
text-align: center;
font-size: 18px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="title-hold">gauge1</div>
<div class="flow-hold">200</div>
<div class="title-hold">gauge2</div>
<div class="flow-hold">10.5</div>
<div class="title-hold">gauge3</div>
<div class="flow-hold">325.5</div>
There is no need for multiple loops. Just loop once and upon each loop iteration check all gauge values and act accordingly.
Also, it's simpler to work with CSS classes, rather than setting inline styles.
Additionally, be careful with your >= and <= values. The way you have it, if a value were 100.5, it wouldn't match any condition. You may not be planning on working with decimal values right now, but by changing the range a bit, you are safeguarded for the future.
See comments inline.
$('.title-hold').each(function() {
let text = $(this).text(); // Get the text of the .title-hold element
// Get a reference to the .flow-hold element that follows it.
// .next() with no arguments will return the next sibline element after the current one.
let next = $(this).next();
// Get the text of the .flow-hold element that follows it and convert to a number.
// The pre-pended "+" here forces a conversion of the string to a number.
let num = +next.text();
// Depending on what the text of the current .title-hold element being looped is...
switch(text){
case 'gauge1':
if(num >= 0 && num <= 100){
next.addClass("green");
} else if(num <= 200){ // <-- NOTE: the previous test already handled values <=100
next.addClass("yellow");
} else if(num <= 400){
next.addClass("red");
} else {
next.addClass("purple");
}
break;
case 'gauge2':
if(num >= 0 && num <= 250){
next.addClass("orange");
} else if(num <= 345){
next.addClass("pink");
} else if(num <= 800){
next.addClass("brown");
} else {
next.addClass("purple");
}
break;
case 'gauge3':
// Repeat the if statement from above, but with appropriate tests and classes
break;
}
});
.title-hold {
width: 100%;
background: #000;
clear: both;
text-align: center;
color: #fff;
font-size: 18px;
}
.flow-hold {
width: 50%;
float: left;
text-align: center;
font-size: 18px;
}
/* These classes will be conditionally applied */
.green { background-color:green; }
.yellow { background-color:yellow; }
.red { background-color:red; }
.purple { background-color:purple; }
.orange { background-color:orange; }
.pink { background-color:pink; }
.brown { background-color:brown; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="title-hold">gauge1</div>
<div class="flow-hold">200</div>
<div class="title-hold">gauge2</div>
<div class="flow-hold">10.5</div>
<div class="title-hold">gauge3</div>
<div class="flow-hold">325.5</div>
.next() doesn't take a function argument, you just use it to get the element that you want to act on.
Also, the else if statements don't need to check the lower limits. The <= test in the preceding if ensures that the number is above that limit. Your code was also skipping values between 100.0 and 101.0 -- they would end up in the else at the end.
$('.title-hold').each(function() {
var flowHold = $(this).next('.flow-hold');
var nextVal = parseInt(flowHold.text());
if ($(this).text() == 'gauge1') {
if (nextVal >= 0.0 && nextVal <= 100.0) {
flowHold.css("background-color", "green");
} else if (nextVal <= 200.0) {
flowHold.css("background-color", "yellow");
} else if (nextVal <= 400.0) {
flowHold.css("background-color", "red");
} else {
flowHold.css("background-color", "purple");
}
} else if ($(this).text() == 'gauge2') {
if (nextVal >= 0.0 && nextVal <= 250.0) {
flowHold.css("background-color", "orange");
} else if (nextVal <= 245.0) {
flowHold.css("background-color", "pink");
} else if (nextVal <= 800.0) {
flowHold.css("background-color", "brown");
} else {
flowHold.css("background-color", "purple");
}
}
});
.title-hold {
width: 100%;
background: #000;
clear: both;
text-align: center;
color: #fff;
font-size: 18px;
}
.flow-hold {
width: 50%;
float: left;
text-align: center;
font-size: 18px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="title-hold">gauge1</div>
<div class="flow-hold">200</div>
<div class="title-hold">gauge2</div>
<div class="flow-hold">10.5</div>
<div class="title-hold">gauge3</div>
<div class="flow-hold">325.5</div>
Here:
const gaugeConfig = {
'gauge1': {
ranges: [
{
min: 0,
max: 100,
color: 'green'
},
{
min: 101,
max: 200,
color: 'yellow'
},
{
min: 300,
max: 400,
color: 'red'
}
],
defaultColor: 'purple'
},
'gauge2': {
ranges: [
{
min: 0,
max: 250,
color: 'orange'
},
{
min: 251,
max: 345,
color: 'pink'
},
{
min: 346,
max: 800,
color: 'brown'
}
],
defaultColor: 'purple'
},
}
function updateColors(flowHold, config) {
flow = parseFloat(flowHold.text());
flowHold.css("background-color", config.defaultColor);
for( var i=0; i < config.ranges.length; i++ ) {
range = config.ranges[i];
if (flow >= range.min && flow <= range.max) {
flowHold.css("background-color",range.color);
break;
}
}
}
$('.flow-hold').each(function() {
flowHold = $(this);
titleHold = flowHold.prev();
title = titleHold.text();
config = gaugeConfig[title];
if (config)
updateColors(flowHold, config);
});
.title-hold {
width: 100%;
background: #000;
clear: both;
text-align: center;
color: #fff;
font-size: 18px;
}
.flow-hold {
width: 50%;
float: left;
text-align: center;
font-size: 18px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="title-hold">gauge1</div>
<div class="flow-hold">200</div>
<div class="title-hold">gauge2</div>
<div class="flow-hold">10.5</div>
<div class="title-hold">gauge3</div>
<div class="flow-hold">325.5</div>
<div class="title-hold">gauge4</div>
<div class="flow-hold">201</div>
Related
I'm working on a tictactoe Person vs Person game. As a bonus, we can try to implement a minimax algorithm to play against the computer. After numerous trials and errors, I think I have the function so far, that it goes through the calculation without an error. However, the return value for best Score is always -10, assuming the player and not the computer would win.
I have two problems in the code:
the minimax-function always returns the value -10, assuming the person would win.
I cant play the last turn. In the debugger I can see that my gameData array, that keeps track of the visible field, works normally like so: [0,"X","X","O","X","O","O",7,"X"]. But the arrays player.person and player.computer have already stored the 0 and the 7. This should not happen.
At this point I am stuck. And I would tell you what I have been trying so far, but the last couple hours were just poking in the dark pretty much. Therefore the least I can do is write down the steps the code takes till the end:
Important variables etc:
Computer is represented by "O", person by "X"
Array gameData: Starts as [0,1,2,...,8] and replaces the numbers with "X" or "O". It tries to prevent that the tictactoe fields can be selected more than once.
Object player with .person-Array and .computer-Array both start as empty. I use these to check if either of them won the game.
isWinner(PLAYER) iterates through the winning conditions and checks if person or computer match it. The function returns the object ({win:true}) if so.
isTie() checks if there is a tie. It returns the object ({tie:true]), if the conditions isWinner(player.computer) = false, isWinner(player.person) = false and emptySpaces(gameData).length = 0 are met.
the function bestMove() searches for the bestMove of computer. Here's where minimax gets executed.
Code Logic overall:
the code starts at line 140 with function vsComputerGame()
next step is function personMove() in line 301
the player's choice "X" gets stored in the gameData Array. EG gameData = [0,"X",2,...,8]. And the position of "X" (in the exp 1`) gets pushed into player.person.
next it checks, if the person won the game or the game is a tie.
next the function bestMove() gets executed. It chooses a tictactoe-field for the computer.
next player.person and player.computer get updated. Without this step, minimax keeps pushing numbers in those arrays.
Code logic bestMove() and minimax():
bestMove() starts at line 190
the initial player.person and player.computer are saved, to restore them, right after the minimax() function returns a value. Same problem as above: Otherwise, isWinner() returns true on the second click of the player.
for loop gets executed. It selects the first available spot in gameData and replaces it with an "O". player.computer gets updated with this possible move from the computer.
then minimax gets executed, which basically has the same code for both player.computer and player.person, as described in this for loop.
when minimax() returns a value, it get stored in the variable score.
now the gameData Array, player.person and player.computer are reset, so the next iteration of the for loop does not flood them.
at last the if (score.eval > bestScore) checks for the highest score. If highest, the index of the current iteration gets stored in the move variable and is then used to place the "O" on the visible field and inside gameData.
"use strict"
// this function stores the chosen players (condition: player1, player2, computer). The start-game is in another module
let menupage = (function() {
let playerSelection = document.querySelectorAll(".player-selection");
let modalContainer = document.querySelector(".modal-bg");
let submitName = document.querySelector("#submit");
let btnColorPlayerTwo = document.querySelector("#player-two");
let btnColorComputer = document.querySelector("#computer");
let btnColorplayerOne = document.querySelector("#player-one");
let modalClose = document.querySelector(".modal-close");
let inputField = document.querySelector("#name");
let isplayerOne;
let gameModeData = {
playerOne : "",
playerTwo : "",
computer : false,
}
function closeModal() {
inputField.value = "";
modalContainer.classList.remove("bg-active");
}
function submitPlayer() {
if (isplayerOne === true) {
if (inputField.value === "") {
alert("Please enter your battle-tag");
} else if (inputField.value !== "") {
btnColorplayerOne.style.backgroundColor = "#4CAF50";
gameModeData.playerOne = inputField.value;
inputField.value = "";
modalContainer.classList.remove("bg-active");
}
}
if (isplayerOne === false) {
if (inputField.value === "") {
alert("Please enter your battle-tag");
} else if (inputField.value !== "") {
gameModeData.playerTwo = inputField.value;
btnColorPlayerTwo.style.backgroundColor = "#f44336";
gameModeData.computer = false;
btnColorComputer.style.backgroundColor = "#e7e7e7";
inputField.value = "";
modalContainer.classList.remove("bg-active");
}
}
}
function definePlayer(id, color) {
modalClose.addEventListener("click", closeModal);
if (id === "player-one") {
if (color.backgroundColor === "" || color.backgroundColor === "rgb(231, 231, 231)") {
isplayerOne = true;
modalContainer.classList.add("bg-active");
submitName.addEventListener("click", submitPlayer);
} else if (color.backgroundColor === "rgb(76, 175, 80)") {
color.backgroundColor = "#e7e7e7";
gameModeData.playerOne = "";
}
}
if (id === "player-two") {
if (color.backgroundColor === "" || color.backgroundColor === "rgb(231, 231, 231)") {
isplayerOne = false;
modalContainer.classList.add("bg-active");
submitName.addEventListener("click", submitPlayer);
}
}
}
function defineOponent(target) {
if (target.backgroundColor === "rgb(0, 140, 186)") {
return;
} else if (target.backgroundColor === "rgb(231, 231, 231)" || target.backgroundColor === "") {
target.backgroundColor = "#008CBA";
btnColorPlayerTwo.style.backgroundColor = "#e7e7e7";
gameModeData.playerTwo = "";
gameModeData.computer = true;
}
}
let setupPlayers = function setupPlayers() {
if (this.id === "player-one" || this.id === "player-two") {
definePlayer(this.id, this.style);
} else if (this.id === "computer") {
defineOponent(this.style);
}
}
playerSelection.forEach(button => button.addEventListener("click", setupPlayers))
return gameModeData;
}())
let startRound = (function startRound() {
let startGameBtn = document.querySelector("#start-game");
let startScreen = document.querySelector(".start-screen");
let gameboard = document.querySelector(".gameboard");
let selectionMenu = document.querySelector(".window-container");
let frame = document.querySelector(".frame");
let scoreboardPlayer = document.querySelector(".scoreboard-left");
let scoreboardOponent = document.querySelector(".scoreboard-right");
let scorePlayer = document.querySelector(".scoreboard-player");
let scoreOponent = document.querySelector(".scoreboard-oponent");
function displayScore() {
scorePlayer.innerText = menupage.playerOne;
menupage.computer === false ? scoreOponent.innerText = menupage.playerTwo : scoreOponent.innerText = "Computer";
}
function startGame() {
if (menupage.playerOne === "") {
alert("Please choose your profile.");
} else if (menupage.playerTwo === "" && menupage.computer === false) {
alert("Please choose an opponent.")
} else {
startScreen.style.display = "none";
gameboard.style.display = "grid";
scoreboardPlayer.style.display = "grid";
scoreboardOponent.style.display = "grid";
frame.style.display = "none";
selectionMenu.style.gridTemplateAreas = '"header header header" "scoreboard-left gameboard scoreboard-right" "frame frame frame"';
displayScore();
game();
}
}
startGameBtn.addEventListener("click", startGame);
}())
/* ***************************** GAME VS COMPUTER FUNCTION STARTS HERE ************************* */
let vsComputerGame = (function vsComputerGame() {
let player = {
person : [],
computer : [],
}
let gameData = [0, 1, 2, 3, 4, 5, 6, 7, 8]
let isWinner = function isWinner(PLAYER) {
let check = PLAYER.join();
let condition = {
1 : ["0","1","2"],
2 : ["3","4","5"],
3 : ["6","7","8"],
4 : ["0","4","8"],
5 : ["2","4","6"],
6 : ["0","3","6"],
7 : ["1","4","7"],
9 : ["2","5","8"]
}
for (const property in condition) {
if (condition[property].every(v => check.includes(v)) === true) {
return ({win : true});
}
}
return ({win : false });
};
let isTie = function isTie() {
if (emptySpaces(gameData).length === 0 && isWinner(player.computer).win === false && isWinner(player.person).win === false) {
return ({tie: true});
} else {
return ({tie : false});
}
}
function emptySpaces(gameData) {
let updatedBoard = [];
for (let i = 0; i < gameData.length; i++) {
if (gameData[i] !== "X") {
if (gameData[i] !== "O") {
updatedBoard.push(gameData[i]);
}
}
}
return updatedBoard;
}
function bestMove() {
let bestScore = -Infinity;
let move;
// the object player with the values {player:[], computer:[]} is used in isWinner to check who won,
// storedComputer and storedPlayer is needed, to reset both arrays after they go through minimax,
// without, the two object-arrays get fludded
let storedComputer = player.computer.map(x => x);
let storedPlayer = player.person.map(x => x);
// first round of the for loop sets a field for the computer,
// first execution of minimax jumps to player.person
for (let i = 0; i < 9; i++) {
// gameData is the Array, that stores the players' moves. Example: [0, 1, 2, "X", 4, 5, "O", 7, 8]
if (gameData[i] !== "X") {
if (gameData[i] !== "O") {
gameData[i] = "O";
player.computer.push(i);
let score = minimax(gameData, player.person);
gameData[i] = i;
player.person = storedPlayer;
player.computer = storedComputer;
if (score.eval > bestScore) {
bestScore = score.eval;
move = i;
console.log(bestScore);
}
}
}
}
// after a move is found for the computer, O gets logged in the gameData Array and on the visible gameboard
let positionO = document.getElementsByName(move);
gameData[move] = "O";
positionO[0].innerText = "O";
}
function minimax(gameData, PLAYER) {
// the BASE of minimax.
// ************ console.log shows, that it always returns -10 ***************
if (isWinner(player.person).win === true) { return ({eval:-10});}
if (isWinner(player.computer).win === true) { return ({eval:10});}
if (isTie().tie === true) {return ({eval:0});};
/*
PLAYER.push pushes the index-number into either player.computer or player.person
This is needed to check the isWinner function
After that, these Arrays get stored in storedComputer and storedPlayer
*/
if (PLAYER === player.computer) {
let bestScore = -Infinity;
for (let i = 0; i < 9; i++) {
if (gameData[i] !== "X") {
if (gameData[i] !== "O") {
PLAYER.push(i);
//let storedComputer = player.computer.map(x => x);
//let storedPlayer = player.person.map(x => x);
gameData[i] = "O";
let score = minimax(gameData, player.person);
//player.person, player.computer and gameData are resetted, after minimax returns a value
gameData[i] = i;
//player.person = storedPlayer;
//player.computer = storedComputer;
if (score.eval > bestScore) {
bestScore = score.eval;
}
}
}
}
return bestScore;
} else {
let bestScore = Infinity;
for (let i = 0; i < 9; i++) {
if (gameData[i] !== "X") {
if (gameData[i] !== "O") {
PLAYER.push(i);
//let storedComputer = player.computer.map(x => x);
//let storedPlayer = player.person.map(x => x);
gameData[i] = "X";
let score = minimax(gameData, player.computer);
//player.person = storedPlayer;
//player.computer = storedComputer;
gameData[i] = i;
if (score.eval < bestScore) {
bestScore = score.eval;
}
}
}
}
return bestScore;
}
}
let cells = document.querySelectorAll(".cell");
cells.forEach(cell => cell.addEventListener("click", personMove));
function personMove() {
if (this.innerText === "X" || this.innerText === "O") {
return;
} else {
let playersChoice = this.getAttribute("data-parent");
player.person.push(Number(this.getAttribute("data-parent")));
this.innerText = "X";
gameData[playersChoice] = "X";
if (isWinner(player.person).win === true) {
console.log("Win");
};
isTie();
bestMove();
player.computer = [];
player.person = [];
for (let i = 0; i < 9; i++) {
if (gameData[i] === "X") {
player.person.push(i);
} else if (gameData[i] === "O") {
player.computer.push(i);
}
}
}
}
})
/* ***************************** GAME VS COMPUTER FUNCTION ENDS HERE ************************* */
let vsPersonGame = (function vsPersonGame() {
let i = 1;
let player = [];
let oponent = [];
let buttons = document.querySelectorAll(".cell");
buttons.forEach(button => button.addEventListener("click", selection));
function selection() {
let newLocal = this
storeSelection(newLocal);
checkWinner();
}
function storeSelection(input) {
if (i >= 10 || input.innerText !== "") {
return;
} else if (i % 2 === 0) {
return input.innerText = "O", oponent.push(input.dataset.parent),
i++;
} else if (i % 2 !== 0) {
return input.innerText = "X", player.push(input.dataset.parent),
i++;
}
}
function checkWinner() {
let condition = {
1 : ["0","1","2"],
2 : ["3","4","5"],
3 : ["6","7","8"],
4 : ["0","4","8"],
5 : ["2","4","6"],
6 : ["0","3","6"],
7 : ["1","4","7"],
9 : ["2","5","8"]
}
for (const property in condition) {
let toStringplayer = player.join();
let toStringoponent = oponent.join();
if (condition[property].every(v => toStringplayer.includes(v)) === true) {
return alert(menupage.playerOne + " won");
} else if (condition[property].every(v => toStringoponent.includes(v)) === true) {
return alert(menupage.playerTwo + " won");
} else if (i === 10) {
if (condition[property].every(v => toStringplayer.includes(v)) === true) {
return alert(menupage.playerOne + " won");
} else if (condition[property].every(v => toStringoponent.includes(v)) === true) {
return alert(menupage.playerTwo + " won");
} else {
return alert("You tied");
}
}
}
}
})
let game = (function() {
if (menupage.computer === true) {
vsComputerGame();
} else {
vsPersonGame();
}
});
html, body {
display: grid;
height: 100%;
margin: 0;
padding: 0;
}
.window-container {
display: grid;
height: 100%;
grid-template-rows: 10% 80% 10%;
grid-template-areas:
"header header header"
". start-screen ."
"frame frame frame";
}
.header {
grid-area: header;
margin-top: 50px;
font-size: 30px;
text-align: center;
color: red;
font-weight: bolder;
}
.start-screen {
grid-area: start-screen;
display: flex;
justify-content: center;
align-items: center;
margin-bottom: 30%;
}
.selection-menu {
flex: 1;
display: grid;
grid-template-rows: 40% 20% 40%;
grid-template-areas:
". . player-two"
"player-one vs ."
". . computer"
}
#player-one {
grid-area: player-one;
background-color: #e7e7e7;
}
#player-two {
grid-area: player-two;
background-color: #e7e7e7;
}
#computer {
grid-area: computer;
background-color: #e7e7e7;
}
#start-game {
display: flex;
cursor: pointer;
border: none;
color: white;
background-color: rgb(37, 36, 36);
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
#vs {
grid-area: vs;
text-align: center;
font-size: 30px;
font-weight: bold;
color: #4CAF50;
}
.player-selection {
cursor: pointer;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
.gameboard {
grid-area: gameboard;
margin-top: 10%;
display: none;
justify-content: center;
grid-template-rows: 150px 150px 150px;
grid-template-columns: 150px 150px 150px;
grid-template-areas:
"tL tM tR"
"mL mM mR"
"bL bM bR";
}
.frame {
grid-area: frame;
display: flex;
position: fixed;
height: 250px;
bottom: 0px;
left: 0px;
right: 0px;
margin-bottom: 0px;
justify-content: center;
align-items: center;
}
.cell {
display: flex;
justify-content: center;
align-items: center;
font-size: 40px;
cursor: pointer;
}
.unselectable {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
#tL {
grid-area: tL;
border-bottom: 2px solid black;
border-right: 2px solid black;
}
#tM {
grid-area: tM;
border-bottom: 2px solid black;
border-right: 2px solid black;
}
#tR {
grid-area: tR;
border-bottom: 2px solid black;
}
#mL {
grid-area: mL;
border-bottom: 2px solid black;
border-right: 2px solid black;
}
#mM {
grid-area: mM;
border-bottom: 2px solid black;
border-right: 2px solid black;
}
#mR {
grid-area: mR;
border-bottom: 2px solid black;
}
#bL {
grid-area: bL;
border-right: 2px solid black;
}
#bM {
grid-area: bM;
border-right: 2px solid black;
}
#bR {
grid-area: bR;
}
.modal-bg {
position: fixed;
width: 100%;
height: 100vh;
top: 0;
left: 0;
background-color: rgba(0,0,0,0.5);
display: flex;
justify-content: center;
align-items: center;
visibility: hidden;
opacity: 0;
transition: visibility 0s, opacity 0.5s;
}
.bg-active {
visibility: visible;
opacity: 1;
}
.modal {
position: relative;
background-color: white;
border-radius: 5px 5px 5px 5px;
width: 30%;
height: 20%;
display: flex;
justify-content: space-around;
align-items: center;
flex-direction: column;
}
.modal button {
padding: 10px 50px;
background-color: #2980b9;
color: white;
border: none;
cursor: pointer;
}
.modal-close {
position: absolute;
top: 10px;
right: 10px;
font-weight: bold;
cursor: pointer;
}
#modal-headline {
font-size: 20px;
}
#submit {
margin-top: 5px;
}
.scoreboard-left {
display: none;
}
.scoreboard-player {
grid-area: scoreboard-player;
display: flex;
}
.scoreboard-right {
display: none;
}
.scoreboard-oponent {
grid-area: scoreboard-oponent;
display: flex;
}
<!DOCTYPE html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="UTF-8">
<link href="styles.css" rel="stylesheet" type="text/css" />
<script src="script.js" defer></script>
<title>Tic Tac Toe</title>
</head>
<body>
<div class="window-container">
<div class="header">Tic Tac Toe</div>
<div class="start-screen">
<div class="selection-menu">
<button class="player-selection" id="player-one">Player One</button>
<button class="player-selection" id="player-two">Player Two</button>
<div id="vs">vs</div>
<button class="player-selection" id="computer">Computer</button>
</div>
</div>
<div class="gameboard">
<div class="cell unselectable" id="tL" data-parent="0" name="0"></div>
<div class="cell unselectable" id="tM" data-parent="1" name="1"></div>
<div class="cell unselectable" id="tR" data-parent="2" name="2"></div>
<div class="cell unselectable" id="mL" data-parent="3" name="3"></div>
<div class="cell unselectable" id="mM" data-parent="4" name="4"></div>
<div class="cell unselectable" id="mR" data-parent="5" name="5"></div>
<div class="cell unselectable" id="bL" data-parent="6" name="6"></div>
<div class="cell unselectable" id="bM" data-parent="7" name="7"></div>
<div class="cell unselectable" id="bR" data-parent="8" name="8"></div>
</div>
<div class="modal-bg">
<div class="modal">
<h2 id="modal-headline">Choose a Name:</h2>
<input type="text" id="name">
<button id="submit" class="submit">Submit</button>
<span class="modal-close">X</span>
</div>
</div>
<div class="frame">
<button id="start-game">Start Game</button>
</div>
<div class="scoreboard-left">
<div class="display-player">
<div class="scoreboard-player"></div>
<div class="p-win">Wins: </div><div class="player-win">0</div>
<div class="p-loss">Losses: </div><div class="player-loss">0</div>
<div class="p-tie">Ties: </div><div class="player-tie">0</div>
</div>
</div>
<div class="scoreboard-right">
<div class="display-oponent">
<div class="scoreboard-oponent"></div>
<div class="o-win">Wins: </div><div class="oponent-win">0</div>
<div class="o-loss">Losses: </div><div class="oponent-loss">0</div>
<div class="o-tie">Ties: </div><div class="oponent-tie">0</div>
</div>
</div>
</div>
</body>
</html>
I appreciate any feedback and hints to solve the problem.
Using the tags() function, there is a parameter for maximum number of tags (maxTags) you can enter into each input.
I need to hide(); the tags-input when maxTags = 2 and then
show(); when the tag is removed / not at the max.
maxTags :1 isn't working but it should be. Only 2 or more is acceptable. I tried debugging the max tags parameter but couldn't find out why maxTags: 1 is
unacceptable.
How can I change the function to allow maxTags: 1 and also show/hide the tag-input when maxTags is reached?
// max tags in tags() function:
if (opts.maxTags) {
if ($self.val().split(",").length == opts.maxTags) {
otherCheck = false;
$input.val("");
$next.val("");
}
}
// Calling the tags() function:
$("#" + formId)
.find(".input--proj")
.tags({
unique: true,
maxTags: 2
})
.autofill({
data: autolist
});
(function($) {
$.fn.tags = function(opts) {
var selector = this.selector;
//console.log("selector",selector);
// updates the original input
function update($original) {
var all = [];
var list = $original.closest(".tags-wrapper").find("li.tag span").each(function() {
all.push($(this).text());
});
all = all.join(",");
$original.val(all);
}
return this.each(function() {
var self = this,
$self = $(this),
$wrapper = $("<div class='tags-wrapper'><ul></ul></div");
tags = $self.val(),
tagsArray = tags.split(","),
$ul = $wrapper.find("ul");
// make sure have opts
if (!opts) opts = {};
opts.maxSize = 50;
// add tags to start
tagsArray.forEach(function(tag) {
if (tag) {
$ul.append("<li class='tag'><span>" + tag + "</span><a href='#'>x</a></li>");
}
});
// get classes on this element
if (opts.classList) $wrapper.addClass(opts.classList);
// add input
$ul.append("<li class='tags-input'><input type='text' class='tags-secret'/></li>");
// set to dom
$self.after($wrapper);
// add the old element
$wrapper.append($self);
// size the text
var $input = $ul.find("input"),
size = parseInt($input.css("font-size")) - 4;
// delete a tag
$wrapper.on("click", "li.tag a", function(e) {
e.preventDefault();
$(this).closest("li").remove();
$self.trigger("tagRemove", $(this).closest("li").find("span").text());
update($self);
$("[data-search]").keyup();
});
// backspace needs to check before keyup
$wrapper.on("keydown", "li input", function(e) {
// backspace
if (e.keyCode == 8 && !$input.val()) {
var $li = $ul.find("li.tag:last").remove();
update($self);
$self.trigger("tagRemove", $li.find("span").text());
}
// prevent for tab
if (e.keyCode == 9) {
e.preventDefault();
}
});
// as we type
$wrapper.on("keyup", "li input", function(e) {
e.preventDefault();
$ul = $wrapper.find("ul");
var $next = $input.next(),
usingAutoFill = $next.hasClass("autofill-bg"),
$inputLi = $ul.find("li.tags-input");
// regular size adjust
$input.width($input.val().length * (size));
// if combined with autofill, check the bg for size
if (usingAutoFill) {
$next.width($next.val().length * (size));
$input.width($next.val().length * (size));
// make sure autofill doesn't get too big
if ($next.width() < opts.maxSize) $next.width(opts.maxSize);
var list = $next.data().data;
}
// make sure we don't get too high
if ($input.width() < opts.maxSize) $input.width(opts.maxSize);
// tab, comma, enter
if (!!~[9, 188, 13].indexOf(e.keyCode)) {
var val = $input.val().replace(",", "");
var otherCheck = true;
// requring a tag to be in autofill
if (opts.requireData && usingAutoFill) {
if (!~list.indexOf(val)) {
otherCheck = false;
$input.val("");
}
}
// unique
if (opts.unique) {
// found a match already there
if (!!~$self.val().split(",").indexOf(val)) {
otherCheck = false;
$input.val("");
$next.val("");
}
}
// max tags
if (opts.maxTags) {
if ($self.val().split(",").length == opts.maxTags) {
otherCheck = false;
$input.val("");
$next.val("");
}
}
// if we have a value, and other checks pass, add the tag
if (val && otherCheck) {
// place the new tag
$inputLi.before("<li class='tag'><span>" + val + "</span><a href='#'>x</a></li>");
// clear the values
$input.val("");
if (usingAutoFill) $next.val("");
update($self);
$self.trigger("tagAdd", val);
}
}
});
});
}
})(jQuery);
var uniqueId = 1;
$(function() {
$(".btn--new").click(function() {
var copy = $("#s_item").clone(true, true);
var formId = "item_" + uniqueId;
copy.attr("id", formId);
$("#s_list").append(copy);
$("#" + formId)
.find(".input--proj")
.each(function() {
var autolist = new Array();
$.each($(".studio__project"), function(index, value) {
if ($.inArray($(value).attr("data-proj"), autolist) < 1) {
autolist.push($(value).attr("data-proj").toLowerCase());
}
});
$("#" + formId)
.find(".input--proj")
.tags({
unique: true,
maxTags: 2
})
.autofill({
data: autolist
});
function placeholderproj() {
$(".search__label--proj")
.find(".tags-secret")
.attr("placeholder", "Enter Keyword");
}
$(document).ready(placeholderproj);
});
uniqueId++;
});
});
$(document).on("keyup , keypress", "li input", function(e) {
$.each($(".tag"), function(index, value) {
$.each($(".studio__project"), function(subIndex, subValue) {
if (
$(subValue).attr("data-proj").toLowerCase() ==
$(value).find("span").html()
) {
var itemColor = $(subValue).attr("data-color");
$(value).css("background-color", itemColor);
}
});
});
$("[data-search]").keyup();
});
$(document).on("click", ".tag a", function(e) {
$("[data-search]").keyup();
});
$(document).ready(function() {
$(".btn--new").trigger("click");
$(".btn--new").trigger("click");
$(".btn--new").trigger("click");
});
::-webkit-input-placeholder {
/* Chrome/Opera/Safari */
color: #8e8e8e;
}
::-moz-placeholder {
/* Firefox 19+ */
color: #8e8e8e;
}
:-ms-input-placeholder {
/* IE 10+ */
color: #8e8e8e;
}
:-moz-placeholder {
/* Firefox 18- */
color: #8e8e8e;
}
.tags-wrapper {
background: white;
display: flex;
position: relative;
width: 100%;
height: 50px;
top: -1px;
border: 1px solid whitesmoke;
overflow: hidden;
}
.tags-wrapper ul {
position: absolute;
display: flex;
flex: 1;
align-items: center;
top: 0;
bottom: 0;
right: 0;
left: 0;
list-style-type: none;
margin: 0;
padding: 0;
}
.tags-wrapper li {
flex-grow: 1;
margin-left: 5px;
}
.tags-wrapper li input {
display: block;
border: none;
width: 100% !important;
}
.tags-wrapper li.tag {
display: flex;
flex-grow: 0;
position: relative;
padding: 10px;
font-size: 14px;
align-items: center;
border-radius: 5px;
list-style: none;
background-image: none;
box-shadow: none;
color: white;
}
.tags-wrapper li a {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
text-decoration: none;
color: rgba(0, 0, 0, 0);
}
.tags-wrapper li a:hover {
background-color: rgba(0, 0, 0, 0.4);
border-radius: 5px;
color: rgba(0, 0, 0);
background-image: url("http://svgshare.com/i/3yv.svg");
background-size: contain;
background-repeat: no-repeat;
background-position: center;
}
.tags-wrapper input {
display: none;
}
#s_item {
display: none
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.staticaly.com/gh/moofawsaw/donorport/master/auto-fill.min.js"></script>
<a id="btn_studio" href="#" class="btn btn--new ripple w-button">Create</a>
<div>keywords are: blue, red, green</div>
<div id="s_list">
<div id="s_item" data-item="studio" data-mode="none" class="post__item studio__item">
<div data-item="studio" class="post__itemwrap post__itemwrap--studio">
<div class="search search--proj w-embed"><label class="search__label--proj" data-color="">
<input type="text" class="input--proj" autocomplete="off" placeholder="">
</label></div>
<div class="w-dyn-list">
<div class="w-dyn-items">
<div class="w-dyn-item">
<div class="w-embed">
<div class="studio__project" data-proj="Blue" data-color="blue"></div>
</div>
</div>
<div class="w-dyn-item">
<div class="w-embed">
<div class="studio__project" data-proj="Green" data-color="green"></div>
</div>
</div>
<div class="w-dyn-item">
<div class="w-embed">
<div class="studio__project" data-proj="Red" data-color="red"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
I've added code to test maxTags value from 1 to 3. Just replace it.
Removed a tag. Show input.
$wrapper.on("click", "li.tag a", function(e) {
e.preventDefault();
$(this).closest("li").remove();
$self.trigger("tagRemove", $(this).closest("li").find("span").text());
update($self);
$("[data-search]").keyup();
$input.show(); // show input on remove
});
If string has no content, return 0. Else use split to find number of elements.
if (opts.maxTags) {
var len = $self.val();
len = len.trim().length > 0 ? len.split(',').length : 0;
(function($) {
$.fn.tags = function(opts) {
var selector = this.selector;
//console.log("selector",selector);
// updates the original input
function update($original) {
var all = [];
var list = $original.closest(".tags-wrapper").find("li.tag span").each(function() {
all.push($(this).text());
});
all = all.join(",");
$original.val(all);
}
return this.each(function() {
var self = this,
$self = $(this),
$wrapper = $("<div class='tags-wrapper'><ul></ul></div");
tags = $self.val(),
tagsArray = tags.split(","),
$ul = $wrapper.find("ul");
// make sure have opts
if (!opts) opts = {};
opts.maxSize = 50;
// add tags to start
tagsArray.forEach(function(tag) {
if (tag) {
$ul.append("<li class='tag'><span>" + tag + "</span><a href='#'>x</a></li>");
}
});
// get classes on this element
if (opts.classList) $wrapper.addClass(opts.classList);
// add input
$ul.append("<li class='tags-input'><input type='text' class='tags-secret'/></li>");
// set to dom
$self.after($wrapper);
// add the old element
$wrapper.append($self);
// size the text
var $input = $ul.find("input"),
size = parseInt($input.css("font-size")) - 4;
// delete a tag
$wrapper.on("click", "li.tag a", function(e) {
e.preventDefault();
$(this).closest("li").remove();
$self.trigger("tagRemove", $(this).closest("li").find("span").text());
update($self);
$("[data-search]").keyup();
$input.show(); // show input on remove
});
// backspace needs to check before keyup
$wrapper.on("keydown", "li input", function(e) {
// backspace
if (e.keyCode == 8 && !$input.val()) {
var $li = $ul.find("li.tag:last").remove();
update($self);
$self.trigger("tagRemove", $li.find("span").text());
}
// prevent for tab
if (e.keyCode == 9) {
e.preventDefault();
}
});
// as we type
$wrapper.on("keyup", "li input", function(e) {
e.preventDefault();
$ul = $wrapper.find("ul");
var $next = $input.next(),
usingAutoFill = $next.hasClass("autofill-bg"),
$inputLi = $ul.find("li.tags-input");
// regular size adjust
$input.width($input.val().length * (size));
// if combined with autofill, check the bg for size
if (usingAutoFill) {
$next.width($next.val().length * (size));
$input.width($next.val().length * (size));
// make sure autofill doesn't get too big
if ($next.width() < opts.maxSize) $next.width(opts.maxSize);
var list = $next.data().data;
}
// make sure we don't get too high
if ($input.width() < opts.maxSize) $input.width(opts.maxSize);
// tab, comma, enter
if (!!~[9, 188, 13].indexOf(e.keyCode)) {
var val = $input.val().replace(",", "");
var otherCheck = true;
// requring a tag to be in autofill
if (opts.requireData && usingAutoFill) {
if (!~list.indexOf(val)) {
otherCheck = false;
$input.val("");
}
}
// unique
if (opts.unique) {
// found a match already there
if (!!~$self.val().split(",").indexOf(val)) {
otherCheck = false;
$input.val("");
$next.val("");
}
}
// max tags
if (opts.maxTags) {
var len = $self.val();
len = len.trim().length > 0 ? len.split(',').length : 0;
if (len == opts.maxTags - 1) $input.hide();
if (len == opts.maxTags) {
otherCheck = false;
$input.val("");
$next.val("");
}
}
// if we have a value, and other checks pass, add the tag
if (val && otherCheck) {
// place the new tag
$inputLi.before("<li class='tag'><span>" + val + "</span><a href='#'>x</a></li>");
// clear the values
$input.val("");
if (usingAutoFill) $next.val("");
update($self);
$self.trigger("tagAdd", val);
}
}
});
});
}
})(jQuery);
var uniqueId = 1;
$(function() {
$(".btn--new").click(function() {
var copy = $("#s_item").clone(true, true);
var formId = "item_" + uniqueId;
copy.attr("id", formId);
$("#s_list").append(copy);
$("#" + formId)
.find(".input--proj")
.each(function() {
var autolist = new Array();
$.each($(".studio__project"), function(index, value) {
if ($.inArray($(value).attr("data-proj"), autolist) < 1) {
autolist.push($(value).attr("data-proj").toLowerCase());
}
});
$("#" + formId)
.find(".input--proj")
.tags({
unique: true,
maxTags: 1
})
.autofill({
data: autolist
});
function placeholderproj() {
$(".search__label--proj")
.find(".tags-secret")
.attr("placeholder", "Enter Keyword");
}
$(document).ready(placeholderproj);
});
uniqueId++;
});
});
$(document).on("keyup , keypress", "li input", function(e) {
$.each($(".tag"), function(index, value) {
$.each($(".studio__project"), function(subIndex, subValue) {
if (
$(subValue).attr("data-proj").toLowerCase() ==
$(value).find("span").html()
) {
var itemColor = $(subValue).attr("data-color");
$(value).css("background-color", itemColor);
}
});
});
$("[data-search]").keyup();
});
$(document).on("click", ".tag a", function(e) {
$("[data-search]").keyup();
});
$(document).ready(function() {
$(".btn--new").trigger("click");
$(".btn--new").trigger("click");
$(".btn--new").trigger("click");
});
::-webkit-input-placeholder {
/* Chrome/Opera/Safari */
color: #8e8e8e;
}
::-moz-placeholder {
/* Firefox 19+ */
color: #8e8e8e;
}
:-ms-input-placeholder {
/* IE 10+ */
color: #8e8e8e;
}
:-moz-placeholder {
/* Firefox 18- */
color: #8e8e8e;
}
.tags-wrapper {
background: white;
display: flex;
position: relative;
width: 100%;
height: 50px;
top: -1px;
border: 1px solid whitesmoke;
overflow: hidden;
}
.tags-wrapper ul {
position: absolute;
display: flex;
flex: 1;
align-items: center;
top: 0;
bottom: 0;
right: 0;
left: 0;
list-style-type: none;
margin: 0;
padding: 0;
}
.tags-wrapper li {
flex-grow: 1;
margin-left: 5px;
}
.tags-wrapper li input {
display: block;
border: none;
width: 100% !important;
}
.tags-wrapper li.tag {
display: flex;
flex-grow: 0;
position: relative;
padding: 10px;
font-size: 14px;
align-items: center;
border-radius: 5px;
list-style: none;
background-image: none;
box-shadow: none;
color: white;
}
.tags-wrapper li a {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
text-decoration: none;
color: rgba(0, 0, 0, 0);
}
.tags-wrapper li a:hover {
background-color: rgba(0, 0, 0, 0.4);
border-radius: 5px;
color: rgba(0, 0, 0);
background-image: url("http://svgshare.com/i/3yv.svg");
background-size: contain;
background-repeat: no-repeat;
background-position: center;
}
.tags-wrapper input {
display: none;
}
#s_item {
display: none
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.staticaly.com/gh/moofawsaw/donorport/master/auto-fill.min.js"></script>
<a id="btn_studio" href="#" class="btn btn--new ripple w-button">Create</a>
<div>keywords are: blue, red, green</div>
<div id="s_list">
<div id="s_item" data-item="studio" data-mode="none" class="post__item studio__item">
<div data-item="studio" class="post__itemwrap post__itemwrap--studio">
<div class="search search--proj w-embed"><label class="search__label--proj" data-color="">
<input type="text" class="input--proj" autocomplete="off" placeholder="">
</label></div>
<div class="w-dyn-list">
<div class="w-dyn-items">
<div class="w-dyn-item">
<div class="w-embed">
<div class="studio__project" data-proj="Blue" data-color="blue"></div>
</div>
</div>
<div class="w-dyn-item">
<div class="w-embed">
<div class="studio__project" data-proj="Green" data-color="green"></div>
</div>
</div>
<div class="w-dyn-item">
<div class="w-embed">
<div class="studio__project" data-proj="Red" data-color="red"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
function someFunc(){
var integer = document.getElementById('email').value.toString().length;
var symbolCount = 0 + integer;
// var last2 = 100 - integer2;
if (symbolCount >= 100) {
document.querySelector('.hidden_block').style.color = 'green';
}
else if (symbolCount <= 100) {
document.querySelector('.hidden_block').style.color = 'black';
document.querySelector('.error').style.display = "block";
}
else {
document.getElementById('max').style.color = 'black';
}
document.getElementById('symbol_count').innerHTML = symbolCount;
}
email.addEventListener("click", function(){
document.querySelector('.hidden_block').style.display = 'block';
document.getElementById('max').style.display = 'none';
});
#max, #max2 {
text-align: right;
margin-right: 55px;
}
.hidden_block {
display: none;
text-align: right;
margin-right: 55px;
}
.error {
display: none;
color: red;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<label for="email">Positive</label>
<textarea type="email" class="form-control" id="email" oninput="someFunc()" placeholder="Tell people about your experience: describe the place or activity, recommendations for travelers?"></textarea>
<p id="max">Minimal length - symbols</p>
<div class="hidden_block">
<span id="count">Symbols : <span id="symbol_count">0 </span> (minimum:100)</span>
</div>
<span class="error">Your review must be at least 100 characters long. Adding details really helps travelers.</span>
Hi everyone.I have a that simple textarea field.I need to realize something like that.When u write less than 100 words and click the outside of the email id the border color must be red.And error class must displayed.And i need to if the textarea field is empty the tag p with id max must be display block if the user will write any symbol the id max must bu display none.Thanks for help
function someFunc(){
var integer = document.getElementById('email').value.toString().length;
var symbolCount = 0 + integer;
var integerValue = document.getElementById('email');
var hidden_block = document.querySelector('.hidden_block');
var max = document.getElementById('max');
var error = document.querySelector('.error');
var positive = document.getElementById("positive");
// var last2 = 100 - integer2;
if (integer >= 1) {
hidden_block.style.display = 'inline-block';
max.style.display = 'none';
integerValue.classList.add("form-control");
} else {
hidden_block.style.display = 'none';
max.style.display = 'block';
error.style.display = "none";
positive.style.color = "#002C38";
integerValue.classList.remove("form-redBorder");
}
integerValue.addEventListener("click", function(){
error.style.display = "none";
positive.style.color = "#002C38";
integerValue.classList.remove("form-redBorder");
});
//Red error and border
document.body.addEventListener("click", function(e) {
var target = e.target || e.srcElement;
if (target !== integerValue && !isChildOf(target, integerValue)) {
error.style.display = "inline-block";
integerValue.classList.add("form-redBorder");
positive.style.color = "red";
} if (integer >= 100) {
error.style.display = "none";
integerValue.classList.remove("form-redBorder");
positive.style.color = "#002C38";
}
}, false);
function isChildOf(child, parent) {
if (child.parentNode === parent) {
return true;
} else if (child.parentNode === null) {
return false;
} else {
return isChildOf(child.parentNode, parent);
}
}
//Finished Red error and border
//Start to count symbols
if (symbolCount >= 100) {
hidden_block.style.color = 'green';
}
else if (symbolCount <= 100) {
hidden_block.style.color = 'black';
}
else {
max.style.color = 'black';
// document.getElementById('max2').style.color = 'black';
}
document.getElementById('symbol_count').innerHTML = symbolCount;
}
#email {
display: block;
padding: 6px 12px;
margin: 0 auto;
width: 90% !important;
height: 120px !important;
/*border:1px solid #44A1B7 !important;*/
}
.form-control {
margin: 0 auto;
width: 90% !important;
height: 120px !important;
border:1px solid #44A1B7;
}
#positive, #negative {
padding: 14px 15px 1px 55px;
color: #002C38;
font-size: 18px;
}
.form-redBorder {
margin: 0 auto;
border:1px solid #FF0000 !important;
}
#max, #max2 {
position: absolute;
right: 1%;
margin-right: 55px;
}
.hidden_block {
position: absolute;
right: 1%;
display: none;
text-align: right;
margin-right: 55px;
}
.error {
margin-left: 55px;
display: none;
color: #FF0000;
}
<form role="form">
<div class="form-group">
<p class="help-block">About youre site.</p>
<label for="email" id="positive">Positive</label>
<textarea type="email" id="email" oninput="someFunc()" placeholder="Your review must be at least 100 characters long<br> Adding details really helps travelers"></textarea>
<p id="max">(100 character minimum)</p><div class="hidden_block">
<span id="count">Symbols : <span id="symbol_count">0 </span> (min:100)</span>
</div>
<span class="error">Your review must be at least 100 characters long.<br> Adding details really helps travelers..</span>
</div>
</form>
You may understand this better by checking the CodePen version.
Going straight to the point, the issue is: when you go to the second or third "slide" (the reddish or bluish colors), and then attempt to resize your window, its interior will become grayish~black. That's not supposed to happen.
The black~gray content must stay within the black~gray "slide", the red in the red one, the blue in the blue one.
I'm making a site which follows this logic, but with images. I made this codepen to simplify since my code is awfully complicated and there's tons of unnecessary code.
I believe the problem is in the if($('body').hasClass('first')){if$(window).resize(function... etc; because the if seems to be ignored since the #glasses div is always gray/black if you resize your window.
Since I'm a beginner in Javascript I don't see anything wrong, in fact I just can't understand why something as simple as a if wouldn't work.
Any help is appreciated. Thanks!
var nums = ['first', 'second', 'third'];
var curr = 0;
$('.next, .prev').on('click', function(e) {
var offset = $(this).hasClass('prev') ? nums.length - 1 : 1;
curr = (curr + offset) % nums.length;
$('body').removeClass();
$('body').addClass(nums[curr]);
if ($('body').hasClass('first')) {
if ($(window).width() >= 1367) {
$("#glasses").css("background", "#000");
} else {
$("#glasses").css("background", "#666");
}
event.preventDefault();
} else if ($('body').hasClass('second')) {
if ($(window).width() >= 1367) {
$("#glasses").css("background", "#00f");
} else {
$("#glasses").css("background", "#66f");
}
event.preventDefault();
} else {
if ($(window).width() >= 1367) {
$("#glasses").css("background", "#f00");
} else {
$("#glasses").css("background", "#6ff");
}
event.preventDefault();
};
})
if ($('body').hasClass('first')) {
$(window).resize(function() {
if ($(window).width() >= 1367) {
$("#glasses").css("background", "#000");
} else {
$("#glasses").css("background", "#666");
}
})
} else if ($('body').hasClass('second')) {
$(window).resize(function() {
if ($(window).width() >= 1367) {
$("#glasses").css("background", "#00f");
} else {
$("#glasses").css("background", "#66f");
}
})
} else if ($('body').hasClass('third')) {
$(window).resize(function() {
if ($(window).width() >= 1367) {
$("#glasses").css("background", "f00");
} else {
$("#glasses").css("background", "6ff");
}
})
}
.slides-navigation a{
top: 50%;
position: fixed;
}
.prev{
left:30px;
position:absolute;
}
.next{
right: 45px;
position:absolute;
}
#glasses{
width: 50%;
height: 450px;
margin: 0 auto;
background: #000;
background-repeat: no-repeat;
background-position: 42% 86%;
}
.first{
border: #000 16px solid;
}
.second{
border: #00f 16px solid;
}
.third{
border: #f00 16px solid;
}
#media screen and (max-width:1367px){
.first{
border: #666 16px solid;
}
.second{
border: #66f 16px solid;
}
.third{
border: #6ff 16px solid;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<body class="first">
<div id="glasses"></div>
<nav class="slides-navigation desktop">
Prev>
Next
</nav>
</body>
If I understand the question correctly, the problem revolves around the $(window).resize functions being inside of the if statements, rather than the other way around.
It should look more like this:
$(window).resize(function() {
if ($('body').hasClass('first')) {
if ($(window).width() >= 1367) {
$("#glasses").css("background", "#000");
} else {
$("#glasses").css("background", "#666");
}
} else if ($('body').hasClass('second')) {
if ($(window).width() >= 1367) {
$("#glasses").css("background", "#00f");
} else {
$("#glasses").css("background", "#66f");
}
} else if ($('body').hasClass('third')) {
if ($(window).width() >= 1367) {
$("#glasses").css("background", "f00");
} else {
$("#glasses").css("background", "6ff");
}
}
});
Otherwise your code checks for for the body's class once, applies the resize function for only that class, and never knows to check again.
Your if statement
if ($('body').hasClass
Is only being run once, when the page loads.
You should move this into the next/prev event handler, so it re-calculates the resize event every time.
I need to avoid only first character value is - symbol in text box.
$(document).on("keypress", "#form_name", function() {
if ($('#form_name').val().substr(0, 1) == "-") {
return true
} else {
return false
}
});
I am trying this method it is not working properly.
Kindly guide me to resolve the issue.
You need to swap what you have given:
$(document).on("keyup", "#form_name", function() {
if ($('#form_name').val().substr(0, 1) == "-") {
$('#form_name').val("");
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="form_name" />
I have also added a small error message with this. Check it out:
$(".error").hide();
$(document).on("keyup", "#form_name", function() {
if ($('#form_name').val().substr(0, 1) == "-") {
$('#form_name').val("");
$(this).next(".error").fadeIn();
return false;
} else
$(this).next(".error").fadeOut();
});
.error {display: inline-block; vertical-align: middle; padding: 2px; border: 1px solid #f00; background: #f66; color: #fff; font-weight: bold; font-size: 0.8em; border-radius: 3px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="form_name" />
<span class="error">Cannot start with -.</span>
$(document).on("keyup", "#form_name", function() { //when a user types in input box
var formValue = this.value;
if ( formValue.charAt( 0 ) == '-' ) {
return false;
} else {
return true;
}
});