I need to add a class to a div on 12 different pages. Bellow is the code I've tried to use that don't work.
<script>
window.onload = init;
var divsWithClass = null;
function init() {
if (window.location.href.indexOf("page1") >= -1 &&
window.location.href.indexOf("page2") >= -1 &&
window.location.href.indexOf("page3/") >= -1 &&
window.location.href.indexOf("page4") >= -1 &&
) {
this.divsWithClass = document.getElementsByClassName("sub-menu");
var index = 0;
while (index < divsWithClass.length) {
divsWithClass[index].className += "et_pb_slide_dropdown_opened";
index++;
}
}
console.log(divsWithClass);
}
</script>
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Code bellow works fine, though as u can see, everything is hand wrote and if i want to push something to that arrays i will have to change whole code.
working example:
for (var s = 0; s < myButtons.length; s++) {
if (
(myButtons[s].className == "1" && colorIndex[0] > 1)
||
(myButtons[s].className == "2" && colorIndex[1] > 1)
||
(myButtons[s].className == "3" && colorIndex[2] > 1)
||
(myButtons[s].className == "4" && colorIndex[3] > 1)
||
(myButtons[s].className == "5" && colorIndex[4] > 1)
||
(myButtons[s].className == "6" && colorIndex[5] > 1)
) {continue;}
alert("things need to be done")
}
the best solution came to my mind(not working one):
for (var s = 0; s < myButtons.length; s++) {
for (var i = 0; i < colorIndex.length; i++) {
if ((myButtons[s].className == (i + 1) && colorIndex[i] > 1)) {
continue;
}
alert("things need to be done")
}
}
So what i want is: to check if all elements of array myButtons.classname==variable from cycle && colorIndex[variable from cycle]>1 OR same thing again but on next step
working code for the first algorithm
const colorIndex = []
colorIndex[0] = 201
colorIndex[1] = 30002
colorIndex[19] = -25
colorIndex[3] = 89
colorIndex[-7] = 89
colorIndex[-9] = -26
const myButtons = [...document.querySelectorAll("button")]
for (var s = 0; s < myButtons.length; s++)
{
if ( (myButtons[s].className == "1" && colorIndex[0] > 1)
|| (myButtons[s].className == "2" && colorIndex[1] > 1)
|| (myButtons[s].className == "3" && colorIndex[2] > 1)
|| (myButtons[s].className == "4" && colorIndex[3] > 1)
|| (myButtons[s].className == "5" && colorIndex[4] > 1)
|| (myButtons[s].className == "6" && colorIndex[5] > 1)
)
{ continue }
alert("things need to be done")
}
console.log('test ending')
<button class="1">1</button>
<button class="2">2</button>
<button class="4">3</button>
<button class="4">4</button>
<button class="4">5</button>
<button class="4">6</button>
<button class="4">7</button>
<button class="2">8</button>
<button class="4">9</button>
Here a pretty short and less hard coded version of the original code
var myButtons = document.querySelectorAll("button");
var colorIndex = [0, 1, 2, 0, 2, 1];
for (var index = 0; index < myButtons.length; index++) {
if (myButtons[index].className == String(index + 1)
&& colorIndex[myButtons[index].className - 1] > 1) continue;
console.log("Button at index '" + index + "' needs to get fixed");
}
<button class="1">1</button>
<button class="2">2</button>
<button class="3">3</button>
<button class="4">4</button>
<button class="5">5</button>
<button class="6">6</button>
Full code attempt:
// Create Buttons Start
var buttonDom = document.getElementById("a1");
var buttonList = [],
buttonCount = 12;
while (buttonList.length < buttonCount) {
var newInput = document.createElement("input");
newInput.type = "button";
buttonList.push(newInput);
buttonDom.appendChild(newInput);
}
var randomList1 = [];
while (randomList1.length < buttonCount / 2) {
var random = Math.floor(Math.random() * buttonCount / 2) + 1;
if (randomList1.indexOf(random) === -1) randomList1.push(random);
}
var randomList2 = [];
while (randomList2.length < buttonCount / 2) {
var random = Math.floor(Math.random() * buttonCount / 2) + 1;
if (randomList2.indexOf(random) === -1) randomList2.push(random);
}
randomList1.forEach((random, index) => buttonList[index].setAttribute("class", random));
randomList2.forEach((random, index) => buttonList[index + buttonCount / 2].setAttribute("class", random));
// Game Start
var myButtons = document.querySelectorAll("input[type='button']");
var click = 1;
var colorIndex = "0".repeat(6).split("").map(Number);
var color = ["red", "blue", "green", "black", "gold", "grey"];
myButtons.forEach(button => button.addEventListener("click", game));
function clickTrun() {
click = !click | 0;
}
function win() {
if (colorIndex.every(i => i == 2)) {
alert("YOU WON mdfker!");
location.reload();
}
}
function resetColorIndex() {
if (click === 1) {
colorIndex = colorIndex.map(function(colorValue) {
return colorValue < 2 ? 0 : colorValue;
});
}
}
function mainGameRules() {
setTimeout(function() {
resetColorIndex();
if (click === 1) {
myButtons.forEach(function(button) {
if (colorIndex[button.className - 1] > 1) return;
button.setAttribute("style", "background-color: none;");
button.disabled = false;
});
}
}, 700);
}
function game() {
this.disabled = true;
var index = this.className - 1;
if (index in colorIndex) {
this.setAttribute("style", "background-color:" + color[index]);
colorIndex[index]++;
mainGameRules();
clickTrun();
}
win();
}
<div id="a1">
</div>
You just need to formulate what you want to do and express it in code. Without sticking to concrete index, try to figure out how any possible index corresponds to particular color. Looking at your example you want to take className for every button, subtract 1 and take color from colorIndex and do something if that color is less than or equal to 1
for (let i = 0; i < myButtons.length; i++) {
// className for current button
const className = myButtons[i].className
// parse it into number
const num = Number(className)
// if number is valid, take element from colorIndex at number-1 position
// and see if that's not bigger than 1
if (num && colorIndex[num - 1] <= 1) {
console.log('things need to be done for index ' + i)
}
}
but my suggestion would be to reconsider your existing setup with myButtons and colorIndex into something more sophisticated
The concept is simliar to a slider. Here is the JsFiddle
Each section is set to:
visibility: hidden;
until assigned the "anim-in" class. The issue is with var $currSection and $nextSection that need the var $rightCounter to correctly evaluate.
var $currSection = $rightCounter;
var $nextSection = $rightCounter + 1;
$rightCounter is updated in the counter function:
function counter (event){
var $counterSelect = $(this).attr('id');
if ( $counterSelect == "right") {
if ( $rightCounter >= 0 && $rightCounter <= 4){
$rightCounter += 1;
console.log($rightCounter);
if ($leftCounter <= 0) {
$leftCounter = 0;
console.log($leftCounter);
}
else {
$leftCounter -= 1;
console.log($leftCounter);
}
}
}
else {
if ($leftCounter >= 0 && $leftCounter <= 4){
$leftCounter += 1;
console.log($leftCounter);
if ($rightCounter <= 0) {
$rightCounter = 0;
console.log($rightCounter);
}
else {
$rightCounter -= 1;
console.log($rightCounter);
}
}
}
animOut();
return $rightCounter;
};
The animOut function uses $currSection and $nextSection to redistribute classes, but they are not updating with the $rightCounter?
Note: the console logs are there to show what the vars are evaluating to
I finished coding Conway's Game of Life in JavaScript and HTML table.
logic cells in a table will be assigned with unique id's and based on the id operations(based 4 rules) take place.
You can find the working code at Codepen or i have put the code below.
The thing is it works well with any number of rows and 9 columns and if more than 9 columns are given their wont be unique id's so it works in undesired manner.
Query Is their a way where i can assign the whole table with unique id's.
Code block tableInitialization is the initialization part.
(function(){
$(document).ready(function(){
var column = "", appendRow = "", inc = 1, selectedCells = [], toRemoveClass = [], toAddClass = [], maxValue;
var tableInitialization = function(noOfRow, noOfColumn){
for(var row=1; row<=noOfRow; row++){
for(var col=1; col<=noOfColumn; col++){
column += "<td id =" + inc+col + "> </td>";
}
appendRow += "<tr>"+column+"</tr>";
column= "";
inc++;
}
$(".table").append(appendRow);
};
$("#submit").click(function(data){
var noOfRow = parseInt($("#rowNo").val());
var noOfColumn = parseInt($("#columnNo").val());
maxValue = parseInt(noOfRow.toString() + noOfColumn.toString());
if(isNaN(noOfRow) || isNaN(noOfColumn)){
alert("Please enter number");
} else {
tableInitialization(noOfRow, noOfColumn);
$("#container").hide();
$("td").click( function(data){
selectedCells.push(parseInt(this.id));
$(this).addClass("valid");
});
}
});
var checkAgain = function(selectedCells){
var check = 0, toBeReplaced = [], inArray = [], livingCell;
var currentNumber = 0;
var north, northEast, East, southEast, south, southWest, west, northWest;
for(var i=0; i<selectedCells.length; i++){
check = 0;
currentNumber = parseInt(selectedCells[i]);
if($("#"+(currentNumber)).hasClass("valid")){
livingCell = true;
} else {
livingCell = false;
}
if(currentNumber > 0 && currentNumber < maxValue){
/*North*/
if((currentNumber-10) > 0 && (currentNumber-10) < maxValue){
if($("#"+(currentNumber-10)).hasClass("valid")){
check ++;
}
}
/*North East*/
if((currentNumber-9) > 0 && (currentNumber-9) < maxValue){
if($("#"+(currentNumber-9)).hasClass("valid")){
check ++;
}
}
/*East*/
if((currentNumber+1) > 0 && (currentNumber+1) < maxValue){
if($("#"+(currentNumber+1)).hasClass("valid")){
check ++;
}
}
/*South East*/
if((currentNumber+11) > 0 && (currentNumber+11) < maxValue){
if($("#"+(currentNumber+11)).hasClass("valid")){
check ++;
}
}
/*South*/
if((currentNumber+10) > 0 && (currentNumber+10) < maxValue){
if($("#"+(currentNumber+10)).hasClass("valid")){
check ++;
}
}
/*South West*/
if((currentNumber+9) > 0 && (currentNumber+9) < maxValue){
if($("#"+(currentNumber+9)).hasClass("valid")){
check ++;
}
}
/*West*/
if((currentNumber-1) > 0 && (currentNumber-1) < maxValue){
if($("#"+(currentNumber-1)).hasClass("valid")){
check ++;
}
}
/*North West*/
if((currentNumber-11) > 0 && (currentNumber-11) < maxValue){
if($("#"+(currentNumber-11)).hasClass("valid")){
check ++;
}
}
if(livingCell){
if(check === 0 || check === 1 ){
if(toRemoveClass.indexOf(currentNumber) == -1){
toRemoveClass.push(currentNumber);
}
}
if(check == 4 || check == 5 || check == 6 || check == 7 || check == 8 ){
if(toRemoveClass.indexOf(currentNumber) == -1){
toRemoveClass.push(currentNumber);
}
}
if(check == 2 || check == 3){
if(toAddClass.indexOf(currentNumber) == -1){
toAddClass.push(currentNumber);
}
}
} else {
if(check == 3){
if(toAddClass.indexOf(currentNumber) == -1){
toAddClass.push(currentNumber);
}
}
}
}
}
};
var gol = function(selectedCells){
var check = 0, inArray = [];
var currentNumber = 0, livingCell;
for(var i=0; i<selectedCells.length; i++){
toBeReplaced = [];
check = 0;
currentNumber = parseInt(selectedCells[i]);
if($("#"+(currentNumber)).hasClass("valid")){
livingCell = true;
} else {
livingCell = false;
}
if(currentNumber > 0 && currentNumber < maxValue){
/*North*/
if((currentNumber-10) > 0 && (currentNumber-10) < maxValue){
if($("#"+(currentNumber-10)).hasClass("valid")){
check ++;
}
if(toBeReplaced.indexOf((currentNumber-10)) == -1){
toBeReplaced.push(currentNumber-10);
}
}
/*North East*/
if((currentNumber-9) > 0 && (currentNumber-9) < maxValue){
if($("#"+(currentNumber-9)).hasClass("valid")){
check ++;
}
if(toBeReplaced.indexOf((currentNumber-9)) == -1){
toBeReplaced.push(currentNumber-9);
}
}
/*East*/
if((currentNumber+1) > 0 && (currentNumber+1) < maxValue){
if($("#"+(currentNumber+1)).hasClass("valid")){
check ++;
}
if(toBeReplaced.indexOf((currentNumber+1)) == -1){
toBeReplaced.push(currentNumber+1);
}
}
/*South East*/
if((currentNumber+11) > 0 && (currentNumber+11) < maxValue){
if($("#"+(currentNumber+11)).hasClass("valid")){
check ++;
}
if(toBeReplaced.indexOf((currentNumber+11)) == -1){
toBeReplaced.push(currentNumber+11);
}
}
/*South*/
if((currentNumber+10) > 0 && (currentNumber+10) < maxValue){
if($("#"+(currentNumber+10)).hasClass("valid")){
check ++;
}
if(toBeReplaced.indexOf((currentNumber+10)) == -1){
toBeReplaced.push(currentNumber+10);
}
}
/*South West*/
if((currentNumber+9) > 0 && (currentNumber+9) < maxValue){
if($("#"+(currentNumber+9)).hasClass("valid")){
check ++;
}
if(toBeReplaced.indexOf((currentNumber+9)) == -1){
toBeReplaced.push(currentNumber+9);
}
}
/*West*/
if((currentNumber-1) > 0 && (currentNumber-1) < maxValue){
if($("#"+(currentNumber-1)).hasClass("valid")){
check ++;
}
if(toBeReplaced.indexOf((currentNumber-1)) == -1){
toBeReplaced.push(currentNumber-1);
}
}
/*North West*/
if((currentNumber-11) > 0 && (currentNumber-11) < maxValue){
if($("#"+(currentNumber-11)).hasClass("valid")){
check ++;
}
if(toBeReplaced.indexOf((currentNumber-11)) == -1){
toBeReplaced.push(currentNumber-11);
}
}
if(livingCell){
if(check == 0 || check == 1 ){
if(toRemoveClass.indexOf(currentNumber) == -1){
toRemoveClass.push(currentNumber);
}
}
if(check == 4 || check == 5 || check == 6 || check == 7 || check == 8 ){
if(toRemoveClass.indexOf(currentNumber) == -1){
toRemoveClass.push(currentNumber);
}
}
if(check == 2 || check == 3){
if(toAddClass.indexOf(currentNumber) == -1){
toAddClass.push(currentNumber);
}
}
} else {
if(check == 3){
if(toAddClass.indexOf(currentNumber) == -1){
toAddClass.push(currentNumber);
}
}
}
}
checkAgain(toBeReplaced);
}
for(var i=0; i<toRemoveClass.length; i++){
$("#"+toRemoveClass[i]).removeClass("valid");
}
for(var i=0; i<toAddClass.length; i++){
$("#"+toAddClass[i]).addClass("valid");
}
toBeReplaced = toAddClass;
if(toAddClass.length == 0){
//exit
return;
} else {
setInterval(function(){
gol($.unique(toBeReplaced));
},1000);
}
selectedCells = [];
toAddClass =[];
toRemoveClass = [];
};
start = function(){
if(selectedCells.length == 0){
alert("select cell");
} else {
gol(selectedCells);
}
};
});
})();
body{
background: #BBDEFB ;
}
td {
width: 20px;
height: 20px;
background: #eee;
}
table {
cursor: default;
}
.valid {
background: #00BFA5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<title>Conways Game of Life</title>
<link rel="stylesheet" type="text/css" href="gameOfLife.css">
</head>
<body>
<h1><code>Conway's game of life</code></h1>
<div id="container">
<h2><code>enter row * columns</code></h2>
<form>
<code>row ★ column : </code>
<input id="rowNo" type="text"/> ★
<input id="columnNo" type="text"/>
</form>
<button id="submit"> Submit </button>
<br><br>
</div>
<table class="table"></table>
<br><br>
<button onClick="start()"> start </button>
<br><br>
<h2><code> Rules </code></h2>
<code>1. Any live cell with fewer than two live neighbours dies,
as if caused by underpopulation.</code><br>
<code>2. Any live cell with more than three live neighbours dies,
as if by overcrowding.</code><br>
<code>3. Any live cell with two or three live neighbours lives
on to the next generation.</code><br>
<code>4. Any dead cell with exactly three live neighbours becomes
a live cell.</code>
<script type="text/javascript" src="gameOfLife.js"></script>
</body>
</html>
Without digging really deep into your code. You build the IDs by using col and row index, so you'll get something like 11, 12, 13, 14, 15, ... 110, 111, 112 etc. for the first row. Without a delimiter the ID of the eleventh row first element would be 111 too. As soon as you use a kind of delimiter like '_' your IDs are unique: 1_1, 1_2 again.
for(var row=1; row<=noOfRow; row++){
for(var col=1; col<=noOfColumn; col++){
column += "<td id =" + inc+"_"+col + "> </td>";
/* you also could add data attributes:
data-row=\""+row+"\" data-col=\""+col+"\"
*/
}
appendRow += "<tr>"+column+"</tr>";
column= "";
inc++;
}
Looking into your code, I think you will get other problems, because there is a lot of code related to "10". For example: if((currentNumber-9) > 0 && (currentNumber-9) < maxValue){ - this won't work in case you'll have more than 9 rows. But fixing this would be a rewritten version of the complete game.
My javascript code:
var footer = document.getElementsByTagName('footer');
for (var i = 0; i < footer.length; ++i) {
var appendTo = footer[0].getElementsByTagName('p'); //get only the p in the first footer to select
if(language.indexOf('nl') <= -1 && location.href.indexOf("/") >= 0 && location.href.indexOf("/en/") <= -1) {
for (var i = 0; i < appendTo.length; ++i) {
appendTo[0].innerHTML += '<div class="language item switch en">english</div>';
}
} else if(language.indexOf('nl') == 0 && location.href.indexOf("/en/") >= 0 ) {
for (var i = 0; i < appendTo.length; ++i) {
appendTo[0].innerHTML += '<div class="language item switch nl">nederlands</div>';
}
} else {}
}
I don't get any console errors. I want to add a 'change language' button when a user is not on the correct language site. Where did I go wrong in my code?
the variable language isn't defined in your function. If you declare it, it seems to work fine.
var language = window.navigator.userLanguage || window.navigator.language;
language = language.split("-");
var footer = document.getElementsByTagName('footer');
for (var i = 0; i < footer.length; ++i) {
var appendTo = footer[0].getElementsByTagName('p'); //get only the p in the first footer to select
if(language.indexOf('nl') <= -1 && location.href.indexOf("/") >= 0 && location.href.indexOf("/en/") <= -1) {
for (var i = 0; i < appendTo.length; ++i) {
appendTo[0].innerHTML += '<div class="language item switch en">english</div>';
}
} else if(language.indexOf('nl') == 0 && location.href.indexOf("/en/") >= 0 ) {
for (var i = 0; i < appendTo.length; ++i) {
appendTo[0].innerHTML += '<div class="language item switch nl">nederlands</div>';
}
} else {}
}
Updated fiddle: http://jsfiddle.net/ecsuZ/2/
I'm having some issues with this. For some reason, updateCurrentItem is always called with the same parameter regardless.
function updatePromoList(query) {
query = query.toUpperCase();
clearCurrentList();
var numItems = 0;
currentItem = 0;
result_set = cached[query.charAt(0)][query.charAt(1)][query.charAt(2)];
for(i in result_set){
if(numItems >= NUMBER_MATCHES){
$("<li/>").html("<span style='color: #aaa'>Please try to limit your search results</span>").appendTo("#possibilities").mouseover(function(event){ updateCurrentItem(numItems+1); });
break;
}
promo = result_set[i];
found_number = false;
if (!promo.client)
found_number = (promo.prj_number.toString().substr(0,query.length) == query) ? true : false;
if (query.length >= MATCH_NAME) {
if(promo.prj_name && typeof promo.prj_name == 'string'){
found_name = promo.prj_name.toUpperCase().indexOf(query);
} else {
found_name = -1;
}
if (promo.client)
found_client = promo.client_name.toString().indexOf(query);
else
found_client = -1;
} else {
found_name = -1;
found_client = -1;
}
if(found_client >= 0) {
var thisIndex = numItems+1;
console.log("setting", thisIndex);
$("<li/>").text(promo.client_name).bind('click',function(e){ updatePromoChoice(e,promo); }).appendTo("#possibilities").mouseover(function(event){ updateCurrentItem(thisIndex); }); } else if(found_name >= 0 || found_number) { var thisIndex = numItems+1;
console.log("setting", thisIndex);
$("<li/>").text(promo.prj_number+": "+promo.prj_name).bind('click',function(e){ updatePromoChoice(e,promo); }).appendTo("#possibilities").mouseover(function(event){ updateCurrentItem(thisIndex); });
}
if(found_number || found_client >= 0 || found_name >= 0){
numItems++;
}
}
}
function updateCurrentItem(i){
currentItem = i;
console.log("updating to", i);
}
The results of running this are:
setting 0
setting 1
setting 2
setting 3
setting 4
setting 5
setting 6
setting 7
setting 8
setting 9
setting 10
setting 11
setting 12
setting 13
then when I move my mouse over the content area containing these <li>s with the mouseOver events, all I ever see is:
updating to 4
Always 4. Any ideas?
You're creating a closure but it's still bound to the numItems variable:
function(event){ updateCurrentItem(numItems+1); }
What you should do is something like this:
(function(numItems){return function(event){ updateCurrentItem(numItems+1); }})(numItems)
Edit: I think I might have the wrong function but the same principle applies:
function(event){ updateCurrentItem(thisIndex); }
should be
(function(thisIndex)
{
return function(event){ updateCurrentItem(thisIndex); }
})(thisIndex)