Why isn't my JS working (in wordpress)? - javascript

What I'm trying to do is have a number count-up on my page that increases at a steady increment/interval. I created stylized images to represent each number 0-9 in the count-up, so I also need to replace each number with its respective image. The first Function in the code represents that task, and the second script is the actual count-up. I'm using wordpress so I've added the JS file and enqueued it in the header.php file.
Here's where I had my problem: I was able to get the count-up to work, but the counterimages(input) function doesn't want to work for me. It might be an issue with how I am trying to "call" on the function on the WordPress page.
If anyone could help me out I would be very grateful!
function counterimages(input) {
var output = ""
for (var i = 0; i < input.length; i++) {
var chr = input.substring(i, i + 1)
if (chr == '£') {
output += '<img border="0" src="img/pound.gif">';
} else if (chr == '.') {
output += '<img border="0" src="img/dot.gif">';
} else {
output += '<img border="0" src="http://eatiply3.staging.wpengine.com/wp-content/uploads/2013/05/'+(chr+1)+'.png">';
}
return output;
}
var START_DATE = new Date("October 21, 2012 22:30:00"); // put in the starting date here
var INTERVAL = 1; // refresh interval in seconds
var INCREMENT = 769.2; // increase per tick (1/0.0013 ~ 769)
var START_VALUE = 35000; // initial value when it's the start date
var count = 0;
jQuery(document).ready(function($) {
var msInterval = INTERVAL * 1000;
var now = new Date();
count = parseInt((now - START_DATE)/msInterval) * INCREMENT + START_VALUE;
$('#counter').html(count.toFixed(0));
window.setInterval( function(){
count += INCREMENT;
$('#counter').html(count.toFixed(0));
}, msInterval);
});`

You are missing a bracket in the counterimages function
http://jsfiddle.net/Rhpjw/
function counterimages(input) {
var output = ""
for (var i = 0; i < input.length; i++) {
var chr = input.substring(i, i + 1)
if (chr == '£') {
output += '<img border="0" src="img/pound.gif">';
} else if (chr == '.') {
output += '<img border="0" src="img/dot.gif">';
} else {
output += '<img border="0" src="http://eatiply3.staging.wpengine.com/wp-content/uploads/2013/05/' + (chr + 1) + '.png">';
}
return output;
}
}
var START_DATE = new Date("October 21, 2012 22:30:00"); // put in the starting date here
var INTERVAL = 1; // refresh interval in seconds
var INCREMENT = 769.2; // increase per tick (1/0.0013 ~ 769)
var START_VALUE = 35000; // initial value when it's the start date
var count = 0;
jQuery(document).ready(function ($) {
var msInterval = INTERVAL * 1000;
var now = new Date();
count = parseInt((now - START_DATE) / msInterval) * INCREMENT + START_VALUE;
$('#counter').html(count.toFixed(0));
window.setInterval(function () {
count += INCREMENT;
$('#counter').html(count.toFixed(0));
}, msInterval);
});

Related

Check if Element value has populated during for loop

I'm trying to loop through a table with the id mytab1 and all the td's with myfindclass2.
The values are being populated by another API so it could take up to a few seconds for the values to be available.
I'm using the setinterval but it doesn't seem to work in a for loop.
When ran it will not wait till the element is populated it just finds the only one populated then continuously runs the nextstep() function as if the clearInterval never worked. And just skips over the elements that are null/''
Is there way to write the setinterval/ check if the element is populated as a function outside of the for loop?
**I'm trying to use the most basic of JS as this will be used in all browsers.
function refreshGauge() {
var table = document.getElementById("mytab1");
var targetTDs = table.querySelectorAll(".myfindclass2");
for (var i = 0; i < targetTDs.length; i++) {
var td = targetTDs[i];
var fvals = td.querySelectorAll("[id*='calcValue']");
var fval = fvals[0].innerText.replace('%', '');
var checkElem = "#" + fvals[0].getAttribute('id');
console.log(checkElem + '-' + $(checkElem).length)
var checkExist = setInterval(function() {
if (fval === '') {
console.log("Doesn't Exist Yet!");
//Update variables to see if updated
fvals = td.querySelectorAll("[id*='calcValue']");
fval = fvals[0].innerText.replace('%', '');
} else {
//stop interval
clearInterval(checkExist);
//perform next function : creates gauge
nextstep(td);
}
}, 100); // check every 100ms
}
console.log('done')
};
my work around is :
function refreshGauge() {
var table = document.getElementById("mytab1");
var targetTDs = table.querySelectorAll(".myfindclass2");
for (var i = 0; i < targetTDs.length; i++) {
var td = targetTDs[i];
var fvals = td.querySelectorAll("[id*='calcValue']");
var fval = fvals[0].innerText.replace('%','');
var checkElem = "#" + fvals[0].getAttribute('id');
console.log(checkElem + '-' + $(checkElem).length)
nextstep(td)
}
console.log('done')
} ;
var timesRun = 0;
var interval = setInterval(function(){
timesRun += 1;
if(timesRun === 10){
clearInterval(interval);
}
refreshGauge()
}, 2000);
but would like to check when the values populated so I don't have to re-run the function 10+ times

When a button is clicked that decrements a value, how do you stop it decrementing into the negative range

(First question!)
I am (attempting to) create a clicker game. When a button is clicked, the gold value should decrement by 10. This works. However, I want to stop it decrementing at zero.
e.g (if button clicked || if gold count >= 0) do code. else: error message
(that is not actual code, just me thinking)
I have tried a few ways, none of which seem to work
Any ideas? (I am not entirely sure if this is possible, as when you click the button, it would decrement by that number and then check if value is zero? i think? Wouldnt that be an infinite loop?)
The variables of (BeggarCount, BeggarCost, oText and oCount) have all been previously defined in HTML. As i said, the code does work, it just dosent stop at zero
CODE:
<script type="text/javascript" language="javascript">
var vButton = document.getElementById("AddBeggar");
var vText = document.getElementById("BeggarCount");
var vcText = document.getElementById("BeggarCost");
var vcost = 10
var vcount = 0;
var vprice = 10;
if (vButton.addEventListener('click') || ocount >= 10) {
vText.innerHTML = vcount += 1;
vcText.innerHTML = vcost += 1;
oText.innerHTML = oincrement += 1;
oText.innerHTML = ocount -= vprice;
vprice += 1;
}, false);
when i try this, simply nothing happens.
I guess you should change your if clause checking the current value of gold like:
if (vButton.addEventListener('click') && ocount >= 10) {
vText.innerHTML = vcount += 1;
vcText.innerHTML = vcost += 1;
oText.innerHTML = oincrement += 1;
oText.innerHTML = ocount -= vprice;
vprice += 1;
}, false);
Just did it!!
<script type="text/javascript" language="javascript">
var vButton = document.getElementById("AddBeggar");
var vText = document.getElementById("BeggarCount");
var vcText = document.getElementById("BeggarCost");3
var vcost = 10
var vcount = 0;
var vprice = 10;
vButton.addEventListener('click', function(i, a) {
if (ocount >= vcost) {
vText.innerHTML = vcount += 1;
vcText.innerHTML = vcost += 1;
oText.innerHTML = oincrement += 1;
oText.innerHTML = ocount -= vprice;
vprice += 1;
}
}, false);
</script>
This code works!!
All variables are the same

Nested for loop incrementation producing inconsistent result

I'm trying to use the variable of the current iteration of the loop in the nested loop.
However when I execute the following code the loop incorrectly starts at f = 6, and then it correctly iterates over the nested loop.
I've removed all the other code and then it works normally. However I have no clue what could possibly be interfering with the loop. There probably is a reason for it and I wish you guys could help me figure this out - and probably learn something more about why this behaviour occurs the way it does.
for (var f = 0; f < 6; f++) {
var JSONURL = "http://blabla.com/json";
$.ajax( JSONURL, {
dataType: "json"
})
.done(function(json) {
for (var i = 0; i < json.timeslots.length; i++) {
var StartHour = json.timeslots[i].begintijd.split(":")[0];
var StartMinute = json.timeslots[i].begintijd.split(":")[1];
var EndHour = json.timeslots[i].eindtijd.split(":")[0];
var EndMinute = json.timeslots[i].eindtijd.split(":")[1];
//Calculate top distance of block in pixels
if (StartHour < 20) {
var TopDistance = ((parseInt(StartHour) - 9) * 240) + (parseInt(StartMinute) * 4);
}
//Calculate height of block in pixels
var BlockHeight = ((((parseInt(EndHour) * 60) + (parseInt(EndMinute))) - ((parseInt(StartHour) * 60) + (parseInt(StartMinute)))) * 4) - 2.5;
//Generate HTML for blocks
var html_first = '<div data-ix="show-pop-up" class="w-clearfix time-block event-block" style="height:'+BlockHeight+'px; top:'+TopDistance+'px; background-color:'+json.timeslots[i].achtergrondkleur+';">';
if (json.timeslots[i].afbeelding.length > 0) {
var html_mid = '<div class="avatar" style="background-image:url('+json.timeslots[i].afbeelding+');"></div>';
}
else {
html_mid = "";
}
var html_last = '<h4 class="card-title">'+json.timeslots[i].naam+'</h4><div class="time-indication">'+json.timeslots[i].begintijd+'</div><div class="speaker-description">'+json.timeslots[i].functie+'</div><div class="hidden-content"><div class="pop-up-wrapper" style="background-color:'+json.timeslots[i].achtergrondkleur+';"><div class="w-clearfix pop-up-header-background"><div data-ix="hide-pop-up" class="close-icon" id="PopupClose"></div><h3 class="white pop-up-title">'+json.timeslots[i].naam+'</h3><div class="pop-up-subtitle">'+json.timeslots[i].functie+'</div></div><div class="w-clearfix pop-up-body"><div class="pop-up-avatar" style="background-image:url('+json.timeslots[i].afbeelding+');"></div><div class="w-clearfix"><div class="pop-up-card-detail-wrap"><div class="time-label">Begint om</div><div class="pop-up-time-text">'+json.timeslots[i].begintijd+'</div></div><div class="pop-up-card-detail-wrap"><div class="time-label">Eindigt om</div><div class="pop-up-time-text">'+json.timeslots[i].eindtijd+'</div></div><div class="pop-up-card-detail-wrap"><div class="time-label">plek</div><div class="pop-up-time-text">Zaal 1</div></div></div><p class="pop-up-paragraph">'+json.timeslots[i].beschrijving_lang+'</p></div><div class="pop-up-footer">Meer over deze spreker</div></div></div></div>';
var html = html_first+html_mid+html_last;
var TargetDiv = "#Locatie"+f+"Column";
alert("Parent loop increment: "+f);
alert("Child loop increment: "+i);
$(TargetDiv).append(html);
}
});
}
It starts at f = 6 because your callback doesn't get called until after f equals 6
What you may do is something to the effect of:
for (var f = 0; f < 6; f++) {
var JSONURL = "http://blabla.com/json";
$.ajax( JSONURL, {
dataType: "json"
})
.done(handleResponse.bind(null, f));
}
function handleResponse(f, json) {
for (var i = 0; i < json.timeslots.length; i++) {
var StartHour = json.timeslots[i].begintijd.split(":")[0];
var StartMinute = json.timeslots[i].begintijd.split(":")[1];
var EndHour = json.timeslots[i].eindtijd.split(":")[0];
var EndMinute = json.timeslots[i].eindtijd.split(":")[1];
//Calculate top distance of block in pixels
if (StartHour < 20) {
var TopDistance = ((parseInt(StartHour) - 9) * 240) + (parseInt(StartMinute) * 4);
}
//Calculate height of block in pixels
var BlockHeight = ((((parseInt(EndHour) * 60) + (parseInt(EndMinute))) - ((parseInt(StartHour) * 60) + (parseInt(StartMinute)))) * 4) - 2.5;
//Generate HTML for blocks
var html_first = '<div data-ix="show-pop-up" class="w-clearfix time-block event-block" style="height:'+BlockHeight+'px; top:'+TopDistance+'px; background-color:'+json.timeslots[i].achtergrondkleur+';">';
if (json.timeslots[i].afbeelding.length > 0) {
var html_mid = '<div class="avatar" style="background-image:url('+json.timeslots[i].afbeelding+');"></div>';
}
else {
html_mid = "";
}
var html_last = '<h4 class="card-title">'+json.timeslots[i].naam+'</h4><div class="time-indication">'+json.timeslots[i].begintijd+'</div><div class="speaker-description">'+json.timeslots[i].functie+'</div><div class="hidden-content"><div class="pop-up-wrapper" style="background-color:'+json.timeslots[i].achtergrondkleur+';"><div class="w-clearfix pop-up-header-background"><div data-ix="hide-pop-up" class="close-icon" id="PopupClose"></div><h3 class="white pop-up-title">'+json.timeslots[i].naam+'</h3><div class="pop-up-subtitle">'+json.timeslots[i].functie+'</div></div><div class="w-clearfix pop-up-body"><div class="pop-up-avatar" style="background-image:url('+json.timeslots[i].afbeelding+');"></div><div class="w-clearfix"><div class="pop-up-card-detail-wrap"><div class="time-label">Begint om</div><div class="pop-up-time-text">'+json.timeslots[i].begintijd+'</div></div><div class="pop-up-card-detail-wrap"><div class="time-label">Eindigt om</div><div class="pop-up-time-text">'+json.timeslots[i].eindtijd+'</div></div><div class="pop-up-card-detail-wrap"><div class="time-label">plek</div><div class="pop-up-time-text">Zaal 1</div></div></div><p class="pop-up-paragraph">'+json.timeslots[i].beschrijving_lang+'</p></div><div class="pop-up-footer">Meer over deze spreker</div></div></div></div>';
var html = html_first+html_mid+html_last;
var TargetDiv = "#Locatie"+f+"Column";
alert("Parent loop increment: "+f);
alert("Child loop increment: "+i);
$(TargetDiv).append(html);
}
}
What this does is call handleResponse by passing in the value of f at the time that the loop is run.
The problem is not the nested loop, but the asynchronous call inside the loop. To resolve this issue you can use an immediately-invoked-anonymous-function to pass the correct value to your function, like so :
for (var f = 0; f < 6; f++) {
(function(foo) {
//ajax call
//your ajax call will now have the correct number
})(f);
}

I guess i need dynamic variables in javascript to do this?

I am trying to use this stopwatch here: Stopwatch Script but for many counters on the page, that are dynamically created via php loops.
For example:
<button type="button" class="btn" id="bn1" data-bid="n1">Start</button>
<br><br>
<div id=n1></div>
<br><br>
<button type="button" class="btn" id="bn2" data-bid="n2">Start</button>
<br><br>
<div id=n2></div>
Using jquery i am trying to create 2 simple functions. One to start each timer clicked and one to stop it
<script src="http://code.jquery.com/jquery-2.2.0.min.js"></script>
<script language=javascript>
var vars = {};
var bid;
var h = 0;
var m = 0;
var s = 0;
$('[class^=btn]').on('click', function() {
var pause = $(this).text() === 'Stop';
$(this).text(pause ? 'Start' : 'Stop');
bid = $(this).attr('data-bid');
return (this.timvar ^= 1) ? startimer(bid) : stop(bid);
});
function stop(bid) {
clearTimeout(['tm' + bid]);
}
function startimer(bid) {
//vars['tm' + bid] = setInterval('disp('+bid+')',1000);
vars['tm' + bid] = setInterval(function() {
disp(bid)
}, 1000);
}
function disp(bid) {
//alert(bid);
// Format the output by adding 0 if it is single digit //
if (s < 10) {
var s1 = '0' + s;
} else {
var s1 = s;
}
if (m < 10) {
var m1 = '0' + m;
} else {
var m1 = m;
}
if (h < 10) {
var h1 = '0' + h;
} else {
var h1 = h;
}
// Display the output //
str = h1 + ':' + m1 + ':' + s1;
document.getElementById(bid).innerHTML = str;
// Calculate the stop watch //
if (s < 59) {
s = s + 1;
} else {
s = 0;
m = m + 1;
if (m == 60) {
m = 0;
h = h + 1;
} // end if m ==60
} // end if else s < 59
// end of calculation for next display
}
</script>
Somehow i have to be able to execute these 2 functions multiple times for each button, that will use a dynamic 'tm' variable that updates the text inside the n1 and n2..(etc) divs with the timer. And then when the user presses stop to be able to stop that specific tm var.
But...i am kinda lost when it comes to dynamic variables and how to properly pass them around between javascript functions...I am not even sure if there is a simpler way of doing this...I dont know what's the proper term to search for it in google. Any advice ? What am i doing wrong ?
-Thanks

issue with Javascript image changer

I have a script running on my page to change the images. I want to repeat it 6 times to use in other places on the same page, but it wont work when I repeat it.
var delay = 2000 //set delay in miliseconds
var curindex = 0
var randomimages = new Array()
randomimages[0] = "hhh200.jpg"
randomimages[1] = "ray200.jpg"
var preload = new Array()
for (n = 0; n < randomimages.length; n++) {
preload[n] = new Image()
preload[n].src = randomimages[n]
}
document.write('<img name="defaultimage" src="' + randomimages[Math.floor(Math.random() * (randomimages.length))] + '">')
function rotateimage() {
if (curindex == (tempindex = Math.floor(Math.random() * (randomimages.length)))) {
curindex = curindex == 0 ? 1 : curindex - 1
} else curindex = tempindex
document.images.defaultimage.src = randomimages[curindex]
}
setInterval("rotateimage()", delay)
Can anyone see why it's not working?
If you are just copying and pasting it somewhere else in the page as is, then you are overriding your variable values, and you are giving both images the same name, so those are 2 problems right there. You should put it all inside on function and call that function in the 2 places you want.
Try this.
function randomImage(randomImages, imageName) {
var delay = 2000 //set delay in miliseconds
var curindex = 0
var preload = new Array()
for (n = 0; n < randomImages.length; n++) {
preload[n] = new Image()
preload[n].src = randomImages[n]
}
document.write('<img name="' + imageName + '" src="' + randomImages[Math.floor(Math.random() * (randomImages.length))] + '">');
function rotateimage() {
var tempindex = Math.floor(Math.random() * (randomImages.length));
if (curindex == tempindex) {
curindex = curindex == 0 ? 1 : curindex - 1
} else curindex = tempindex
document.images[imageName].src = randomImages[curindex];
}
setInterval("rotateimage()", delay);
}
// and then to use it, create your image arrays outside of the function, and call the function.
var images1 = new Array();
images1[0] = "hhh200.jpg";
images1[1] = "ray200.jpg";
var images2 = new Array();
images2[0] = "hhh200.jpg";
images2[1] = "ray200.jpg";
randomImage(images1, 'imageOneName');
randomImage(images2, 'imageTwoName');
I have not tested this code, but this is the general idea you should follow.

Categories

Resources