I have a for loop like this:
for(var i = 0; i < woord.length; i++) {
if(woord[i] === letter) {
goed = true;
woordContainer.innerHTML[i] = woord[i];
}
}
But the text in the woordContainer doesn't change on the page. I tried logging woord[i] to the console and it show the correct letter.
EDIT:
Let me share the complete code, so you can understand it better:
(it is a hangman game)
var store,
woord,
wrapper,
woordContainer,
letterInput,
gokButton,
pogingen,
pogingenText;
window.onload = function() {
store = new Persist.Store("galgje");
woord = store.get("woord");
pogingen = 10;
wrapper = document.getElementById("wrapper");
woordContainer = document.getElementById("woordContainer");
letterInput = document.getElementById("letterInput");
gokButton = document.getElementById("gokButton");
pogingenText = document.getElementById("pogingenText");
if (!woord) {
document.location.href = "./index.html";
}
for (var i = 0; i < woord.length; i++) {
woordContainer.innerHTML += ".";
}
wrapper.appendChild(woordContainer);
gokButton.onclick = function() {
var letter = letterInput.value.toLowerCase();
var goed = false;
if(letter) {
for(var i = 0; i < woord.length; i++) {
if(woord[i] === letter) {
goed = true;
woordContainer.innerHTML = woord[i];
}
}
if(!goed) {
pogingen--;
if(pogingen === 0) {
document.location.href = "./af.html";
}
pogingenText.innerHTML = "Pogingen: " + pogingen;
}
letterInput.value = "";
}
return false;
}
}
If you want to replace the character int woordContainer.innerHTML at index i, with the one in woord[i], you can do it like this:
if(woord[i] === letter) {
goed = true;
var temp = woordContainer.innerHTML
woordContainer.innerHTML = temp.substr(0, i) + woord[i] + temp.substr(i + woord[i].length);
}
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);
});
})();
How can an array value (could be any number less than 20K) be appended to a string?
I'm trying to imitate :
if (form1.EActQ20 === undefined) { Q2B0 = 0; }
else (Q2B0 = document.form1.EActQ20.value);
var und = x < 20000;
var less1 = form1.EActQ1.und.toString();
var less2 = form1.EActQ2.und.toString();
var less3 = form1.EActQ3.und.toString();
var less4 = form1.EActQ4.und.toString();
if (less1 === undefined) { Q1B.und.toString() = 0; }
else (Q1B.und.toString() = document.less1.value); /// is now a value to get added in an equation
if (less2 === undefined) { Q2B.und.toString() = 0; }
else (Q2B.und.toString() = document.less2.value);
if (less3 === undefined) { Q3B.und.toString() = 0; }
else (Q3B.und.toString() = document.less3.value);
if (less4 === undefined) { Q4B.und.toString() = 0; }
else (Q4B.und.toString() = document.less4.value);
/// Revised Code Below
arr = [];
var und = 0; // some number below 2000
var less = form1["EActQ1" + und];
if (less1 === undefined) {
arr[und] = 0;
} else {
arr[und] = document["less1" + und].value;
}
if (less2 === undefined) {
arr[und] = 0;
} else {
arr[und] = document["less2" + und].value;
}
if (less3 === undefined) {
arr[und] = 0;
} else {
arr[und] = document["less3" + und].value;
}
if (less1 === undefined) {
arr[und] = 0;
} else {
arr[und] = document["less1" + und].value;
}
add = (["Q1B"+ und] * 1)+(["Q2B"+ und] * 1)+(["Q3B"+ und] * 1)+(["Q4B"+ und] * 1);
Returns NaN. I'm defining cells based on their values and trying to add them up.
You seem to be looking for bracket notation:
var und = 0; // some number below 2000
var less = form1["EActQ" + und];
Also use an object to collect all those values, not a set of Q2B… variables. Or even better, just an array:
arr = [];
…
if (less === undefined) {
arr[und] = 0;
} else {
arr[und] = document["less" + und].value;
}
Recently i have used code in project that is still working it it http://kreditka.testovi-site.pw. But when i tried to reuse javascript the default rules js got broken and i got an error in console explaining that varibale cannot be found. Is it somehow related that sme o the code is not resusable and each line should be rewritten one by one for defferent projects?
(function () {
console.log("()");
"use strict";
var polosa = document.querySelector("#polosa");
alert(polosa);
var x = document.querySelectorAll("#slide1");
var o;
for (o = 0; o < x.length; o++) {
x[o].style.left = o*300+"px";
}
var x = document.querySelectorAll("#slide");
var a;
for (a = 0; a < x.length; a++) {
x[a].style.left = a*300+"px";
}
var doc = document.querySelectorAll('.btn-click');
for (var i = 0; i < doc.length; i++) {
doc[i].addEventListener("click", highlightThis, true);
}
var doc1 = document.querySelectorAll('.btn1-click');
for (var j = 0; j < doc.length; j++) {
doc1[j].addEventListener("click", highlightThis1, true);
}
var polosa = document.querySelector('#polosa');
polosa.style.left = '0px';
var left = 0;
var sliderItem = document.querySelector('#slide');
function highlightThis(event) {
console.log("highlightThis");
var currentActiveButton = document.querySelector(".btn-click.btn-slide-active");
currentActiveButton.classList.toggle("btn-slide-active");
event.target.classList.toggle("btn-slide-active");
console.log(event.target.dataset.value);
shiftSlide({
prev: currentActiveButton.dataset.value,
next: event.target.dataset.value
});
}
function highlightThis1(event) {
console.log("highlightThis1");
var currentActiveButton1 = document.querySelector(".btn1-click.btn-slide-active");
currentActiveButton1.classList.toggle("btn-slide-active");
event.target.classList.toggle("btn-slide-active");
console.log(event.target.dataset.value);
shiftSlide1({
prev: currentActiveButton1.dataset.value,
next: event.target.dataset.value
});
}
function shiftSlide(obj) {
var polosa = document.querySelector('#polosa');
console.log("shiftSlide");
var currentSliderPosition = parseInt(polosa.style.left);
if (obj.prev === obj.next) {
return
} else {
var left = (obj.prev - obj.next) * 300;
polosa.style.left = currentSliderPosition + left + "px";
}
}
function shiftSlide1(obj) {
var polosa = document.querySelector('#polosa1');
console.log("shiftSlide");
var currentSliderPosition = parseInt(polosa1.style.left);
if (obj.prev === obj.next) {
return
} else {
var left = (obj.prev - obj.next) * 300;
polosa1.style.left = currentSliderPosition + left + "px";
}
}
})();
I am trying to push elements to an array in a nested loop, but only the last item is getting repeated in the final array, where am I going wrong, very new to javascript asynchronous concept.Below is the function in which I push the items to an array.
$scope.showBeList = function(feed) {
if (feed[srcServ.KEY_CONTENT_TEXT]) {
var content = JSON.parse(feed[srcServ.KEY_CONTENT_TEXT])
if (content) {
$scope.beList = {};
for (var key in content) {
var decorationVal;
//reading value from a lokijs collection
var decoration = dataServ[srcServ.CONST_COLLECTION_DECORATION].find({
'name': key
});
if (decoration && decoration.length) {
decorationVal = decoration[0];
if (decorationVal != null) {
var tempObj = JSON.parse(decorationVal.value);
if (tempObj) {
var header = tempObj[key][key + '_HEADER'];
if (header) {
var counter = content[key].length;
var tempItems = [];
for (var j = 0; j < content[key].length; j++) {
(function(j) {
var obj = {};
obj[srcServ.KEY_MAIN_HEADER] = tempObj[key][srcServ.KEY_DESC];
obj[srcServ.KEY_SUB_HEADER] = header[srcServ.KEY_DESC];
obj.id = j;
var itemVal = content[key][j][key + '_HEADER'];
var details = [];
var notes = [];
for (var item in itemVal) {
var val = null;
var found = false;
for (var i = 0; i < header.field.length; i++) {
if (header.field[i].name == item) {
val = header.field[i];
found = true;
break;
}
}
if (found && val != null) {
val[srcServ.KEY_DESC_VALUE] = itemVal[item];
details.push(val);
}
}
obj.details = details;
counter--;
if (counter == 0) {
$scope.showMoreDetails = true;
$scope.beList.beItems = tempItems;
console.log(JSON.stringify($scope.beList));
}
tempItems.push(obj)
})(j);
// $scope.beList.beItems.push(obj);
}
}
}
}
}
}
}
}
}
If I run this code:
var alts = {};
$('.grid ul').find('.lista-produtos:visible').each(function(){
var classes2 = $(this).attr('class').split(' ');
for (var i = 0; i < classes2.length; i++) {
var matches2 = /^tipo\-(.+)/.exec(classes2[i]);
if (matches2 != null) {
var produto2 = matches2[1];
}
}
if(!alts[classes2]){
alts[classes2] = true;
$('ul.filters').append('<li class="filter-produto">'+ produto2 +'</li>');
}
});
as a function, like this:
function tipoProduto(){
var alts = {};
$('.grid ul').find('.lista-produtos:visible').each(function(){
var classes2 = $(this).attr('class').split(' ');
for (var i = 0; i < classes2.length; i++) {
var matches2 = /^tipo\-(.+)/.exec(classes2[i]);
if (matches2 != null) {
var produto2 = matches2[1];
}
}
if(!alts[classes2]){
alts[classes2] = true;
$('ul.filters').append('<li class="filter-produto">'+ produto2 +'</li>');
}
});
}
and call it here:
$('.list-group-item').click(function(){
var classes1 = $(this).attr('class').split(' ');
for (var i = 0; i < classes1.length; i++) {
var matches1 = /^ctrl\-(.+)/.exec(classes1[i]);
if (matches1 != null) {
var marca1 = matches1[1];
}
}
$(this).addClass("active");
$('.list-group-item').not(this).removeClass("active");
if ($('.todos-produtos').hasClass("active")) {
$('.lista-produtos').hide();
$('.' + marca1).show();
}
else {
var produto1 = $('li.filter-produto.active').text();
$('.lista-produtos').not('.' + marca1 + '.tipo-' + produto1).hide();
$('.' + marca1 + '.tipo-' + produto1).show()
}
tiposProduto(); // CALLING IT HERE //
});
});
then this code below doesn't work:
$(document).ready(function(){
$('.filter-produto').click(function() {
var classes3 = $('.list-group-item.active').attr('class').split(' ');
for (var i = 0; i < classes3.length; i++) {
var matches3 = /^ctrl\-(.+)/.exec(classes3[i]);
if (matches3 != null) {
var marca2 = matches3[1];
}
}
$(this).addClass("active");
$('.filter-produto').not(this).removeClass("active");
if ($(this).hasClass("todos-produtos")) {
$('.' + marca2).show();
}
else {
var produto3 = $(this).text();
$(".lista-produtos").not('.tipo-' + produto3).hide();
$('.' + marca2 + '.tipo-' + produto3).show();
}
});
});
but if I change the 1st code to this:
$(document).ready(function(){
var alts = {};
$('.grid ul').find('.lista-produtos:visible').each(function(){
var classes2 = $(this).attr('class').split(' ');
for (var i = 0; i < classes2.length; i++) {
var matches2 = /^tipo\-(.+)/.exec(classes2[i]);
if (matches2 != null) {
var produto2 = matches2[1];
}
}
if(!alts[classes2]){
alts[classes2] = true;
$('ul.filters').append('<li class="filter-produto">'+ produto2 +'</li>');
}
});
});
then the 4th code works again.
The problem is I need the code above as a function, like I showed on the 2nd and 3rd examples.
Thanks!
Thanks for the few replies. I found out the problem.
Appended objects weren't being recognized by the functions. That's why $('.filter-produto').click(function() { wasn't working.