Updating Integer on the Page - javascript

I'm creating something which shows a list of cats and then increments a counter when the image is clicked. I've got everything working so when the image is clicked it increments the integer when I log it to the console. The only problem is that on the page the counter doesn't increment, it stays static at zero.
Here is my code. I've tried to create an update function which takes everything with the class tag and then loops through it replacing the HTML with the same thing so it redraws the text.
However it doesn't work. Any help would be appreciated!
var HTMLcatName = '<h1>%data%</h1>';
var HTMLcatImage = '<img id="cat" src="%data%">';
var HTMLcatCounter = '<p class="counter">Number of clicks: %data%</p>';
var noCats = 'No cats selected m8';
var cats = {
"name": ["Monte", "Jib"],
"image": ["images/monte.jpg", "images/jib.jpg"],
"clicks": [0, 0],
display: function () {
for (i = 0; i < cats.image.length; i++) {
formattedCatNames = HTMLcatName.replace("%data%", cats.name[i]);
var catNames = formattedCatNames;
formattedCatImages = HTMLcatImage.replace("%data%", cats.image[i]);
var catImages = formattedCatImages;
formattedCatCounter = HTMLcatCounter.replace("%data%", cats.clicks[i]);
var catCounter = formattedCatCounter
var elem = document.createElement('div');
elem.innerHTML = catNames + catImages + catCounter;
elem.querySelector('img').addEventListener('click', (function(catCountUp) {
return function() {
cats.clicks[catCountUp]++;
update();
};
})(i));
document.body.appendChild(elem);
}
},
}
cats.display();
var getCounterClass = document.getElementsByClassName("counter");
var update = function() {
for (j = 0; j < getCounterClass.length; j++) {
getCounterClass[j].innerHTML = '<p class="counter">Number of clicks: ' + cats.clicks[j] + '</p>';
}
}

I cannot see the click event, but this can be the error:
getTags.innerHTML = '<p class="counter">Number of clicks: ' + cats.clicks[j] + '</p>';
replace with
getTags[j].innerHTML = 'Number of clicks: ' + cats.clicks[j];
you are missing the counter in the for loop for targeting the right element

Related

Log the innerText of a created element

I'm trying to make my script only log the strings once. So when a new string is created it will only log the new strings... This script logs all of the strings at once. I would like to find a way to make it only log the .innerText of freshly created children in that element with the id "team_log_actual".
Children can be added at any point of time.
Here is my script:
setInterval(function() {
var logelement = $('#team_log_actual');
var foo = document.getElementById('team_log_actual');
for (let i = 0; i < foo.children.length; i++) {
//console.log(foo.children[i].innerText);
var PRINTactions = foo.children[i].innerText;
var PRINTactionsEle = foo.children[i];
var fields = PRINTactions.split(/ /);
var Username = fields[2]; //grabs the second field from the splitted string. which is the username..
var text1 = fields[3];
var text2 = fields[4];
var text3 = fields[5];
var text4 = fields[6];
var text5 = fields[7];
var text6 = fields[8];
var text7 = fields[9];
var text8 = fields[10];
var text9 = fields[11];
var text10 = fields[12];
//Defined multiple just in case. Each field will contain a string. If one is there, but it's highly unlikely to go past 5-6.
var combinetext = fields[3] + " " + fields[4] + " " + fields[5] + " " + fields[6] + " " + fields[7];
if (combinetext.includes("used item") == true) {
console.log(Username + " : " + combinetext) // log the Username and the combinedtext. Only if the combinetext includes the string "in ejector".
}
}
}, 10000); // Run every 10 seconds.
Solved using MutationObserver. Recommended by user: CodeWalker
// Solved code.
var Logconsole = document.getElementById('team_log_actual');
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
for (var i = 0; i < mutation.addedNodes.length; i++) {
//This var gets the innertext of the new element.
var TextFromNewElement = mutation.addedNodes[i].innerText;
console.log(TextFromNewElement);
}
});
});
observer.observe(Logconsole, {
childList: true
});
//Test code. ----- Create a fake element every 5 seconds.
var testelement = document.createElement('div');
testelement.id = 'team_log_actual';
testelement.innerHTML = '<p> <b>[<span style="color: #0FF">USER:</span>] <bdi style="color: #0FF;">User2</bdi></b> harvest a plant.</p>'
setInterval(function(){
//every 5 seconds, add the test element.
Logconsole.appendChild(testelement)
}, 5000);
<div id="team_log_actual" class="log">
<p> <b>[<span style="color: #0FF">USER:</span>] <bdi style="color: #0FF;">User1</bdi></b> planted a seed.</p>
</div>

How to call two functions with the same event?

