Issue with fly out menu using javascript - javascript

I have a menu that flies out, however it will not return to its original state.
let toggleNavStatus = function () {
let toggleNavStatus = true;
let getsidebar = document.querySelector(".sidebar");
if (toggleNavStatus === true) {
getsidebar.style.left = "0px";
} else if (toggleNavStatus === false) {
getsidebar.style.left = "-250px";
}
}

This should work:
let toggleStatus = false;
let toggleNav = function () {
let getsidebar = document.querySelector(".sidebar");
if (toggleStatus === true) {
getsidebar.style.left = "0px";
} else {
getsidebar.style.left = "-250px";
}
toggleStatus = !toggleStatus;
}

Related

How can I make my function work on Safari/iOS?

I have a javascript snippet that doesn't work properly on Safari / iOS and would like some help.
let coverageAtt1 = document.getElementById("att-check1");
let coverageAtt2 = document.getElementById("att-check2");
let coverageAtt3 = document.getElementById("att-check3");
let coverageAtt4 = document.getElementById("att-check4");
let checkboxes = [coverageAtt1, coverageAtt2, coverageAtt3, coverageAtt4];
let attributeCond = [];
let coverageCond = '';
for (let checkbox of checkboxes) {
checkbox.oninput = function() {updateAtt()};
function updateAtt() {
if (checkbox.checked) {
attributeCond.push(checkbox.value);
}
else if (attributeCond.includes(checkbox.value)) {
attributePosition = attributeCond.indexOf(checkbox.value);
attributeCond.splice(attributePosition, 1);
}
else {
null;
}
console.log(attributeCond);
sliders();
}
}
function sliders() {
filteredPlans = plans.filter((item) => {
if (attributeCond.length == 0) {
coverageCond = attributeCond.includes(item.coverage) == false;
}
else {
coverageCond = attributeCond.includes(item.coverage) == true;
}
return (coverageCond);
});
Opening the console in Safari states that the "checkbox" variable have not been declared/cannot be found.

I'm creating a game but the restart process is not what i want

This is my script:
const player = document.getElementById("gameChar");
const obstacle = document.getElementById('gameObst');
var isVisible = true
function Toggle() {
var num = 0;
player.classList.toggle("d-none");
isVisible = false;
setTimeout(function() {
player.classList.toggle("d-none");
isVisible = true;
// obstacle.style.animationName = "tweak";
}, 700)
// obstacle.style.animationName = ""
}
// var consditionstyle = condition
// var condition1 = document.getElementById("gameObst");
// condition = condition1.defaultView.getComputedStyle(gameObst, screenLeft = 30);
// console.log(condition);
// var condition1 = document.getElementById("gameObst");
// var getProperty = document.getComputedStyle("condition1");
// var getValue = getProperty.getPropertyValue("left")
// console.log(getValue);
// var el = document.getElementById('gameObst');
// var comp = el.currentStyle || getComputedStyle(el, null);
// alert(comp.left);
// if(comp.left == "675px"){
// console.log("yes");
// }else{
// console.log("no");
// }
var modal = document.querySelector(".mymodal");
function doesIntersect() {
const playerBounds = player.getBoundingClientRect();
const obstacleBounds = obstacle.getBoundingClientRect();
const intersectsFromRight = obstacleBounds.left < playerBounds.right
const intersectsFromLeft = obstacleBounds.right > playerBounds.left
if (intersectsFromRight && intersectsFromLeft && isVisible) {
// obstacle.style.animationName = "";
modal.classList.add("d-block");
console.log(obstacle);
obstacle.style.display = "none";
exit();
}
requestAnimationFrame(doesIntersect);
}
requestAnimationFrame(doesIntersect);
function dNone() {
// obstacle.style.animationName = "";
if (obstacle.style.animationName == "tweak") {
console.log("yes");
obstacle.style.left = "1350px";
obstacle.style.display = "block";
// obstacle.style.animationName.replace(tweak, nothing);
}
}
But for more reference this is a link to the game:
https://jsfiddle.net/Samuel_Emeka/894rLx31/1/
I want the modal for the game over to close when I click restart and restart the animation.
I've tried changing the animation name to another one, then on close of the modal add the animation name back but all to no avail. I'd like to get assistance with this soon. I hope so. Thanks

Need help completing a function for a Memory Card Game in JavaScript

I've been working on a school poject which consists of making a Memory Card Game, and I'm having trouble creating a function which tells me when all the cards have been correctly flipped (and thus the game has ended).
This is what I have so far in my scripts.js :
const cards = document.querySelectorAll('.memory-card');
let hasFlippedCard = false;
let lockBoard = false;
let firstCard, secondCard;
let allCardsFlipped = false;
function flipCard() {
if (lockBoard) return;
if (this === firstCard) return;
this.classList.add('flip');
if (!hasFlippedCard) {
hasFlippedCard = true;
firstCard = this;
return;
}
secondCard = this;
lockBoard = true;
checkForMatch();
}
function checkForMatch() {
let isMatch = firstCard.dataset.name === secondCard.dataset.name;
isMatch ? disableCards() : unflipCards();
}
function disableCards() {
firstCard.removeEventListener('click', flipCard);
secondCard.removeEventListener('click', flipCard);
resetBoard();
}
function unflipCards() {
setTimeout(() => {
firstCard.classList.remove('flip');
secondCard.classList.remove('flip');
resetBoard();
}, 1500);
}
function resetBoard() {
hasFlippedCard = false;
lockBoard = false;
firstCard = null;
secondCard = null;
}
function haveAllCardBeenFlipped(){
return allCardsFlipped = true
}
function gameWon(){
if (allCardsFlipped = true){
window.location.href = 'vitoria.html'
}
else {
break
}
}
(function shuffle() {
cards.forEach(card => {
let ramdomPos = Math.ceil(Math.random() * 12);
card.style.order = ramdomPos;
});
})();
cards.forEach(card => card.addEventListener('click', flipCard));
My question now is what do I write in the function haveAllCardsBeenFlipped so that it checks if the cards have been flipped and returns True if the condition has been met, otherwise breaks.
You just need to iterate through all of the cards and check if all of them has flip class or not. That should give you your answer.
function haveAllCardBeenFlipped(){
let allCardFlipped = true;
cards.forEach(card => {
if(card.classList.contains('flip')) {
allCardFlipped = false;
break;
}
});
return allCardsFlipped;
}
I'd use the every array method to do this. You can create an array from the result of querySelectorAll with Array.from.
function haveAllCardBeenFlipped(){
return Array.from(cards).every(card => card.classList.contains('flip'));
}

Restart a function if there is no click, or touch event on screen

I found this code on net, it's about a memory game.
var MemoryApp = (function () {
'use strict';
var size = 36;
var sizeStyle = "smallGame";
var maxpics = 18;
var gameRunning = false;
var cardOpen = null;
var time = 0;
var timer;
var s4;
var s6;
var s8;
var attempts = 0;
var found = 0;
var foundDisp;
var attDisp;
var timeDisp;
var template;
var popupImage;
var popupHolder;
var gameGrid;
var currentCardSet = 'zoo';
var currentCards = [];
window.onload = runGame;
function activated() {
WinJS.UI.processAll().then(function(){
s4 = document.getElementById("size4x4");
s6 = document.getElementById("size6x6");
s8 = document.getElementById("size8x8");
s4.addEventListener("click", gameSize, false);
s6.addEventListener("click", gameSize, false);
s8.addEventListener("click", gameSize, false);
var start = document.getElementById("startGame");
if (start) {
start.onclick = runGame;
}
var stop = document.getElementById("stopGame");
if (stop) {
stop.onclick = stopGame;
}
template = document.getElementById("cardTemplate");
popupImage = document.getElementById("popupImage");
popupHolder = document.getElementById("popupHolder");
popupHolder.addEventListener("click", closeImageView, false);
foundDisp = document.getElementById("foundDisplay");
attDisp = document.getElementById("attemptsDisplay");
timeDisp = document.getElementById("timeDisplay");
// Expose functions globally
window.updateClock = updateClock;
window.resetCards = resetCards;
window.gameTag1 = null;
window.gameTag2 = null;
buildCards();
});
}
function closeImageView() {
removeClass(popupHolder, "openImagePopup");
}
function makePictureArray() {
var pics = new Array();
for (var i = 0; i < maxpics; i++) {
pics[i] = getDefaultURL(i);
}
return pics;
}
function removeAllChildren(element) {
if (element.hasChildNodes()) {
while (element.childNodes.length > 0) {
element.removeChild(element.firstChild);
}
}
}
function buildCards() {
// Assumption: game grid size is a power of 2
var stride = Math.sqrt(size);
// Make picture selection
var pics = makePictureArray();
var sel = new Array();
for (var i = 0; i < size / 2; i++) {
var idx = parseInt(Math.random() * pics.length);
sel[i] = pics[idx];
// remove the used pic
pics.splice(idx, 1);
}
// get an array with the card content
var content = new Array();
for (var i = 0; i < size / 2; i++) {
content[i] = sel[i];
content[i + size / 2] = sel[i];
}
var gameBoard = document.querySelector('#gameBoard');
removeAllChildren(gameBoard);
var gameGrid = document.createElement("div");
gameGrid.id = "gameGrid";
addClass(gameGrid, sizeStyle);
gameBoard.appendChild(gameGrid);
for (var i=0; i<size; i++) {
var item = document.createElement("div");
item.className = "gameItem"+i;
item.addEventListener("click", cardClicked, false);
setClosed(item);
var r = parseInt(Math.random() * content.length);
// Add image
insertTemplate(item, template);
var walker = document.createTreeWalker(item, NodeFilter.SHOW_ELEMENT, imgFilter, false);
while (walker.nextNode())
walker.currentNode.setAttribute("src", content[r]);
// Add path to ease styling
var walker = document.createTreeWalker(item, NodeFilter.SHOW_ELEMENT, pFilter, false);
while (walker.nextNode())
walker.currentNode.innerText = content[r];
item.contentIndex = content[r];
content.splice(r, 1);
gameGrid.appendChild(item);
}
}
function imgFilter(node) {
if (node.tagName == "IMG") //filter IMG elements
return NodeFilter.FILTER_ACCEPT
else
return NodeFilter.FILTER_SKIP
}
function pFilter(node) {
if (node.tagName == "P") //filter IMG elements
return NodeFilter.FILTER_ACCEPT
else
return NodeFilter.FILTER_SKIP
}
function insertTemplate(parent, templateParent) {
if (templateParent.children && templateParent.children.length >= 1) {
var tchild = templateParent.children[0].cloneNode(true);
parent.appendChild(tchild);
}
}
function gameSize() {
document.size.size4x4.checked = false;
document.size.size6x6.checked = false;
document.size.size8x8.checked = false;
var newsize = 36;
var gSize = "smallGame";
if (this.name == "size4x4") {
document.size.size4x4.checked = true;
newsize = 36;
gSize = "smallGame";
}
if (this.name == "size6x6") {
document.size.size6x6.checked = true;
newsize = 36;
gSize = "mediumGame";
}
if (this.name == "size8x8") {
document.size.size8x8.checked = true;
newsize = 36;
gSize = "largeGame";
}
if (!gameRunning == true) {
size = newsize;
sizeStyle = gSize;
buildCards();
}
}
function stopGame() {
if (!gameRunning)
return;
gameRunning = false;
foundDisp.innerText = "0";
found = 0;
attDisp.innerText = "0";
attempts = 0;
clearInterval(timer);
timeDisp.innerText = "00:00";
s4.disabled = false;
s6.disabled = false;
s8.disabled = false;
}
function runGame() {
//don't do anything if game already running
if (gameRunning == true)
return;
window.gameTag1 = null;
window.gameTag2 = null;
cardOpen = null;
gameRunning = true;
buildCards();
timeDisp.innerText = "00:00";
time = 0;
foundDisp.innerText = "0";
found = 0;
attDisp.innerText = "0";
attempts = 0;
timer = setInterval("updateClock()", 1000);
s4.disabled = true;
s6.disabled = true;
s8.disabled = true;
}
function getDefaultURL(i) {
var idx = i+1;
if (idx<1)
idx = 1;
if (idx>32)
idx = 32;
var result = "/photos/" + currentCardSet + "/";
if (idx < 10)
result = result + "0";
result = result + idx.toString() + ".jpg";
return result;
}
function updateClock() {
time = time + 1;
var mins = parseInt(time / 60);
var secs = time - mins * 60;
mins = mins.toString();
secs = secs.toString();
if (mins.length < 2)
mins = "0" + mins;
if (secs.length < 2)
secs = "0" + secs;
timeDisp.innerText = mins + ":" + secs;
}
function cardClicked() {
// If an open card is clicked, bring up the full size popup
if (this.cardFoundFlag || cardOpen === this) {
popupImage.setAttribute("src", this.contentIndex);
popupHolder.style.display = "block";
addClass(popupHolder, "openImagePopup");
return;
}
// don't do anything if no game is running, or a move is in play...
if (!gameRunning || window.gameTag1 !=null || window.gameTag2 != null)
return;
if (cardOpen == null) {
setOpen(this);
cardOpen = this;
} else {
if (this.contentIndex == cardOpen.contentIndex) {
setFound(this);
setFound(cardOpen);
this.cardFoundFlag = true;
cardOpen.cardFoundFlag = true;
cardOpen = null;
found++;
foundDisp.innerText = found;
updateAttempts();
if (found == size / 2) {
gameRunning = false;
clearInterval(timer);
foundDisp.innerText = "ALL!";
}
} else {
setOpen(this);
// Hack to get around insulation of these functions
window.gameTag1 = this;
window.gameTag2 = cardOpen;
setTimeout("resetCards()", 1100);
cardOpen = null;
updateAttempts();
}
}
}
function setOpen(el) {
removeClass(el, "closedCard");
addClass(el, "openCard");
}
function setClosed(el) {
removeClass(el, "openCard");
addClass(el, "closedCard");
}
function setFound(el) {
removeClass(el, "openCard");
removeClass(el, "closedCard");
addClass(el, "foundCard");
}
function resetCardStyles(el) {
removeClass(el, "openCard");
removeClass(el, "foundCard");
addClass(el, "closedCard");
}
function updateAttempts() {
attempts++;
attDisp.innerText = attempts;
}
function resetAllCards() {
buildCards();
}
function resetCards() {
setClosed(window.gameTag1);
setClosed(window.gameTag2);
window.gameTag1 = null;
window.gameTag2 = null;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
// Utilities
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
function hasClass(el, className) {
// authors can pass in either an element object or an ID
el = (typeof (el) == 'object') ? el : document.getElementById(el);
// no need to continue if there's no className
if (!el.className) return false;
// iterate through all the classes
var classArray = el.className.split(' ');
for (var i = 0; i < classArray.length; i++) {
if (className == classArray[i]) return true; // found? return true
}
// if we're still here, the class does not exist
return false;
}
function addClass(el, className) {
// authors can pass in either an element object or an ID
el = (typeof (el) == 'object') ? el : document.getElementById(el);
// simply append the className to the string
el.className += ' ' + className;
return;
}
function removeClass(el, className) {
// authors can pass in either an element object or an ID
el = (typeof (el) == 'object') ? el : document.getElementById(el);
// if the class doesn't exist, there's no need to remove it
if (!hasClass(el, className)) return;
// iterate through all the classes
var classArray = el.className.split(' ');
for (var i = 0; i < classArray.length; i++) {
// found it!
if (className == classArray[i]) {
classArray.splice(i, 1); // remove it
i--; // decrement so we don't skip over any future occurences
}
}
// reassign the className
el.className = classArray.join(' ');
return;
}
WinJS.Application.onactivated = function (e) {
if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
activated();
}
}
WinJS.Application.start();
});
var theMemoryApp = new MemoryApp();
I need to add a function which is going to check for touch or click detection on the screen. If there is no touch after some seconds, all game has to restart from the beginning. How can I do that?
I hide that start and stop buttons on the design. So with window.onload=runGame game starts automatically when its loaded. But need to be restart if children live the game play when its not finished. For example, if there is no touch after 120 seconds, all code has to restart from beginning. Or there is buildCard function in the code. This timer can trigger this function also. I will be glad for any kind of help cause this is for kids.
You can use debounce technique like shown in below snippet. I have added click event but you can add touch specific events also. timer() will be triggered every 120 secs if click event is not triggered i.e if user doesn't click or touch. I could not run your code to test. Please let me know if this doesn't work.
var MemoryApp = (function () {
'use strict';
var size = 36;
var sizeStyle = "smallGame";
var maxpics = 18;
var gameRunning = false;
var cardOpen = null;
var time = 0;
var timer;
var s4;
var s6;
var s8;
var attempts = 0;
var found = 0;
var foundDisp;
var attDisp;
var timeDisp;
var template;
var popupImage;
var popupHolder;
var gameGrid;
var currentCardSet = 'zoo';
var currentCards = [],
__timeOut = 0;
window.onload = runGame;
var timer = function() {
clearTimeout(__timeOut);
__timeOut = setTimeout(function() {
buildCards();
}, 120000);
};
window.addEventListener('click', timer);
function activated() {
WinJS.UI.processAll().then(function(){
s4 = document.getElementById("size4x4");
s6 = document.getElementById("size6x6");
s8 = document.getElementById("size8x8");
s4.addEventListener("click", gameSize, false);
s6.addEventListener("click", gameSize, false);
s8.addEventListener("click", gameSize, false);
var start = document.getElementById("startGame");
if (start) {
start.onclick = runGame;
}
var stop = document.getElementById("stopGame");
if (stop) {
stop.onclick = stopGame;
}
template = document.getElementById("cardTemplate");
popupImage = document.getElementById("popupImage");
popupHolder = document.getElementById("popupHolder");
popupHolder.addEventListener("click", closeImageView, false);
foundDisp = document.getElementById("foundDisplay");
attDisp = document.getElementById("attemptsDisplay");
timeDisp = document.getElementById("timeDisplay");
// Expose functions globally
window.updateClock = updateClock;
window.resetCards = resetCards;
window.gameTag1 = null;
window.gameTag2 = null;
buildCards();
});
}
function closeImageView() {
removeClass(popupHolder, "openImagePopup");
}
function makePictureArray() {
var pics = new Array();
for (var i = 0; i < maxpics; i++) {
pics[i] = getDefaultURL(i);
}
return pics;
}
function removeAllChildren(element) {
if (element.hasChildNodes()) {
while (element.childNodes.length > 0) {
element.removeChild(element.firstChild);
}
}
}
function buildCards() {
// Assumption: game grid size is a power of 2
var stride = Math.sqrt(size);
// Make picture selection
var pics = makePictureArray();
var sel = new Array();
for (var i = 0; i < size / 2; i++) {
var idx = parseInt(Math.random() * pics.length);
sel[i] = pics[idx];
// remove the used pic
pics.splice(idx, 1);
}
// get an array with the card content
var content = new Array();
for (var i = 0; i < size / 2; i++) {
content[i] = sel[i];
content[i + size / 2] = sel[i];
}
var gameBoard = document.querySelector('#gameBoard');
removeAllChildren(gameBoard);
var gameGrid = document.createElement("div");
gameGrid.id = "gameGrid";
addClass(gameGrid, sizeStyle);
gameBoard.appendChild(gameGrid);
for (var i=0; i<size; i++) {
var item = document.createElement("div");
item.className = "gameItem"+i;
item.addEventListener("click", cardClicked, false);
setClosed(item);
var r = parseInt(Math.random() * content.length);
// Add image
insertTemplate(item, template);
var walker = document.createTreeWalker(item, NodeFilter.SHOW_ELEMENT, imgFilter, false);
while (walker.nextNode())
walker.currentNode.setAttribute("src", content[r]);
// Add path to ease styling
var walker = document.createTreeWalker(item, NodeFilter.SHOW_ELEMENT, pFilter, false);
while (walker.nextNode())
walker.currentNode.innerText = content[r];
item.contentIndex = content[r];
content.splice(r, 1);
gameGrid.appendChild(item);
}
}
function imgFilter(node) {
if (node.tagName == "IMG") //filter IMG elements
return NodeFilter.FILTER_ACCEPT
else
return NodeFilter.FILTER_SKIP
}
function pFilter(node) {
if (node.tagName == "P") //filter IMG elements
return NodeFilter.FILTER_ACCEPT
else
return NodeFilter.FILTER_SKIP
}
function insertTemplate(parent, templateParent) {
if (templateParent.children && templateParent.children.length >= 1) {
var tchild = templateParent.children[0].cloneNode(true);
parent.appendChild(tchild);
}
}
function gameSize() {
document.size.size4x4.checked = false;
document.size.size6x6.checked = false;
document.size.size8x8.checked = false;
var newsize = 36;
var gSize = "smallGame";
if (this.name == "size4x4") {
document.size.size4x4.checked = true;
newsize = 36;
gSize = "smallGame";
}
if (this.name == "size6x6") {
document.size.size6x6.checked = true;
newsize = 36;
gSize = "mediumGame";
}
if (this.name == "size8x8") {
document.size.size8x8.checked = true;
newsize = 36;
gSize = "largeGame";
}
if (!gameRunning == true) {
size = newsize;
sizeStyle = gSize;
buildCards();
}
}
function stopGame() {
if (!gameRunning)
return;
gameRunning = false;
foundDisp.innerText = "0";
found = 0;
attDisp.innerText = "0";
attempts = 0;
clearInterval(timer);
timeDisp.innerText = "00:00";
s4.disabled = false;
s6.disabled = false;
s8.disabled = false;
}
function runGame() {
//don't do anything if game already running
if (gameRunning == true)
return;
window.gameTag1 = null;
window.gameTag2 = null;
cardOpen = null;
gameRunning = true;
buildCards();
timeDisp.innerText = "00:00";
time = 0;
foundDisp.innerText = "0";
found = 0;
attDisp.innerText = "0";
attempts = 0;
timer = setInterval("updateClock()", 1000);
s4.disabled = true;
s6.disabled = true;
s8.disabled = true;
}
function getDefaultURL(i) {
var idx = i+1;
if (idx<1)
idx = 1;
if (idx>32)
idx = 32;
var result = "/photos/" + currentCardSet + "/";
if (idx < 10)
result = result + "0";
result = result + idx.toString() + ".jpg";
return result;
}
function updateClock() {
time = time + 1;
var mins = parseInt(time / 60);
var secs = time - mins * 60;
mins = mins.toString();
secs = secs.toString();
if (mins.length < 2)
mins = "0" + mins;
if (secs.length < 2)
secs = "0" + secs;
timeDisp.innerText = mins + ":" + secs;
}
function cardClicked() {
// If an open card is clicked, bring up the full size popup
if (this.cardFoundFlag || cardOpen === this) {
popupImage.setAttribute("src", this.contentIndex);
popupHolder.style.display = "block";
addClass(popupHolder, "openImagePopup");
return;
}
// don't do anything if no game is running, or a move is in play...
if (!gameRunning || window.gameTag1 !=null || window.gameTag2 != null)
return;
if (cardOpen == null) {
setOpen(this);
cardOpen = this;
} else {
if (this.contentIndex == cardOpen.contentIndex) {
setFound(this);
setFound(cardOpen);
this.cardFoundFlag = true;
cardOpen.cardFoundFlag = true;
cardOpen = null;
found++;
foundDisp.innerText = found;
updateAttempts();
if (found == size / 2) {
gameRunning = false;
clearInterval(timer);
foundDisp.innerText = "ALL!";
}
} else {
setOpen(this);
// Hack to get around insulation of these functions
window.gameTag1 = this;
window.gameTag2 = cardOpen;
setTimeout("resetCards()", 1100);
cardOpen = null;
updateAttempts();
}
}
}
function setOpen(el) {
removeClass(el, "closedCard");
addClass(el, "openCard");
}
function setClosed(el) {
removeClass(el, "openCard");
addClass(el, "closedCard");
}
function setFound(el) {
removeClass(el, "openCard");
removeClass(el, "closedCard");
addClass(el, "foundCard");
}
function resetCardStyles(el) {
removeClass(el, "openCard");
removeClass(el, "foundCard");
addClass(el, "closedCard");
}
function updateAttempts() {
attempts++;
attDisp.innerText = attempts;
}
function resetAllCards() {
buildCards();
}
function resetCards() {
setClosed(window.gameTag1);
setClosed(window.gameTag2);
window.gameTag1 = null;
window.gameTag2 = null;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
// Utilities
//
//////////////////////////////////////////////////////////////////////////////////////////////////////
function hasClass(el, className) {
// authors can pass in either an element object or an ID
el = (typeof (el) == 'object') ? el : document.getElementById(el);
// no need to continue if there's no className
if (!el.className) return false;
// iterate through all the classes
var classArray = el.className.split(' ');
for (var i = 0; i < classArray.length; i++) {
if (className == classArray[i]) return true; // found? return true
}
// if we're still here, the class does not exist
return false;
}
function addClass(el, className) {
// authors can pass in either an element object or an ID
el = (typeof (el) == 'object') ? el : document.getElementById(el);
// simply append the className to the string
el.className += ' ' + className;
return;
}
function removeClass(el, className) {
// authors can pass in either an element object or an ID
el = (typeof (el) == 'object') ? el : document.getElementById(el);
// if the class doesn't exist, there's no need to remove it
if (!hasClass(el, className)) return;
// iterate through all the classes
var classArray = el.className.split(' ');
for (var i = 0; i < classArray.length; i++) {
// found it!
if (className == classArray[i]) {
classArray.splice(i, 1); // remove it
i--; // decrement so we don't skip over any future occurences
}
}
// reassign the className
el.className = classArray.join(' ');
return;
}
WinJS.Application.onactivated = function (e) {
if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
activated();
}
}
WinJS.Application.start();
});
var theMemoryApp = new MemoryApp();

Adding class to javascript selector?

createDocumentStructure('h3, .twistytext'); is the line I am having problems with - last line.
It works if I just have h3 in there but wanted to add a class too. Tried a bunch of different ways to syntax the class in but nothing is working. So I want the expand/collapse to be <div> then <h3 class="twistytext">.
// JavaScript Document
var collapseDivs, collapseLinks;
function createDocumentStructure(tagName) {
if (document.getElementsByTagName) {
var elements = document.getElementsByTagName(tagName);
collapseDivs = new Array(elements.length);
collapseLinks = new Array(elements.length);
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
var siblingContainer;
if (document.createElement && (siblingContainer = document.createElement('div')) && siblingContainer.style) {
var nextSibling = element.nextSibling;
element.parentNode.insertBefore(siblingContainer, nextSibling);
var nextElement = elements[i + 1];
while (nextSibling != nextElement && nextSibling != null) {
var toMove = nextSibling;
nextSibling = nextSibling.nextSibling;
siblingContainer.appendChild(toMove);
}
siblingContainer.style.display = 'none';
collapseDivs[i] = siblingContainer;
createCollapseLink(element, siblingContainer, i);
} else {
// no dynamic creation of elements possible
return;
}
}
createCollapseExpandAll(elements[0]);
}
}
function createCollapseLink(element, siblingContainer, index) {
var div;
if (document.createElement && (div = document.createElement('div'))) {
div.appendChild(document.createTextNode(String.fromCharCode(160)));
var imge = document.createElement('img');
imge.src = 'https://smartsales.thomsonreuters.com/library/template/cssfiles/gsam/expand.jpg';
imge.setAttribute('width', '20px');
imge.setAttribute('height', '20px');
imge.setAttribute('class', 'imge')
imge.alt = 'Expand';
var link = document.createElement('a');
link.collapseDiv = siblingContainer;
link.href = '#';
link.appendChild(imge);
link.onclick = collapseExpandLink;
//link.onclick = removediv;
collapseLinks[index] = link;
div.appendChild(link);
element.appendChild(div);
}
}
function collapseExpandLink(evt) {
if (this.collapseDiv.style.display == '') {
this.parentNode.parentNode.nextSibling.style.display = 'none';
this.firstChild.alt = 'expand';
this.firstChild.src = 'https://smartsales.thomsonreuters.com/library/template/cssfiles/gsam/expand.jpg';
} else {
this.parentNode.parentNode.nextSibling.style.display = '';
var imgc = document.createElement('img');
imgc.src = 'https://smartsales.thomsonreuters.com/library/template/cssfiles/gsam/collapse.jpg';
imgc.setAttribute('width', '20px');
imgc.setAttribute('height', '20px');
imgc.setAttribute('class', 'imge')
imgc.alt = 'Collapse';
this.firstChild.src = 'https://smartsales.thomsonreuters.com/library/template/cssfiles/gsam/collapse.jpg';
this.firstChild.alt = 'Collapse';
// this.firstChild.setAttribute("src","collapse-eikon.jpg");
}
if (evt && evt.preventDefault) {
evt.preventDefault();
}
return false;
}
function createCollapseExpandAll(firstElement) {
var div;
if (document.createElement && (div = document.createElement('div'))) {
var link = document.createElement('a');
link.setAttribute('class', 'expanderall');
link.href = '#';
link.appendChild(document.createTextNode('Expand all'));
link.onclick = expandAll;
div.appendChild(link);
div.appendChild(document.createTextNode(' '));
link = document.createElement('a');
link.setAttribute('class', 'expanderall');
link.href = '#';
link.appendChild(document.createTextNode('Collapse all'));
link.onclick = collapseAll;
div.appendChild(link);
firstElement.parentNode.insertBefore(div, firstElement);
}
}
function expandAll(evt) {
for (var i = 0; i < collapseDivs.length; i++) {
collapseDivs[i].style.display = '';
collapseLinks[i].firstChild.src = 'https://smartsales.thomsonreuters.com/library/template/cssfiles/gsam/collapse.jpg';
}
if (evt && evt.preventDefault) {
evt.preventDefault();
}
return false;
}
function collapseAll(evt) {
for (var i = 0; i < collapseDivs.length; i++) {
collapseDivs[i].style.display = 'none';
collapseLinks[i].firstChild.src = 'https://smartsales.thomsonreuters.com/library/template/cssfiles/gsam/expand.jpg';
}
if (evt && evt.preventDefault) {
evt.preventDefault();
}
return false;
}
window.onload = function (evt) {
createDocumentStructure('h3, .twistytext');
}
in your function
function createDocumentStructure(tagName) {
change to
function createDocumentStructure(tagName,className) {
and in that function add code
if(className)
{
elements.className = className;
}
for more detail refer Change an element's class with JavaScript

Categories