Run function inside another function - javascript

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.

Related

Simplify if else statements through a Javascript Array

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);
});
})();

Boolean for each question with array list

one var with multiples "selected" question relates to "employee".
When open the system will show up all question, whatever I pressed the button will show me an employee and I will select one (ex: Brian for the first question) and will select "positive".
When I click on my second question, Brian is already selected. HERE is my problem.
Should be select only in one question and is making flag for all question.
anything wrong with the boolean?
var resultHandler = function(){
currentQuestion = this;
$('#details-name').text(currentQuestion.question);
$('#projectPopUp').show();
};
var cancel = function() {
//do nothing for now
}
var commenthandler = function() {
var value = $("#" + this.id + "-comment").val();
this.comments = value;
$("#" + this.id + "-comment").val(value);
};
var names = [];
// bt select ppl
var nameList = function (){
for (var i = 0; i < employees.length; i++) {
var name = employees[i];
var id = i;
var data = {
id: 'e' +id,
name: name
};
names.push(data);
$('#detailsgrid tbody').append(Utils.processTemplate("#popupPersonTemplate tbody", data));
$("#" + data.id + "-status").text('Select');
$("#" + data.id + "-status").click(statusHandler.bind(data));
}
};
var statusHandler = function(){
var previousResult = this.inspectionResult;
var answerIndex = answers.indexOf(previousResult);
/** -1 is if the answer is not found if not found defaults to first answer
* else it gets the next answer
*/
console.log('Answer Index: ' + answerIndex);
if (answerIndex == -1) {
console.log('Answer index is -1');
answerIndex = 0;
this.active = 'false';
updateActiveStatus(this);
} else {
answerIndex = (answerIndex + 1) % answers.length;
}
var currentResult = answers[answerIndex];
this.inspectionResult = currentResult;
$("#" + this.id + "-status").text(currentResult);
// commentvisibilitymanager(this);
};
var buildQuestionnaire = function(){
parseInitialDataHolder();
for (var i = 0; i < ARRAY_OF_QUESTIONS.length; i++){
var id = ARRAY_OF_QUESTIONS[i].code;
if (id && typeof id != 'undefined'){
id = id.replace('.', '-');
};
var data = {
id: id,
question: ARRAY_OF_QUESTIONS[i].question,
inspectionResult: "", //defaultResults
employee_results: [],
active: true
};
var initialdata = initialdataholder[id];
if(initialdata) {
data = initialdata;
}
dataholder.push(data);
if (typeof ARRAY_OF_QUESTIONS[i].header == 'undefined') {
$('#questionsTable tbody').append(Utils.processTemplate("#rowTemplate tbody", data));
$("#" + id + "-inspectionResult").text(data.inspectionResult || 'Select');
$("#" + id + "-inspectionResult").click(resultHandler.bind(data));
updateActiveStatus(data);
commentvisibilitymanager(data);
}
else {
$('#questionsTable tbody').append(Utils.processTemplate("#sectionRowTemplate tbody", data));
}
}
}
//to close the popup
var closePopup = function() {
$('#projectPopUp').hide();
};
$(document).ready(function() {
buildQuestionnaire();
nameList();
});

Show all tabs content vanilla js

How can I change this javascript code, that when I click on "Green" I want the content from all tabs to be displayed? https://codepen.io/wangel13/pen/OXBrRp
'use strict';
function Tabs() {
var bindAll = function() {
var menuElements = document.querySelectorAll('[data-tab]');
for(var i = 0; i < menuElements.length ; i++) {
menuElements[i].addEventListener('click', change, false);
}
}
var clear = function() {
var menuElements = document.querySelectorAll('[data-tab]');
for(var i = 0; i < menuElements.length ; i++) {
menuElements[i].classList.remove('active');
var id = menuElements[i].getAttribute('data-tab');
document.getElementById(id).classList.remove('active');
}
}
var change = function(e) {
clear();
e.target.classList.add('active');
var id = e.currentTarget.getAttribute('data-tab');
document.getElementById(id).classList.add('active');
}
bindAll();
}
var connectTabs = new Tabs();
Take a look at this:
'use strict';
function Tabs() {
var bindAll = function() {
var menuElements = document.querySelectorAll('[data-tab]');
for(var i = 0; i < menuElements.length ; i++) {
menuElements[i].addEventListener('click', change, false);
}
}
var clear = function() {
var menuElements = document.querySelectorAll('[data-tab]');
for(var i = 0; i < menuElements.length ; i++) {
menuElements[i].classList.remove('active');
var id = menuElements[i].getAttribute('data-tab');
document.getElementById(id).classList.remove('active');
}
}
function makeAllActive() {
var tabs = document.querySelectorAll('.b-tab');
Array.from(tabs).map(item => {
item.classList.add('active');
});
}
var change = function(e) {
clear();
e.target.classList.add('active');
var id = e.currentTarget.getAttribute('data-tab');
if(id === "green") {
makeAllActive();
return;
}
document.getElementById(id).classList.add('active');
}
bindAll();
}
var connectTabs = new Tabs();

Push to an array in a nested loop is repeating the last value

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);
}
}
}
}
}
}
}
}
}

Change one letter of innerHTML

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);
}

Categories