I want to display eight elements of first array in eight divs with class .box, and one element of second array in the center div with id center by clicking any div except the middle one with id center. The problem is the two functions named nextElems & arr are not called simultaneously. If one function is called, another does not work. I am able to call the function arr, but how to call the function nextElems simultaneously on the click of any div.
Your suggestions are always really great and helpful and I am much obliged.
<div id="container"> </div>
var words = [40];
// Showing 8 elements each time in different divs
var count = 0;
var x = "";
function nextElems() {
var newArray = words.slice(count, count + 8);
for (i = 0; i < newArray.length; i++)
{
x += '<div class=box>' + newArray[i] + '</div>';
document.getElementById('container').innerHTML = x;
}
x = "";
count += 8;
// Creating div in middle between fourth and fifth div
if (count <= 40) {
var center = document.querySelector('#div-3');
center.insertAdjacentHTML('afterend', '<div id="center"> </div>')
}
}
nextElems();
// Showing elements one at a time in order
var oppo = ["White", "Easy", "Soft", "Low", "Good"];
var x = "";
var count = 0;
function arr() {
if (count < oppo.length) {
x += '<div>' + oppo[count] + '</div>';
document.getElementById('center').innerHTML = x;
count++;
} else {
count = 0;
document.getElementById('center').innerHTML = "";
}
x = "";
}
arr();
$('.box').click(function() {
arr();
});
I have tried
$('.box').click(function() {
arr();
nextElems();
});
I have also tried it on the click of a button & with other jQuery
methods.
You need to declare variables inside a function scope.
Because now your code performed in the next order:
var count = 0;
var x = "";
nextElems();
var oppo = ["White", "Easy", "Soft", "Low", "Good"];
var x = "";
var count = 0;
..
someday later ...
..
arr(); //here you modify your global variables "x" and "count", so next function will use it with unpredictable values
nextElems();
so you need to declare it like
function nextElems() {
var count = 0;
var x = "";
...somecode
}
and then you can use
$('.box').click(function() {
arr();
nextElems();
});

Nesting a function returning NaN

I am running into an error when I try nesting a simple counter function inside an existing function. I know some people frown upon this, so if there is any other way of doing this, it would be greatly appreciated. Basically, I am calling a function to parse a JSON string to get 3 numbers. I would like to animate those 3 numbers with a counter every time a new calculation is made. My instinct is to place this counter function inside of the same for loop that runs to get the numbers themselves. Doing so returns NaN. I'm sure there is something very little that I am missing here that I am hoping someone can pick up on.
Code:
var text = '{JSON data}'
var obj = JSON.parse(text);
function calculate() {
var e = document.getElementById("ltSpecialtyList");
var selectedSpec = e.options[e.selectedIndex].text;
console.log(selectedSpec);
var x = document.getElementById("ltLocationList");
var selectedState = x.options[x.selectedIndex].text;
console.log(selectedState);
for (i = 0; i < obj.values.length; i++)
{
if (obj.values[i].State == selectedState && obj.values[i].Specialty == selectedSpec)
{
// DISPLAY RESULTS DIV (JQUERY)
var $resultsDiv = $("#ROI-results");
$resultsDiv.fadeIn();
// CAPTURE HEADER SPAN NAMES
var headerState = document.getElementById("header-state-name");
var headerSpec = document.getElementById("header-specialty-name");
// CLEAR STATE AND SPECIALTY FROM SPAN
headerState.innerHTML = "";
headerSpec.innerHTML = "";
// ADD SELECTED STATE AND SPECIALTY
headerState.innerHTML += selectedState;
headerSpec.innerHTML += selectedSpec;
// CAPTURE RESULT DATA DIVS
var permResults = document.getElementById("ROI-results-perm-data");
var locumResults = document.getElementById("ROI-results-locums-data");
var uncollectedResults = document.getElementById("ROI-results-uncollected-data");
// CLEAR DATA DIVS
permResults.innerHTML = "";
locumResults.innerHTML = "";
uncollectedResults.innerHTML = "";
//POPULATE DIV WITH DATA
permResults.innerHTML += "<p class='ROI-results-data-number univers-bold'>" + obj.values[i].Permanent + "</p>";
locumResults.innerHTML += "<p class='ROI-results-data-number univers-bold'>" + obj.values[i].Locums + "</p>";
uncollectedResults.innerHTML += "<p class='ROI-results-data-number univers-bold'>" + obj.values[i].Gross + "</p>";
}
// COUNTER
$('.ROI-results-data-number').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
}
}

Hiding and showing classes with the same Class with jQuery

