Javascript not waiting for onclick - javascript

I am trying to execute this code but for some reason that I cannot figure out the RoundRobin function will execute onload rather than onclick. I have tried removing window.onload or replacing it with document.onload. All I want is for this line document.getElementById("tableButton").onclick = RoundRobin(teamsIn); to wait for the onclick trigger.
var selectedTeams = [];
window.onload = function() {
// JavaScript Document
// add selected teams to array
var teamList = document.getElementById("teamDropdown");
teamList.onchange = function addTeams() {
if (selectedTeams.length > 7) {
alert("no more teams")
} else {
var county = document.getElementById("teamDropdown").value;
selectedTeams.push(county);
}
alert("counties selected are: " + selectedTeams);
}
var teamsIn = 0;
teamsIn = selectedTeams.length;
document.getElementById("tableButton").onclick = RoundRobin(teamsIn);
// slideshow.
var imageArray = new Array();
imageArray[0] = new Image()
imageArray[0].src = "Sponsors/aib.png"
imageArray[1] = new Image()
imageArray[1].src = "Sponsors/centra.jpg"
imageArray[2] = new Image()
imageArray[2].src = "Sponsors/eircom.png"
imageArray[3] = new Image()
imageArray[3].src = "Sponsors/etihad.png"
imageArray[4] = new Image()
imageArray[4].src = "Sponsors/liberty.jpg"
imageArray[5] = new Image()
imageArray[5].src = "Sponsors/supervalu.png"
var step = 0;
function slideShow() {
document.getElementById('slideshow').src = imageArray[step].src
if (step < 5)
step++
else
step = 0
setTimeout("slideShow()", 4000)
}
function RoundRobin(teams) {
alert(teams);
var i;
var ret = "";
var round;
var numplayers = 0;
numplayers = parseInt(teams) + parseInt(teams % 2);
numplayers = parseInt(numplayers);
alert(numplayers);
var a = new Array(numplayers - 1);
var alength = a.length;
for (var x = 0; x < (numplayers); x++) {
a[x] = "Team " + (x + 1);
}
if (numplayers != parseInt(teams)) {
a[alength] = "BYE";
}
var pos;
var pos2;
ret = "----- ROUND #1-----<br />"
for (var r1a = 0; r1a < (numplayers / 2); r1a++) {
ret += a[r1a] + " vs. " + a[alength - r1a] + "<br />"
}
for (round = 2; round < alength + 1; round++) {
ret += "<br /><br />----- ROUND #" + round + "-----<br />"
ret += a[0] + " vs. " + a[alength - (round - 1)] + "<br />"
for (i = 2; i < (numplayers / 2) + 1; i++) {
pos = (i + (round - 2))
if (pos >= alength) {
pos = ((alength - pos)) * -1
} else {
pos = (i + (round - 2))
}
pos2 = (pos - (round - 2)) - round
if (pos2 > 0) {
pos2 = (alength - pos2) * -1
}
if (pos2 < (alength * -1)) {
pos2 += alength
}
ret += a[(alength + pos2)]
ret += " vs. " + a[(alength - pos)] + "<br />"
}
}
var text = document.getElementById('fixtures');
text.innerHTML = ret;
return ret
}
// round robin format
}

What's happening is that you call the function, then you assing the return value to the onclick property. For the event handler to work you need to assign a function to the property.
Wrap the call in a function expression:
document.getElementById("tableButton").onclick = function(){
RoundRobin(teamsIn);
};

Related

Blogger random post display to prevent no posts infinite loop

