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
Related
I have written some javascript code for a multilanguage site. The code works great but I feel like I have a lot of duplicate code. I was wondering if someone can explain how I can make this simpler or minimized. I have tried to use a forEach(function (item, index) but it does not seem to be working.
This is the original code that works....
(function () {
var lang1 = "/en/"; //default language
var lang2 = "/fr/"; //second language
var lang3 = "/es/"; //third language
var languageSwitcher = document.querySelectorAll("a[href='/languages']").forEach((el) => el.parentNode.classList.add("language-switcher"));
document.querySelector("[data-folder='/languages']").classList.add("language-switcher");
document.querySelectorAll(".language-switcher .header-nav-folder-item").forEach((el) => el.classList.add("languages"));
document.querySelectorAll(".language-switcher .header-menu-nav-item:not(:first-child)").forEach((el) => el.classList.add("languages"));
var languages = document.querySelectorAll(".languages");
var language1 = document.querySelectorAll(".language-switcher .languages a[href*='"+lang1+"']");
var language2 = document.querySelectorAll(".language-switcher .languages a[href*='"+lang2+"']")
var language3 = document.querySelectorAll(".language-switcher .languages a[href*='"+lang3+"']")
var windowURL = window.location.href;
var pageURL = windowURL.split("/")[4];
if (pageURL == undefined) {
for (var i = 0; i < language1.length; i++) {
language1[i].onclick = function () {
var path = lang1 + "home";
this.href = path;
};
}
for (var i = 0; i < language2.length; i++) {
language2[i].onclick = function () {
var path = lang2 + "home";
this.href = path;
};
}
for (var i = 0; i < language3.length; i++) {
language3[i].onclick = function () {
var path = lang3 + "home";
this.href = path;
};
}
} else {
for (var i = 0; i < language1.length; i++) {
language1[i].onclick = function () {
var path = lang1 + pageURL;
this.href = path;
};
}
for (var i = 0; i < language2.length; i++) {
language2[i].onclick = function () {
var path = lang2 + pageURL;
this.href = path;
};
}
for (var i = 0; i < language3.length; i++) {
language3[i].onclick = function () {
var path = lang3 + pageURL;
this.href = path;
};
}
}
document.querySelectorAll(".header-nav-item:not(.language-switcher) a").forEach((el) => el.classList.add("language"));
document.querySelectorAll(".header-menu-nav-item:not(.language-switcher) a").forEach((el) => el.classList.add("language"));
document.querySelectorAll('[data-folder="/languages"] .header-menu-nav-item a').forEach((el) => el.classList.remove("language"));
var languageLinks = document.querySelectorAll(".language");
for (var i = 0; i < languageLinks.length; i++) {
var navURL = languageLinks[i].href;
if (windowURL.indexOf(lang1) != -1) {
languages.forEach((el) => el.classList.remove("active"));
languages[0].classList.add("active");
if (navURL.indexOf(lang1) != -1) {
languageLinks[i].closest("div").style.display = "block";
} else {
languageLinks[i].closest("div").style.display = "none";
}
} else if (windowURL.indexOf(lang2) != -1) {
languages.forEach((el) => el.classList.remove("active"));
languages[1].classList.add("active");
if (navURL.indexOf(lang2) != -1) {
languageLinks[i].closest("div").style.display = "block";
} else {
languageLinks[i].closest("div").style.display = "none";
}
} else if (windowURL.indexOf(lang3) != -1) {
if (navURL.indexOf(lang3) != -1) {
languages.forEach((el) => el.classList.remove("active"));
languages[2].classList.add("active");
languageLinks[i].closest("div").style.display = "block";
} else {
languageLinks[i].closest("div").style.display = "none";
}
} else {
if (navURL.indexOf(lang1) != -1) {
languages.forEach((el) => el.classList.remove("active"));
languages[0].classList.add("active");
languageLinks[i].closest("div").style.display = "block";
} else {
languageLinks[i].closest("div").style.display = "none";
}
}
}
var active = document.querySelector(".language-switcher .active");
active.closest(".language-switcher").prepend(active);
document.querySelectorAll(".header a").forEach((el) => (el.style.visibility = "visible"));
languageSwitcher.style.display = "flex";
})();
I have attempted to use a forEach function and an array but it is not working.
(function () {
var lang = ["/en/", "/fr/", "/es/"];
document.querySelectorAll("a[href='/languages']").forEach((el) => el.parentNode.classList.add("language-switcher"));
document.querySelector("[data-folder='/languages']").classList.add("language-switcher");
document.querySelectorAll(".language-switcher .header-nav-folder-item").forEach((el) => el.classList.add("languages"));
document.querySelectorAll(".language-switcher .header-menu-nav-item:not(:first-child)").forEach((el) => el.classList.add("languages"));
var languages = document.querySelectorAll(".languages");
var windowURL = window.location.href;
var pageURL = windowURL.split("/")[4];
lang.forEach(function (index, value) {
var language = document.querySelectorAll(".language-switcher .languages a[href*='" + value + "']");
if (pageURL == undefined) {
for (var i = 0; i < language.length; i++) {
language[i].onclick = function () {
var path = value + "home";
this.href = path;
};
}
} else {
for (var i = 0; i < language.length; i++) {
language[i].onclick = function () {
var path = value + pageURL;
this.href = path;
};
}
}
document.querySelectorAll(".header-nav-item:not(.language-switcher) a").forEach((el) => el.classList.add("language"));
document.querySelectorAll(".header-menu-nav-item:not(.language-switcher) a").forEach((el) => el.classList.add("language"));
document.querySelectorAll('[data-folder="/languages"] .header-menu-nav-item a').forEach((el) => el.classList.remove("language"));
var languageLinks = document.querySelectorAll(".language");
for (var j = 0; j < languageLinks.length; j++) {
var navURL = languageLinks[j].href;
if (windowURL.indexOf(value) != -1) {
languages.forEach((el) => el.classList.remove("active"));
languages[index].classList.add("active");
if (navURL.indexOf(value) != -1) {
languageLinks[j].closest("div").style.display = "block";
} else {
languageLinks[j].closest("div").style.display = "none";
}
} else {
if (navURL.indexOf('/en/') != -1) {
languages.forEach((el) => el.classList.remove("active"));
languages[0].classList.add("active");
languageLinks[j].closest("div").style.display = "block";
} else {
languageLinks[j].closest("div").style.display = "none";
}
}
}
document.querySelector(".header").style.visibility = "visible";
var active = document.querySelector(".language-switcher .active");
active.closest(".language-switcher").prepend(active);
});
})();
I look into a few answers but I'm not getting any results, I'm trying to fix this issue "Uncaught TypeError: this.getElements is not a function". This part of the code, full code in the link.
var SIDEBAR = new function() {
this.on = function(nameElement){
this.menu = nameElement;
return this;
};
/*more code*/
this.getElements = function() {
/*more code*/
return [];
};
/*more code*/
this.addElements = function() {
var elementsData = this.getElements();
/*more code*/
};
}();
var sid = SIDEBAR.on('test');
sid.load();
Full code: https://jsfiddle.net/e6shbnsu/
The value of this is determined by how a function is called.
this will point to window in setTimeout. Use .bind to have specified values as this context.
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
function inElectron() {
return navigator.userAgent.indexOf("Electron") != -1;
}
var dataManager = {
getItem: function(key, local) {
if (inElectron() || local == 1)
return localStorage.getItem(key);
else
return sessionStorage.getItem(key);
},
setItem: function(key, item, local) {
if (inElectron() || local == 1)
localStorage.setItem(key, item);
else
sessionStorage.setItem(key, item);
}
};
var SIDEBAR = new function() {
this.on = function(nameElement) {
this.menu = nameElement;
return this;
};
this.load = function() {
this.currentElement = 0;
this.refreshElements();
};
this.setAddElementName = function(name) {
this.addElementName = name;
};
this.setNewElementName = function(name) {
this.newElementName = name;
};
this.getElements = function() {
var elementsData = dataManager.getItem(this.getDataKey);
if (typeof elementsData !== 'undefined' && elementsData !== null) {
return JSON.parse(elementsData);
}
return this.getPreloadData();
};
this.setDataKey = function(key) {
this.dataKey = key;
};
this.getDataKey = function() {
if (this.dataKey) {
return this.dataKey;
}
return "SideBar" + this.menu;
};
this.setPreloadData = function(dataArray) {
this.preloadData = dataArray;
};
this.getPreloadData = function() {
if (typeof this.preloadData !== 'undefined' && this.preloadData !== null) {
return this.preloadData;
}
return [];
};
this.getCurrentElement = function() {
var elementsData = getElements;
return elementsData[currentElement];
};
this.refreshElements = function() {
window.setTimeout(function() {
this.clearElements();
}.bind(this), 1);
//outer `this` context is bound to the handler
window.setTimeout(function() {
this.addElements();
}.bind(this), 2);
};
this.deleteElement = function() {
var newArr = [];
var elementsData = this.getElements();
for (var i = 0, l = elementsData.length; i < l; i++) {
if (i != index) {
newArr.push(elementsData[i]);
}
}
dataManager.setItem(this.getDataKey, JSON.stringify(newArr));
};
this.addElements = function() {
var elementsData = this.getElements();
var menuNode = document.getElementById(this.menu);
console.log(elementsData);
for (var i = 0; i < elementsData.length; i++) {
var li = document.createElement("li");
var div = document.createElement("div");
li.value = i;
div.classList.add("list");
var p = document.createElement("p");
p.id = "textBlock";
p.style.display = "inline";
p.setAttribute("contentEditable", false);
p.appendChild(document.createTextNode(elementsData[i].name));
div.appendChild(p);
var obj = getObject();
console.log(obj);
div.onclick = function(e) {
e.stopImmediatePropagation();
if (this.querySelector("#textBlock").contentEditable == "false") {
this.currentElement = this.parentNode.value;
elementsData = this.getElements();
document.getElementById("prompt").innerHTML = elementsData[this.parentNode.value]["data"];
document.querySelector("#wrapper").classList.toggle("toggled");
}
};
var span2 = document.createElement("span");
span2.id = "deleteMode";
span2.classList.add("glyphicon");
span2.classList.add("glyphicon-minus");
span2.onclick = function(e) {
e.stopImmediatePropagation();
deleteItem(this.parentNode.parentNode.value);
window.setTimeout(this.refreshElements, 1);
};
span2.style.display = "none";
div.appendChild(span2);
var span = document.createElement("span");
span.id = "editMode";
span.classList.add("glyphicon");
span.classList.add("glyphicon-pencil");
span.onclick = function(e) {
e.stopImmediatePropagation();
// get href of first anchor in element and change location
for (var j = 0; j < menuNode.length; j++) {
menuNode[j].classList.add("disabled");
}
this.style.display = "none";
this.parentNode.querySelector("#deleteMode").style.display = "";
this.parentNode.classList.add("editableMode");
this.parentNode.classList.remove("disabled");
var textBlock = this.parentNode.querySelector("#textBlock");
textBlock.setAttribute("contentEditable", true);
this.placeCaretAtEnd(textBlock);
textBlock.onkeydown = function(e) {
if (e.keyCode == 13) {
e.stopImmediatePropagation();
var text = this.innerHTML.replace(" ", '');
text = text.replace("<br>", '');
if (text.length > 0) {
this.innerHTML = text;
elementsData[this.parentNode.parentNode.value]['name'] = text;
dataManager.setItem("IFTeleprompterScripts", JSON.stringify(elementsData));
for (var j = 0; j < menuNode.length; j++) {
menuNode[j].classList.remove("disabled");
}
this.parentNode.classList.remove("editableMode");
this.setAttribute("contentEditable", false);
this.parentNode.querySelector("#editMode").style.display = "";
this.parentNode.querySelector("#deleteMode").style.display = "none";
} else {
return false;
}
} else if (e.keyCode == 8) {
if (textBlock.innerHTML.length - 1 === 0) {
textBlock.innerHTML = " ";
}
}
return true;
};
return false;
};
div.appendChild(span);
li.appendChild(div);
scriptsNode.appendChild(li);
}
var li = document.createElement("li");
var div = document.createElement("div");
var span2 = document.createElement("span");
span2.id = "addMode";
span2.classList.add("glyphicon");
span2.classList.add("glyphicon-plus");
div.appendChild(span2);
var p = document.createElement("p");
p.id = "textBlock";
p.style.display = "inline";
p.setAttribute("contentEditable", false);
if (typeof this.addElementName !== 'undefined' && this.addElementName !== null)
p.appendChild(document.createTextNode(" " + this.addElementName));
else
p.appendChild(document.createTextNode(" Add " + this.menu));
div.appendChild(p);
li.onclick = function(e) {
e.stopImmediatePropagation();
var newPushElementName = "New " + this.menu;
if (typeof this.addElementName !== 'undefined' && this.addElementName !== null) {
newPushElementName = this.addElementName;
}
elementsData.push({
"name": newPushElementName,
"data": ""
});
dataManager.setItem(this.getDataKey, JSON.stringify(elementsData));
this.refreshElements();
};
li.appendChild(div);
menuNode.appendChild(li);
};
this.placeCaretAtEnd = function(el) {
el.focus();
if (typeof window.getSelection != "undefined" && typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
};
}();
var sid = SIDEBAR.on('test');
sid.load();
<ul class="sidebar-nav" id="test">
</ul>
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();
In my below, it works fine upto IE9, but not in IE10+:
function createList() {
try {
var listObj = document.getElementById('dialedList');
//document.getElementById('dialedDiv').style.display = "inline";
var list = opener.dialedNumbers; // This is array
//alert("list : "+list);
for (var i = 0; i < list.length; i++) {
//alert(list[i])
if (list[i] != undefined && list[i] != null && list[i] != "") {
alert("come");
var li = document.createElement("<li>");
alert("not come");
li.innerHTML = list[i];
li.onclick = function () {
//alert(this);
document.getElementById('screen').value = this.innerHTML;
document.getElementById('screen').focus();
};
li.onmouseover = function () {
this.style.backgroundColor = "#719FE5";
this.focus();
};
li.onmouseout = function () {
this.style.backgroundColor = "white";
this.focus();
};
listObj.appendChild(li);
}
}
} catch (e) {
alert(e.description);
alert(e.message);
}
}
createElement doesn't accept HTML, it accepts an element name ("tag name"). So you don't include the angle brackets:
var li = document.createElement("li");
If you've had other browsers accepting the previous version, they were just being tolerant.
I have a group of tabs that change the main panel when clicked on. In order to change a particular color property, I need to insert an additional div into my HTML. However, when I do so, it cause an error in the javascript. I'm not a javascript expert, but I think the reason is that the script is calling for an element in a particular order. So when I throw a new element into the picture, it loses its track. Here's my HTML. Basically all the items in the ul are always visible, and when you click on one, it makes the corresponding content visible:
<div id="TabbedPanels">
<div id="TabbedPanels1" class="VTabbedPanels">
<div class="TabbedPanelsContentGroup">
<div class="TabbedPanelsContent">1</div>
<div class="TabbedPanelsContent">2</div>
<div class="TabbedPanelsContent">3</div>
</div>
<ul class="TabbedPanelsTabGroup">
<li class="TabbedPanelsTab" tabindex="0">1</li>
<li class="TabbedPanelsTab" tabindex="0">2</li>
<li class="TabbedPanelsTab" tabindex="0">3</li>
</ul>
</div>
</div>
So now I want to slip a div around theTabbedPanelsContentGroup div, but like I said, it messes everything up. Here's the complete js:
var Spry;
if (!Spry) Spry = {};
if (!Spry.Widget) Spry.Widget = {};
Spry.Widget.TabbedPanels = function(element, opts)
{
this.element = this.getElement(element);
this.defaultTab = 0; // Show the first panel by default.
this.tabSelectedClass = "TabbedPanelsTabSelected";
this.tabHoverClass = "TabbedPanelsTabHover";
this.tabFocusedClass = "TabbedPanelsTabFocused";
this.panelVisibleClass = "TabbedPanelsContentVisible";
this.focusElement = null;
this.hasFocus = false;
this.currentTabIndex = 0;
this.enableKeyboardNavigation = true;
this.nextPanelKeyCode = Spry.Widget.TabbedPanels.KEY_RIGHT;
this.previousPanelKeyCode = Spry.Widget.TabbedPanels.KEY_LEFT;
Spry.Widget.TabbedPanels.setOptions(this, opts);
// If the defaultTab is expressed as a number/index, convert
// it to an element.
if (typeof (this.defaultTab) == "number")
{
if (this.defaultTab < 0)
this.defaultTab = 0;
else
{
var count = this.getTabbedPanelCount();
if (this.defaultTab >= count)
this.defaultTab = (count > 1) ? (count - 1) : 0;
}
this.defaultTab = this.getTabs()[this.defaultTab];
}
// The defaultTab property is supposed to be the tab element for the tab content
// to show by default. The caller is allowed to pass in the element itself or the
// element's id, so we need to convert the current value to an element if necessary.
if (this.defaultTab)
this.defaultTab = this.getElement(this.defaultTab);
this.attachBehaviors();
};
Spry.Widget.TabbedPanels.prototype.getElement = function(ele)
{
if (ele && typeof ele == "string")
return document.getElementById(ele);
return ele;
};
Spry.Widget.TabbedPanels.prototype.getElementChildren = function(element)
{
var children = [];
var child = element.firstChild;
while (child)
{
if (child.nodeType == 1 /* Node.ELEMENT_NODE */)
children.push(child);
child = child.nextSibling;
}
return children;
};
Spry.Widget.TabbedPanels.prototype.addClassName = function(ele, className)
{
if (!ele || !className || (ele.className && ele.className.search(new RegExp("\\b" + className + "\\b")) != -1))
return;
ele.className += (ele.className ? " " : "") + className;
};
Spry.Widget.TabbedPanels.prototype.removeClassName = function(ele, className)
{
if (!ele || !className || (ele.className && ele.className.search(new RegExp("\\b" + className + "\\b")) == -1))
return;
ele.className = ele.className.replace(new RegExp("\\s*\\b" + className + "\\b", "g"), "");
};
Spry.Widget.TabbedPanels.setOptions = function(obj, optionsObj, ignoreUndefinedProps)
{
if (!optionsObj)
return;
for (var optionName in optionsObj)
{
if (ignoreUndefinedProps && optionsObj[optionName] == undefined)
continue;
obj[optionName] = optionsObj[optionName];
}
};
Spry.Widget.TabbedPanels.prototype.getTabGroup = function()
{
if (this.element)
{
var children = this.getElementChildren(this.element);
if (children.length)
return children[1];
}
return null;
};
Spry.Widget.TabbedPanels.prototype.getTabs = function()
{
var tabs = [];
var tg = this.getTabGroup();
if (tg)
tabs = this.getElementChildren(tg);
return tabs;
};
Spry.Widget.TabbedPanels.prototype.getContentPanelGroup = function()
{
if (this.element)
{
var children = this.getElementChildren(this.element);
if (children.length > 1)
return children[0];
}
return null;
};
Spry.Widget.TabbedPanels.prototype.getContentPanels = function()
{
var panels = [];
var pg = this.getContentPanelGroup();
if (pg)
panels = this.getElementChildren(pg);
return panels;
};
Spry.Widget.TabbedPanels.prototype.getIndex = function(ele, arr)
{
ele = this.getElement(ele);
if (ele && arr && arr.length)
{
for (var i = 0; i < arr.length; i++)
{
if (ele == arr[i])
return i;
}
}
return -1;
};
Spry.Widget.TabbedPanels.prototype.getTabIndex = function(ele)
{
var i = this.getIndex(ele, this.getTabs());
if (i < 0)
i = this.getIndex(ele, this.getContentPanels());
return i;
};
Spry.Widget.TabbedPanels.prototype.getCurrentTabIndex = function()
{
return this.currentTabIndex;
};
Spry.Widget.TabbedPanels.prototype.getTabbedPanelCount = function(ele)
{
return Math.min(this.getTabs().length, this.getContentPanels().length);
};
Spry.Widget.TabbedPanels.addEventListener = function(element, eventType, handler, capture)
{
try
{
if (element.addEventListener)
element.addEventListener(eventType, handler, capture);
else if (element.attachEvent)
element.attachEvent("on" + eventType, handler);
}
catch (e) {}
};
Spry.Widget.TabbedPanels.prototype.cancelEvent = function(e)
{
if (e.preventDefault) e.preventDefault();
else e.returnValue = false;
if (e.stopPropagation) e.stopPropagation();
else e.cancelBubble = true;
return false;
};
Spry.Widget.TabbedPanels.prototype.onTabClick = function(e, tab)
{
this.showPanel(tab);
return this.cancelEvent(e);
};
Spry.Widget.TabbedPanels.prototype.onTabMouseOver = function(e, tab)
{
this.addClassName(tab, this.tabHoverClass);
return false;
};
Spry.Widget.TabbedPanels.prototype.onTabMouseOut = function(e, tab)
{
this.removeClassName(tab, this.tabHoverClass);
return false;
};
Spry.Widget.TabbedPanels.prototype.onTabFocus = function(e, tab)
{
this.hasFocus = true;
this.addClassName(tab, this.tabFocusedClass);
return false;
};
Spry.Widget.TabbedPanels.prototype.onTabBlur = function(e, tab)
{
this.hasFocus = false;
this.removeClassName(tab, this.tabFocusedClass);
return false;
};
Spry.Widget.TabbedPanels.KEY_UP = 38;
Spry.Widget.TabbedPanels.KEY_DOWN = 40;
Spry.Widget.TabbedPanels.KEY_LEFT = 37;
Spry.Widget.TabbedPanels.KEY_RIGHT = 39;
Spry.Widget.TabbedPanels.prototype.onTabKeyDown = function(e, tab)
{
var key = e.keyCode;
if (!this.hasFocus || (key != this.previousPanelKeyCode && key != this.nextPanelKeyCode))
return true;
var tabs = this.getTabs();
for (var i =0; i < tabs.length; i++)
if (tabs[i] == tab)
{
var el = false;
if (key == this.previousPanelKeyCode && i > 0)
el = tabs[i-1];
else if (key == this.nextPanelKeyCode && i < tabs.length-1)
el = tabs[i+1];
if (el)
{
this.showPanel(el);
el.focus();
break;
}
}
return this.cancelEvent(e);
};
Spry.Widget.TabbedPanels.prototype.preorderTraversal = function(root, func)
{
var stopTraversal = false;
if (root)
{
stopTraversal = func(root);
if (root.hasChildNodes())
{
var child = root.firstChild;
while (!stopTraversal && child)
{
stopTraversal = this.preorderTraversal(child, func);
try { child = child.nextSibling; } catch (e) { child = null; }
}
}
}
return stopTraversal;
};
Spry.Widget.TabbedPanels.prototype.addPanelEventListeners = function(tab, panel)
{
var self = this;
Spry.Widget.TabbedPanels.addEventListener(tab, "click", function(e) { return self.onTabClick(e, tab); }, false);
Spry.Widget.TabbedPanels.addEventListener(tab, "mouseover", function(e) { return self.onTabMouseOver(e, tab); }, false);
Spry.Widget.TabbedPanels.addEventListener(tab, "mouseout", function(e) { return self.onTabMouseOut(e, tab); }, false);
if (this.enableKeyboardNavigation)
{
// XXX: IE doesn't allow the setting of tabindex dynamically. This means we can't
// rely on adding the tabindex attribute if it is missing to enable keyboard navigation
// by default.
// Find the first element within the tab container that has a tabindex or the first
// anchor tag.
var tabIndexEle = null;
var tabAnchorEle = null;
this.preorderTraversal(tab, function(node) {
if (node.nodeType == 1 /* NODE.ELEMENT_NODE */)
{
var tabIndexAttr = tab.attributes.getNamedItem("tabindex");
if (tabIndexAttr)
{
tabIndexEle = node;
return true;
}
if (!tabAnchorEle && node.nodeName.toLowerCase() == "a")
tabAnchorEle = node;
}
return false;
});
if (tabIndexEle)
this.focusElement = tabIndexEle;
else if (tabAnchorEle)
this.focusElement = tabAnchorEle;
if (this.focusElement)
{
Spry.Widget.TabbedPanels.addEventListener(this.focusElement, "focus", function(e) { return self.onTabFocus(e, tab); }, false);
Spry.Widget.TabbedPanels.addEventListener(this.focusElement, "blur", function(e) { return self.onTabBlur(e, tab); }, false);
Spry.Widget.TabbedPanels.addEventListener(this.focusElement, "keydown", function(e) { return self.onTabKeyDown(e, tab); }, false);
}
}
};
Spry.Widget.TabbedPanels.prototype.showPanel = function(elementOrIndex)
{
var tpIndex = -1;
if (typeof elementOrIndex == "number")
tpIndex = elementOrIndex;
else // Must be the element for the tab or content panel.
tpIndex = this.getTabIndex(elementOrIndex);
if (!tpIndex < 0 || tpIndex >= this.getTabbedPanelCount())
return;
var tabs = this.getTabs();
var panels = this.getContentPanels();
var numTabbedPanels = Math.max(tabs.length, panels.length);
for (var i = 0; i < numTabbedPanels; i++)
{
if (i != tpIndex)
{
if (tabs[i])
this.removeClassName(tabs[i], this.tabSelectedClass);
if (panels[i])
{
this.removeClassName(panels[i], this.panelVisibleClass);
panels[i].style.display = "none";
}
}
}
this.addClassName(tabs[tpIndex], this.tabSelectedClass);
this.addClassName(panels[tpIndex], this.panelVisibleClass);
panels[tpIndex].style.display = "block";
this.currentTabIndex = tpIndex;
};
Spry.Widget.TabbedPanels.prototype.attachBehaviors = function(element)
{
var tabs = this.getTabs();
var panels = this.getContentPanels();
var panelCount = this.getTabbedPanelCount();
for (var i = 0; i < panelCount; i++)
this.addPanelEventListeners(tabs[i], panels[i]);
this.showPanel(this.defaultTab);
};
I think it could work if I could just figure out where in the js to bypass the new element I'm inserting. Thanks a lot.
You should be able to achieve styling, like changing some color without the need to resort to additional divs. Just add a class to the top div and change your css accordingly
If you currently initialize with Spry.Widget.TabbedPanels('TabbedPanels'), changing it to Spry.Widget.TabbedPanels('TabbedPanels1') should do the trick.. (if i understand your problem and edits correctly)
A simple solution is to put additional styles on each TabbedPanelsContent element. You can add the same children <div> for styling in each tab. For another solution, I have not tested this, but a change like the following might work:
Spry.Widget.TabbedPanels.prototype.getContentPanelGroup = function()
{
if (this.element)
{
var children = this.getElementChildren(this.element);
if (children.length > 1)
{
var subchildren = this.getElementChildren(children[0]);
return subchildren[0];
}
}
return null;
};