I'm creating a tool which generates a bunch of divs based on data I input into an array, however they all have the same class. The idea is that when one link is clicked it shows one of the ".catbox" divs and hides the rest.
All of these divs have the same class so I need to iterate through them, but I'm not quite sure how this is done with jQuery. Currently clicking on the last ".list" class triggers the on click event instead of all of them, and currently it shows all of the divs with the class ".catbox" instead of the corresponding one.
Here is the code:
var HTMLcatName = '<h1>%data%</h1>';
var HTMLcatImage = '<img id="cat" src="%data%">';
var HTMLcatCounter = '<p class="counter">Number of clicks: %data%</p>';
var HTMLcatList = '<p>%data%</p>'
var noCats = 'No cats selected m8';
var getCounterClass = document.getElementsByClassName("counter");
$(document).ready(function() {
cats.display();
$('.catbox').hide();
for (u = 0; u < cats.name.length; u++) {
formattedCatList = HTMLcatList.replace("%data%", cats.name[u]);
var listDiv = document.createElement('div');
listDiv.innerHTML = formattedCatList;
listDiv.className = "list";
$(".list").click(function() {
$(".catbox").toggle("slow");
});
$("body").prepend(listDiv);
}
});
var update = function() {
for (j = 0; j < getCounterClass.length; j++) {
getCounterClass[j].innerHTML = 'Number of clicks: ' + cats.clicks[j];
}
}
var cats = {
"name": ["Monte", "Jib"],
"image": ["images/monte.jpg", "images/jib.jpg"],
"clicks": [0, 0],
display: function () {
for (i = 0; i < cats.image.length; i++) {
formattedCatNames = HTMLcatName.replace("%data%", cats.name[i]);
formattedCatImages = HTMLcatImage.replace("%data%", cats.image[i]);
formattedCatCounter = HTMLcatCounter.replace("%data%", cats.clicks[i]);
var catDiv = document.createElement('div');
catDiv.className = "catbox";
catDiv.innerHTML = formattedCatNames + formattedCatImages + formattedCatCounter;
catDiv.querySelector('img').addEventListener('click', (function(catCountUp) {
return function() {
cats.clicks[catCountUp]++;
update();
};
})(i));
document.body.appendChild(catDiv);
}
},
}
The function I need help with is found within $(document).ready(function() {
Any help would be greatly appreciated.
The following can do it:
$(".list").on("click", function(){
$(this).find(".catbox").toggle("slow");
});
With $('.list') you get a group of elements of class list, so if you use $('.list').click(); you will bind the click event to just one element. You should use:
$(".list").each(function(){
$(this).click(function() {
$(".catbox").toggle("slow");
});
});

Javascript function not recognizing id in getElementById

I am adding a row to a table, and attached an ondblclick event to the cells. The function addrow is working fine, and the dblclick is taking me to seltogg, with the correct parameters. However, the var selbutton = document.getElementById in seltogg is returning a null. When I call seltogg with a dblclick on the original table in the document, it runs fine. All the parameters "selna" have alphabetic values, with no spaces, special characters, etc. Can someone tell me why seltogg is unable to correctly perform the document.getElementById when I pass the id from addrow; also how to fix the problem.
function addrow(jtop, sel4list, ron4list) {
var tablex = document.getElementById('thetable');
var initcount = document.getElementById('numrows').value;
var sel4arr = sel4list.split(",");
var idcount = parseInt(initcount) + 1;
var rowx = tablex.insertRow(1);
var jtop1 = jtop - 1;
for (j = 0; j <= jtop1; j++) {
var cellx = rowx.insertCell(j);
cellx.style.border = "1px solid blue";
var inputx = document.createElement("input");
inputx.type = "text";
inputx.ondblclick = (function() {
var curj = j;
var selna = sel4arr[curj + 2];
var cellj = parseInt(curj) + 3;
inputx.id = "cell_" + idcount + "_" + cellj;
var b = "cell_" + idcount + "_" + cellj;
return function() {
seltogg(selna, b);
}
})();
cellx.appendChild(inputx);
} //end j loop
var rowCount = tablex.rows.length;
document.getElementById('numrows').value = rowCount - 1; //dont count header
} //end function addrow
function seltogg(selna, cellid) {
if (selna == "none") {
return;
}
document.getElementById('x').value = cellid; //setting up for the next function
var selbutton = document.getElementById(selna); //*****this is returning null
if (selbutton.style.display != 'none') { //if it's on
selbutton.style.display = 'none';
} //turn it off
else { //if it's off
selbutton.style.display = '';
} //turn it on
} //end of function seltogg
You try, writing this sentence:
document.getElementById("numrows").value on document.getElementById('numrows').value
This is my part the my code:
contapara=(parseInt(contapara)+1);
document.getElementById("sorpara").innerHTML+="<li id=\"inputp"+contapara+"_id\" class=\"ui-state-default\"><span class=\"ui-icon ui-icon-arrowthick-2-n-s\"></span>"+$('#inputp'+contapara+'_id').val()+"</li>";
Look you have to use this " y not '.
TRY!!!!

Categories

Resources