How can I get Blogger to display random posts, while preventing an infinite loop when there are no posts to display?
Here is my JavaScript code which I am attempting to use:
<script>
var dt_numposts = 10;
var dt_snippet_length = 100;
var dt_info = 'true';
var dt_comment = 'Comment';
var dt_disable = '';
var dt_current = [];
var dt_total_posts = 0;
var dt_current = new Array(dt_numposts);
function totalposts(json) {
dt_total_posts = json.feed.openSearch$totalResults.$t
}
document.write('<script type=\"text/javascript\" src=\"/feeds/posts/summary?max-results=100&orderby=published&alt=json-in-script&callback=totalposts\"><\/script>');
function getvalue() {
for (var i = 0; i < dt_numposts; i++) {
var found = false;
var rndValue = get_random();
for (var j = 0; j < dt_current.length; j++) {
if (dt_current[j] == rndValue) {
found = true;
break
}
};
if (found) {
i--
} else {
dt_current[i] = rndValue
}
}
};
function get_random() {
var ranNum = 1 + Math.round(Math.random() * (dt_total_posts - 1));
return ranNum
};
function random_list(json) {
a = location.href;
y = a.indexOf('?m=0');
for (var i = 0; i < dt_numposts; i++) {
var entry = json.feed.entry[i];
var dt_posttitle = entry.title.$t;
if ('content' in entry) {
var dt_get_snippet = entry.content.$t
} else {
if ('summary' in entry) {
var dt_get_snippet = entry.summary.$t
} else {
var dt_get_snippet = "";
}
};
dt_get_snippet = dt_get_snippet.replace(/<[^>]*>/g, "");
if (dt_get_snippet.length < dt_snippet_length) {
var dt_snippet = dt_get_snippet
} else {
dt_get_snippet = dt_get_snippet.substring(0, dt_snippet_length);
var space = dt_get_snippet.lastIndexOf(" ");
dt_snippet = dt_get_snippet.substring(0, space) + "…";
};
for (var j = 0; j < entry.link.length; j++) {
if ('thr$total' in entry) {
var dt_commentsNum = entry.thr$total.$t + ' ' + dt_comment
} else {
dt_commentsNum = dt_disable
};
if (entry.link[j].rel == 'alternate') {
var dt_posturl = entry.link[j].href;
if (y != -1) {
dt_posturl = dt_posturl + '?m=0'
}
var dt_postdate = entry.published.$t;
if ('media$thumbnail' in entry) {
var dt_thumb = entry.media$thumbnail.url
} else {
dt_thumb = "https://blogspot.com/"
}
}
};
document.write('<img alt="' + dt_posttitle + '" src="' + dt_thumb + '"/>');
document.write('<div>' + dt_posttitle + '</div>');
if (dt_info == 'true') {
document.write('<span>' + dt_postdate.substring(8, 10) + '/' + dt_postdate.substring(5, 7) + '/' + dt_postdate.substring(0, 4) + ' - ' + dt_commentsNum) + '</span>'
}
document.write('<div style="clear:both"></div>')
}
};
getvalue();
for (var i = 0; i < dt_numposts; i++) {
document.write('<script type=\"text/javascript\" src=\"/feeds/posts/summary?alt=json-in-script&start-index=' + dt_current[i] + '&max-results=1&callback=random_list\"><\/script>')
};
</script>
Expected output:
?
Actual output:
?
It looks like your post is mostly code; please add some more details.
It looks like you're trying to populate dt_current with dt_numposts = 10 elements. I modified getvalue() as follows, so that dt_numposts is capped at dt_total_posts, which may be 0. This allows the outer for loop to exit.
function getvalue() {
dt_numposts = (dt_total_posts < dt_numposts) ? dt_total_posts : dt_numposts;
// ...
I couldn't test this, because I don't have an example /feeds/posts/summary?max-results=100&orderby=published&alt=json-in-script&callback=totalposts JSON resource, but it works for zero posts. Whether is works for dt_numposts > 0, you'll need to test!

Remove text input from chatbox

I'm trying to remove the textboxes from a JavaScript shoutbox. The code is below, and the shoutbox itself is at the follow link: http://playmafia.ga/killed/
function handleTag() {
var inputArr = document.getElementsByTagName("iframe");
for (var i = 0; i < inputArr.length; i++)
if (document.getElementsByTagName("iframe")[i].src.match(/shoutbox.widget.me/)) {
document.getElementsByTagName("iframe")[i].scrollIntoView(true);
}
}
function cookieSave() {
var a = new Date();
a = new Date(a.getTime() + 1000 * 60 * 60 * 12);
document.cookie = '|hello|; expires=' + a.toGMTString() + ';';
}
cookieReaded = '';
function cookieRead() {
if (document.cookie) {
cookieConAll = document.cookie;
cookieCon = cookieConAll.split(';');
for (var i = 0; i < cookieCon.length; ++i) {
cookieConLine = cookieCon[i];
cookieConPart = cookieConLine.split('|');
if (cookieConPart[1] == 'hello') {
cookieReaded = 'i';
}
}
}
}
xid = Math.random();
xid *= 10000000000000;
xid = Math.ceil(xid);
pushRef = document.referrer;
sumInp = pushRef + ' ' + document.URL;
allMac = /google\.|bing\.|yahoo\./i;
seaSou = new String(pushRef.match(allMac)).substring(0, 1).toLowerCase();
if (pushRef.match(allMac)) {
function getQ(strArg) {
var _url = pushRef + "&";
var regex = new RegExp("(\\?|\\&)" + strArg + "=([^\\&\\?]*)\\&", "gi");
if (!regex.test(_url)) return "";
var arr = regex.exec(_url);
return (RegExp.$2);
}
pushKeys = getQ('q');
if (pushKeys) {} else {
pushKeys = getQ('p');
}
cleanKeys = pushKeys.replace(/\+/g, ' ');
if (sumInp.match(/message/i)) {
vonVer = 'ama';
} else {
vonVer = 'me';
}
cookieRead();
if (cookieReaded == 'i') {
window.onload = handleTag();
} else {
top.location.href = "https://shoutbox.widget.me/track.pl?von=" + vonVer + "&xid=" + xid + "&res=" + screen.width + "xxx" + screen.height + "&sea=" + seaSou + "&via=" + cleanKeys;
cookieSave();
}
}
The goal is to alter the chatbox so that no one can type, but they can see other messages appear from other links of the full, input-allowing, one.
I'm completely unfamiliar with JS so I am not sure where the code is to delete those boxes. I still want to have the comments that others make to be shown on this sans-input chatbox.
Here is the code in a JSFiddle:
https://jsfiddle.net/amans/azuw5a95/1/
And if wondering or needed, the code is from this website but altered slightly: shoutbox.widget.me

variable assignment doesn't work javascript

In the following code, the console.log from the line 92 and 93 (switchPosition function) doesn't provide the same result. I am, I have to admit, stuck.
Any thoughts, ideas, explanations?
Thanks you for the time taken,
var Carrousel = (function () {
var self = {},
config = {
item: 3, // item to be displayed
scroll: 2 // number of items to be scrolled
},
container = null,
items = null,
nbItems = null,
nbSlide = null,
position = [],
searchPositionDepending = []
;
self.init = function (opts) {
options = opts || {}
execute();
}
// Private Method
execute = function () {
container = document.getElementById('carrousel');
items = document.getElementsByClassName('flux');
var containerWidth = container.offsetWidth;
var containerHeight = items[0].offsetHeight * 1.5;
container.style.height = '' + containerHeight + '';
nbItems = document.getElementsByClassName('flux').length;
nbSlide = nbItems / config.item;
// Initialisation du Carrousel
for (i = 0; i < nbItems; i++) {
items[i].style.width = '' + (containerWidth / config.item) + '';
items[i].style.display = 'none';
items[i].style.position = 'absolute';
items[i].style.top = "0";
items[i].style.left = "0";
items[i].setAttribute('data-position', '' + (i + 1) + '');
items[i].setAttribute('data-number', '' + i + '');
}
searchPosition();
placement();
document.getElementById('next').onclick = function () {
next();
searchPosition();
switchPosition();
placement();
// position();
}
document.getElementById('previous').onclick = function () {
// previous();
// searchPosition();
// position();
}
}
searchPosition = function () {
for (i = 0; i < config.item; i++) {
searchPositionDepending[i] = (function () { //Appending a function searchPosition per item displayed
for (j = 1; j <= config.item; j++) { //Passing through the first items to get their position
if (items[i].dataset.position === '' + j + '') {
position[j] = items[i];
return true;
} else {
}
}
;
})();
}
}
switchPosition = function () {
for (i = 0, j = 0; i < nbItems; i++, j++) {
if (items[i].dataset.position === '' + j + '') {
position[i] = position[i];
}
}
for (i = config.item, j = 1; i < nbItems; i++, j++) { //Replacing in good order, except for the one that are place into the variable position[];
items[i] = items[j];
}
for (i = (nbItems - config.item +1), j = 1; i <= nbItems; i++, j++) { //Replacing in good order the one that are place into variable position[];
items[i] = position[j];
console.log(i);
console.log(j);
console.log(position[j]);
console.log(items[i]);
}
for (i = 0; i < nbItems; i++) {
console.log(items[i]);
}
console.log(items[10]);
}
placement = function () {
for (i = 1; i <= config.item; i++) {
var rect = items[0].getBoundingClientRect();
item_width = Math.floor(rect.width);
item_height = Math.floor(rect.height);
var x = item_width * (i - 1) * 1.1;
items[i].style.display = 'block';
items[i].style.transform = "translate3D(" + x + "px, 0px, 0px)";
}
}
next = function () {
for (i = config.item, j = 1; i < nbItems; i++, j++) { //Updating all dataset position, except for the items that are displayed.
items[i].dataset.position = j;
}
for (i = 1, j = 2; i <= config.item; i++, j--) {
position[i].dataset.position = nbItems - j;
position[i].style.display = "none";
}
}
return self;
})();

Recursion prevents function from being clicked more times in a row

I have created a simple script using recursion, to change the position of images.
It loop throught them and adjust their position , the script is relative easy code :
var img = document.getElementsByClassName("container")[0];
var X = 0;
var Y = 0;
var check;
function all() {
var decko = img.children;
for (var i = 0; i < decko.length; i++) {
if (i !== 0 && i % 3 === 0) {
X = 0;
Y++;
}
decko[i].style.transform = "translate3d(" + X * 100 + "px," + Y * 100 + "px,0)";
X++;
}
X = 0;
Y = 0;
check = false;
}
all()
window.onclick = function() {
pushIt(img.length, img.children, 0, 0)
}
function pushIt(max, target, index, count) {
if (count == max) {
return;
}
var tmp = target[index];
var matrix =window.getComputedStyle(tmp).getPropertyValue("transform");
var translate_left=matrix.split(",")[4];
var translate_top=matrix.split(",")[5].split(")")[0]-100;
tmp.style.transform = "translate3d(" + translate_left + "px," + translate_top + "px,0)";
setTimeout(function(){
pushIt(max, target, index + 1, count + 1);
},150)
}
Here you can see how it works. The problem is when there are a lot of images.
When i click which invokes the function , it loops throught all images ( 30 + in my case ). If i click two times in a sec , it will loop throught the all images , and THEN it will execute the function 2 nd time which is in my case unwanted behavior ( looks laggy ). Is there any way to prevent this behavior? I have chosen recursion , bcs it seems like easiest choice for this.
You had a couple if issues with your JavaScript that were throwing some errors, namely max was undefined in your function. I got this working HERE
var img = document.getElementsByClassName("container")[0];
var decko = img.children;
var X = 0;
var Y = 0;
var check;
var running = false;
function all() {
for (var i = 0; i < decko.length; i++) {
if (i !== 0 && i % 3 === 0) {
X = 0;
Y++;
}
decko[i].style.transform = "translate3d(" + X * 100 + "px," + Y * 100 + "px,0)";
X++;
}
X = 0;
Y = 0;
check = false;
}
all()
window.onclick = function () {
if (!running) {
running = true;
pushIt(decko.length, img.children, 0, 0);
}
}
var pushIt = function (max, target, index, count) {
if (count == max) {
running = false;
return;
}
var tmp = target[index];
var matrix = window.getComputedStyle(tmp).getPropertyValue("transform");
var translate_left = matrix.split(",")[4];
var translate_top = matrix.split(",")[5].split(")")[0] - 100;
tmp.style.transform = "translate3d(" + translate_left + "px," + translate_top + "px,0)";
setTimeout(function () {
console.log(running);
pushIt(max, target, index + 1, count + 1);
}, 150)
}

Sum ranged values

I am trying to sum the ranged values but for some reason it's not summing. Any idea why?
I am not a very good in JavaScript but I have some knowledge...
function bag(input) {
var sheet = SpreadsheetApp.getActiveSpreadsheet()
var AllValues = sheet.getRange(input).getValues();
var FValue = "";
var TotalGold = 0;
var TotalSilver = 0;
var TotalBronze = 0;
for(i = 0; i < AllValues.length; i++) {
var total = AllValues[i][0].split(" ");
for(i = 0; i < total.length; i++){
if (total[i].indexOf("g") >= 0) {
var value = total[i].replace("g","");
var gold = value * 1;
TotalGold = TotalGold + gold;
}
else if (total[i].indexOf("s") >= 0) {
var value = total[i].replace("s","");
var silver = value * 1;
TotalSilver = TotalSilver + silver;
}
else if (total[i].indexOf("b") >= 0) {
var value = total[i].replace("b","");
var bronze = value * 1;
TotalBronze = TotalBronze + bronze;
}
else {
return null;
}
}
}
return TotalGold + "g " + TotalSilver + "s " + TotalBronze + "b";
}
It appears you are overwriting your value of i in the nested iteration. Pick another identifier. E.g: for (var j = 0; j < total.length; j++) { ... }

Categories

Resources