JS Changing Classes issue - javascript

I'm using API sockets to update the market data.
and I want to classes change when the price goes up and down,
my first class (_class) is working successfully,
second class (_class2) is working at the start by changing to UP (pump) but it won't get back to down (dump) when the price goes down just like the first class. I'm in a bit of confusion coz I'm not so experienced at js.
can anyone tell me where I am mistaken?
window.updateMarkets = function (data) {
if (data.coin != undefined) {
var coin = 'BTC_' + data.coin;
var coin_data = data.msg;
var _coinTable = $('#coins-info-table');
var row = _coinTable.find("tr#" + coin);
price = _coinTable.find("tr#" + coin + " .price");
change = _coinTable.find("tr#" + coin + " .change");
volume = _coinTable.find("tr#" + coin + " .volume");
capital = _coinTable.find("tr#" + coin + " .market_capital");
supply = _coinTable.find("tr#" + coin + " .supply");
_price = formatter.format(coin_data.price);
previous_price = $(price).data('usd');
_class = coin_data.cap24hrChange >= 0 ? 'increment' : 'decrement';
_class2 = coin_data.cap24hrChange >= 0 ? 'pump' :'dump';
if (coin_data.cap24hrChange >= 0.0) {
$(price).html(_price).removeClass().addClass(_class + ' price').data("usd", _price);
} else {
$(price).html(_price).removeClass().addClass(_class + ' price').data("usd", _price);
}
if (coin_data.cap24hrChange >= 0.0) {
$(price).html(_price).removeClass().addClass(_class2 + ' price').data("usd", _price);
} else {
$(price).html(_price).removeClass().addClass(_class2 + ' price').data("usd", _price);
}
$(volume).html(formatter.format(coin_data.volume));
$(capital).html(formatter.format(coin_data.mktcap));
$(supply).html(coin_data.supply);
if (_price !== previous_price) {
_class = previous_price < _price ? 'increment' : 'decrement';
_class2 = previous_price < _price ? 'pump' : 'dump';
$(row).addClass(_class);
setTimeout(function () {
$(row).removeClass('increment decrement');
}, 300);
}
}
};

Related

How to process large jquery each loop without crashing browser(mainly firefox)

I made a javascript code to create some html element in parent iframe based on user selection from an iframe in a popup.
My code is given below.
The each loop may contain 50 to 150 iteration. Sometimes when I call function AddProcedures the Mozilla crashes during iteration, Is there any way to fix this issue or to reduce the browser load. I tried to put setTimeout after some code blocks but it didn't help.
I have also changed the for loop to jquery each, just to try if that helps.
var tot_codes = 0;
function doAddProcedure(thisVal,resolve){
var enc_id = $("#cpt_encounter").val();
var rowId = window.parent.$("[data-encounterBilled='"+ enc_id +"']").closest('tr').attr('id'); // table row ID
var recalc = parseInt(rowId.substring(rowId.indexOf('id-')+3));
var countval = $("#last_id").val();
//Load issue Fix
//Old code
//for (i = 0; i < document.cpt.elements.length; i++) {
//if (document.cpt.elements[i].type == "checkbox") {
//if (document.cpt.elements[i].checked == true) {
$('#cpt input:checkbox:checked').each(function(){
setTimeout(function() { }, 100);
var currentCodeMod = $(this).attr("data-codemod");
var currentCodeTypid = $(this).attr("data-codeTypeid");
if (currentCodeMod == null)
return;
tot_codes++;
var nextcntval = parseInt(countval) + 1;
var code_no = $(this).attr("id").replace("cpt_chkbx", "");
var Code = $("#codeVal" + code_no).val();
var just = $("#codeType" + code_no).val();
var categoryId = $("#codeType" + code_no).data("categoryid"); //Added to get category //Bug Fix
var Name = $("#cpttext" + code_no).val();
var codedisp = Code + ':' + Name;
var Modifier = '';
//if($("#modifier_setngs").val() == 1){
var Modifier1 = $("#modcpt1"+code_no).val() != '' ? $("#modcpt1"+code_no).val() + ":" : '';
var Modifier2 = $("#modcpt2"+code_no).val() != '' ? $("#modcpt2"+code_no).val() + ":" : '';
var Modifier3 = $("#modcpt3"+code_no).val() != '' ? $("#modcpt3"+code_no).val() + ":" : '';
var Modifier4 = $("#modcpt4"+code_no).val() != '' ? $("#modcpt4"+code_no).val() + ":" : '';
Modifier = Modifier1 + Modifier2 + Modifier3 + Modifier4;
//}
var codetableid = $("#code_tab_id" + code_no).val();
var j = countval; /* lineitem wise uniqid */
//var encounter = window.parent.$('#codetype-' + j).closest('tr.charge-entry-row').find('.expand-actions').attr('data-encounterid');
var encounter = enc_id;
var codeforarr = encounter + ':' + just + ':' + Code + '::' + Modifier;
window.parent.pushToArray(codeforarr);
var f = 0;
$(window.parent.$("#codetype-" + countval).parents().find('.inner-table .charge-entry-row')).each(function() {
//console.log($(this).find('.inputStringHidden').val() + '/' + codeforarr);
if ($(this).find('.inputStringHidden').val() == codeforarr) {
var exis_row_id = $(this).find('.inputStringHidden').attr('id').split('inputStringHidden-');
j = exis_row_id[1].toString();
f = 1;
$(this).find('.front_pay_codes_display').trigger('click');
}
});
if (f == 0) {
if (window.parent.document.getElementById('inputStringHidden-' + countval).value != '') {
window.parent.$("#codetype-" + countval).children().parent().parent().parent().siblings().find('.addnew-row').attr('data-rowadd', 'fromdb').trigger("click");
countval = parseInt(countval) + 1;
j = countval.toString();
}
window.parent.$("#add-" + countval).trigger("click");
window.parent.$("#codetype-" + (countval)).val(currentCodeTypid);
window.parent.$("#codetype-" + countval).trigger("change");
}
window.parent.document.getElementById('inputString' + j).value = codedisp;
window.parent.document.getElementById('category-' + j).value = categoryId; //Added to set category //Bug Fix
window.parent.document.getElementById('string_id' + j).value = Code;
window.parent.document.getElementById('string_value' + j).value = Name;
window.parent.document.getElementById('inputStringHidden-' + j).value = codeforarr;
window.parent.document.getElementById('codetableid-' + j).value = codetableid;
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.val-change-bit').val(1);
setTimeout(function() {}, 100);
window.parent.$("#suggestions" + j).hide();
window.parent.$("#inputString" + j).focus();
var uniqidHidden = window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.uniqid-hidden').val();
window.parent.$('#add-modifier' + j).parent().find('.displaymode-elem').text(Modifier);
//if($("#modifier_setngs").val() == 1){
if (f == 0) {
window.parent.$('#add-modifier' + j).parent().find('.displaymode-elem').addClass('area-hide');
}else{
window.parent.$('#add-modifier' + j).parent().find('.displaymode-elem').removeClass('area-hide');
}
window.parent.$('#modifiers' + uniqidHidden).val(Modifier);
arr = Modifier.split(':');
window.parent.$('#modifier-' + uniqidHidden + '-1').val(arr[0]);
window.parent.$('#modifier-' + uniqidHidden + '-2').val(arr[1]);
window.parent.$('#modifier-' + uniqidHidden + '-3').val(arr[2]);
window.parent.$('#modifier-' + uniqidHidden + '-4').val(arr[3]);
//}
var eclaimPlanActive = window.parent.$('#eclaimPlanActive').val();
var price = $("#cpt_price" + code_no).val();
var price_level = $("#pricelevelhidden" + code_no).val();
if (price == 0 || price == null)
price = 0;
window.parent.$('#price-' + j).val(price);
window.parent.$('#bill-pricelevel-' + j).val(price_level);
/** Charge Total **/
var chargeTotal = window.parent.$('#charge-total').text().replace(/[\s\,]/g, '').trim();
if (chargeTotal == '')
chargeTotal = parseFloat(0);
var tempChargeTotal = parseFloat(chargeTotal) + parseFloat(price);
window.parent.$('#charge-total span').html(tempChargeTotal);
/** End **/
var units = $("#cpt_units" + code_no).val(); //data[0]['units']
if (units == 0 || units == null)
units = 1;
window.parent.$('#qty-' + j).val(units);
var tax = 0;
var disc = 0;
setTimeout(function() { }, 100);
if (window.parent.$('#tax-' + j).length > 0)
tax = window.parent.$('#tax-' + j).val().replace(/[\s\,]/g, '');
if (window.parent.$('#discount-' + j).length > 0)
disc = window.parent.$('#discount-' + j).val().replace(/[\s\,]/g, '');
var amount = price * units;
amount = amount + ((amount * tax) / 100);
if (disc > 0) {
var p = price * units;
var dc = ((p * disc) / 100);
amount = amount - dc;
}
/** Discount Total **/
var disTotal = window.parent.$('#discount-total').text().replace(/[\s\,]/g, '').trim();
if (disTotal == '')
disTotal = parseFloat(0);
var tempDisTotal = parseFloat(disTotal) + parseFloat(dc);
if (isNaN(tempDisTotal) == true) {
tempDisTotal = '0.00';
}
window.parent.$('#discount-total').html(tempDisTotal);
/** End **/
if (!parseFloat(window.parent.$('#lineitempaid-' + j).val()))
window.parent.$('#lineitempaid-' + j).val('0.00');
window.parent.$('#total-' + j).val(amount);
window.parent.$('#remainder-' + j).val(amount);
window.parent.$('#hidremainder-' + j).val(amount);
//insurance and patient_share
if (eclaimPlanActive == '1') {
var codetableid = window.parent.$('#codetableid-' + j).val();
var parentRowVal = parseInt(window.parent.$('#codetableid-' + j).closest('tr').find('.row_value').attr('data-rowvalue')) - 1;
var insData1 = window.parent.$('tr#row-id-' + parentRowVal + ' .encounter').attr('data-insdata1');
window.parent.getBenefitCategoryOfCode(j, codetableid, insData1);
if (window.parent.$('#have-benefit').val() == '0') {
var insData2 = window.parent.$('tr#row-id-' + parentRowVal + ' .encounter').attr('data-insdata2');
window.parent.getBenefitCategoryOfCode(j, codetableid, insData2);
}
}
var passParams = '';
window.parent.calculate('qty-' + j, passParams);
//Updating the title
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.fi-searchitems').attr('data-original-title', codedisp);
if (f == 0) {
//Display DIv :: Relace with new values
var cloneLabel = window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.show_label').clone();
//In Edit Mode
if (cloneLabel.find('.displaymode-elem').length > 0) {
var $max_length = 16;
var trucncateCode = Name;
if (trucncateCode.length > $max_length)
trucncateCode = trucncateCode.substring(0, $max_length) + '...';
cloneLabel.find('.front_pay_codetype').text(just + ":");
cloneLabel.find('.front_pay_code').text(trucncateCode);
cloneLabel.find('.displaymode-elem').removeClass('area-hide');
cloneLabel.removeClass('area-hide');
cloneLabel.find("input[name='code_type']").val(just).attr('id', 'code_type-' + j);
cloneLabel.find("input[name='string_id']").val(Code).attr('id', 'string_id-' + j);
cloneLabel.find("input[name='string_value']").val(Name);
var dataType = $("#inputString" + j).closest('tr.charge-entry-row').find('.data_type').val();
if (dataType == "lab") {
var lab = $("select[name='lab_type']").find('option:selected').val();
if (cloneLabel.find("input[name='lab_type']").length > 0) {
cloneLabel.find("input[name='lab_type']").val(lab);
} else {
cloneLabel.append('<input type="hidden" name="lab_type" class="lab_type" value="' + lab + '">');
}
} else {
cloneLabel.find("input[name='lab_type']").remove();
}
setTimeout(function() { }, 100);
//Making the view
cloneLabel.removeClass('area-hide');
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.front_pay_codes_editelem').removeClass('area-show').addClass('area-hide');
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.show_label').replaceWith(cloneLabel);
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.show_autosuggest').html('');
}
window.parent.$("#codetype-" + countval).children().parent().parent().parent().siblings().find('.addnew-row').attr('data-rowadd', 'fromdb').trigger("click");
countval = nextcntval.toString();
}
else {
window.parent.$("#suggestions" + j).hide();
countval = countval.toString();
}
setTimeout(function() { }, 150);
});
window.parent.reCalculatePlanEncounterWise(recalc);
resolve("Success!");
}
function doAddPromise(thisVal){
return new Promise(function(resolve){
doAddProcedure(thisVal,resolve);
});
}
function AddProcedures(thisval)
{
$('#procedureSaveButton').text('Processing....');
// $('.fa-spinner').removeClass('hide');
top.ShowAjaxLoader('Loading..');
setTimeout(function(){
}, 2000);
//top.ShowAjaxLoader('Loading..');
setTimeout(function(){
$.when(doAddPromise(thisval)).done(function(){
if (tot_codes > 0) {
window.parent.phFrntpayClosePopup();
top.notification('Successfully added the procedures.');
//top.HideAjaxLoader('Loading..');
top.HideAjaxLoader();
$('body').removeClass('modal-open');
} else {
top.notification('Please select atleast one procedure.');
$('#procedureSaveButton').text('Add Procedures');
//$('.fa-spinner').addClass('hide');
top.HideAjaxLoader();
}
});
}, 10);
}

Trying to grab a innerhtml from within a innerhtml

So i've recently ran into issues with trying to move specific pieces of a <p> </p> called result. as such i thought hey! wouldn't be easier to break each part inside of result down into another <p>!? well it works lol however trying to grab that inner <p> that in this cause we'll call vault is being difficult. I've tried several methods but cant seem to grab it's value from outside in a document.getElementByID....here's the code below for the html.
document.getElementById("result").innerHTML = Monster + "<p id='vault'> || HP: " + HP + "</p> || Defense: " + Def + " || Attack: " + ATK + " || Can it Dodge/Block: " + DB + " || Can it retaliate: " + RET + " || Initative: " + INT + " || Exp: " + MEXP + " <input type='submit' class='new' onclick='Combat(" + loop + ")' value='FIGHT!'></input>" + "<br><br>" + A;
}
then the script that eventually calls it
function Combat(id){
document.getElementById("vault").innerHTML = id;
document.getElementById("C").value = id
}
So what i'm trying is change id "C" to ID"VAULT" inside of id ("result").
any ideas on why i can't grab vault?
What you want would be easier with Object-oriented JavaScript.
Usually when coding JavaScript you want to be as independent of the DOM (HTML) as possible.
Consider the following example:
/**
* Monster
*/
var Monster = (function() {
function Monster(HP, DEF, ATK, DB, RET, INT, MEXP) {
if (HP === void 0) {
HP = 100;
}
if (DEF === void 0) {
DEF = 10;
}
if (ATK === void 0) {
ATK = 100;
}
if (DB === void 0) {
DB = 10;
}
if (RET === void 0) {
RET = true;
}
if (INT === void 0) {
INT = 100;
}
if (MEXP === void 0) {
MEXP = 100;
}
this.HP = HP;
this.DEF = DEF;
this.ATK = ATK;
this.DB = DB;
this.RET = RET;
this.INT = INT;
this.MEXP = MEXP;
}
/**
* getHTML
*/
Monster.prototype.getHTML = function() {
return "HP: " + this.HP + " || Defense: " + this.DEF + " || Attack: " + this.ATK + " || Can it Dodge/Block: " + this.DB + " || Can it retaliate: " + this.RET + " || Initative: " + this.INT + " || Exp: " + this.MEXP;
};
/**
* attacked
*/
Monster.prototype.attacked = function(damage) {
if (damage === void 0) {
damage = 0;
}
//check defences
if (damage > this.DEF + this.DB) {
//take damage
this.HP -= (damage - this.DEF + this.DB);
}
if (this.HP < 0) {
//Return true if it slew the monster
return true;
} else {
//Return false if the monster survived
return false;
}
};
return Monster;
}());
/**
* Area
*/
var Area = (function() {
function Area(name) {
if (name === void 0) {
name = "Vault";
}
this.name = name;
this.monsters = [];
}
/**
* addMonster
*/
Area.prototype.addMonster = function(monster) {
this.monsters.push(monster);
return this;
};
/**
* attackVault
*/
Area.prototype.assault = function(damage) {
if (damage === void 0) {
damage = 0;
}
//If no monster
if (this.monsters.length < 1) {
alert("You have cleared this vault");
return true;
} else {
//If monsters exists, attack the first
var monsterKilled = this.monsters[0].attacked(damage);
//If the monster was killed
if (monsterKilled) {
//remove monster
this.monsters.splice(0, 1);
//Alert the player
alert("Well done hero!\nOnly " + (this.monsters.length) + " remaining!");
}
}
//Return maybe monsters left?
return this.monsters.length < 1;
};
return Area;
}());
////GRAP HTML ELEMENT
var output = document.getElementById("current-monster");
////RUNNING YOUR GAME
//Build and populate world
var vault = new Area();
vault
.addMonster(new Monster())
.addMonster(new Monster());
//INTERACTION
alert("Start");
//Hit the vault till it is empty
while (vault.assault(45) != true) {
output.innerHTML = vault.monsters[0].getHTML();
alert("Attack!");
}
output.innerHTML = "Victory!";
<h1 id="title">Monster Game!</h1>
<h2 id="current-monster"></h2>
See how i can easily access the data though JavaScript?
When coding a JavaScript game, it makes sense to keep important data and structures in your JavaScript.
Ok so i added the bit - ADyson suggested...
document.getElementById("result").innerHTML = Monster + "<p id='vault(" + loop + ")'> || HP: " + HP + "</p>" + " || Defense: " + Def + " || Attack: " + ATK + " || Can it Dodge/Block: " + DB + " || Can it retaliate: " + RET + " || Initative: " + INT + " || Exp: " + MEXP + " <input type='submit' class='new' onclick='Combat(" + loop + ")' value='FIGHT!'></input>" + "<br><br>" + A;
}
}
}
function Chest(id){
window.open('LootGen.html', '_blank');
}
function Combat(id){
var id = document.getElementById("vault" + id).innerHTML;
document.getElementById("C").value = id;
submit();
}
However now when i run it on the " ).innerHTML;" i'm getting a
MonsterGen.html:426 Uncaught TypeError: Cannot read property
'innerHTML' of nullCombat # MonsterGen.html:426onclick #
MonsterGen.html:1
Ok I found out exactly was was going wrong; it was the naming convention in the <P>.
Originally it was id='vault(" + loop + ")'... this would make it vault(1) etc.... however the getElement was getting it by this call ("vault" + id) so it would call vault1....thus two separate id's entirely....that's why it was returning null.
So I removed the () in the equation and now everything is working beautifully.

Javascript If statement not acknowledged

Here is the code
setHighScore: function() {
var highScore = 0;
if (!window.snake || !window.fpsls || !window.fmlts) {
return;
}
if (++bot.tickCounter >= 20) {
bot.tickCounter = 0;
var currentScore = parseInt(Math.floor(150 * (window.fpsls[window.snake.sct] +
window.snake.fam / window.fmlts[window.snake.sct] - 1) - 50) / 10);
if (Number(currentScore) > Number(highScore)) {
highScore = currentScore;
window.localStorage.setItem('highScoreLoc', highScore);
console.log('Current Score: ' + currentScore);
}
}
},
onFrameUpdate: function() {
// Botstatus overlay
var generalStyle = '<span style = "opacity: 0.35";>';
window.fps_overlay.innerHTML = generalStyle + 'FPS: ' +
userInterface.framesPerSecond.getFPS() + '</span>';
if (window.position_overlay && window.playing) {
// Display Personal High Score
userInterface.setHighScore();
window.scoreHuD.innerHTML = generalStyle +
'Your High Score: ' + parseInt(Number(window.localStorage.getItem('highScoreLoc')));
// Display the X and Y of the snake
window.position_overlay.innerHTML = generalStyle +
'X: ' + (Math.round(window.snake.xx) || 0) +
' Y: ' + (Math.round(window.snake.yy) || 0) +
'</span>';
}
It's meant to check if the score is bigger than the high score then save the new high score (if its bigger) and after that print it on screen. But it isn't for some reason
line 10 is the if statement
the 2 lines above it are to find the current score and i know it outputs the current score because of line 13
Its Tampermonkey
and the actual script https://github.com/Classicanon/Slither.io-bot/blob/master/bot.user.js For (Slither.io)

nodejs, function jumping to a completely unrelated line for no reason?

So I'm trying to add a command to an already existing project InsomBot to retrieve a League of Legends player's information, I am using lol-api found on npm for this, the only modifications made to this package were to update the API url's as they were outdated and incorrect, my code is below and an image of the issue in a debugger is also below, once the program reaches line 105 it jumps to line 111 for seemingly no reason, perhaps I'm missing a simple indentation error here or I'm not closing something properly, etc. Any help would be appreciated.
i.stack.imgur.com/PnDHU.png (Seems I can't post more than 2 links)
var cc = require('config-multipaas'),
env = require('./env.json'),
Discord = require('discord.js'),
Imgur = require("imgur-search"),
Giphy = require('giphy-wrapper')(env["giphy_key"]),
urban = require('urban'),
api = require('lol-api');
//lol
api.configure("API_KEY_HIDDEN");
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1'
var config_overrides = {
PORT: server_port
}
var config = cc(config_overrides);
var mybot = new Discord.Client();
var isearch = new Imgur(env["imgur_key"]);
var termCount = new Map();
var seenURLs = new Map();
mybot.on("message", function (msg) {
var message = msg.content;
//keywords
var giphy = "/giphy ";
var imgurKey = "/img ";
var hatter = "hater";
var def = "/define ";
var commands = "/commands";
var lolstatus = "/lolstatus";
// Reply to direct mentions
if (msg.isMentioned(mybot.user)) {
mybot.reply(msg, "right back atcha");
return;
}
// Giphy
var giphyIndex = message.indexOf(giphy);
if (giphyIndex > -1) {
var term = message.substring(giphyIndex + giphy.length).trim().replace(/\s/g, "+");
var count = termCount.get(term) || 0;
// console.log("count for term " + term + " is: " + count);
termCount.set(term,count+1);
Giphy.search(term, 100, count, function (err, data) {
if (err) {
return;
}
var items = data.data;
var index = Math.floor(Math.random() * items.length / 2.0);
// console.log("found " + items.length + " items for " + term);
while (index < items.length && seenURLs.get(items[index].url) !== undefined) {
index++;
}
// console.log("using? result number " + index);
if (items.length > index) {
var item = items[index];
seenURLs.set(item.url, 1);
mybot.sendMessage(msg, item.url);
} else {
var apology = "sorry, I couldn't find any giphys for the term: " + term;
mybot.reply(msg, apology);
}
});
return;
}
//Imgur
var imgurIndex = message.indexOf(imgurKey);
if (imgurIndex > -1) {
var term = message.substring(imgurIndex + imgurKey.length).trim().replace(/\s/g, "+");
// console.log("searching imgur for term: " + term);
isearch.search(term).then(function(results) {
// console.log("found results: " + JSON.stringify(results,null,2));
if (results === undefined || results.length === 0) {
mybot.reply(msg, "sorry, I couldn't find any imgurs for the term: " + term);
return;
}
var image = results[Math.floor(Math.random() * results.length)];
mybot.sendMessage(msg, "Here's a description of an image: " + image.title + " " + image.description + " " + image.link);
});
return;
}
//lol
var lolIndex = message.indexOf(lolstatus);
debugger;
if (lolIndex > -1) {
debugger;
var term = message.substring(lolIndex + lolstatus.length).trim().replace(/\s/g, "+");
debugger;
api.summonerByName(term, 'na', function(results){
debugger;
console.log(results);
});
}
//Define
var defIndex = message.indexOf(def);
if (defIndex > -1) {
var term = message.substring(defIndex + def.length).trim().replace(/\s/g, "+");
urban(term).first(function(json) {
if (json !== undefined) {
// console.log("got json from UD: " + JSON.stringify(json,null,2));
var definition = "" + json.word + ": " + json.definition + "\nupvotes: " + json.thumbs_up + " downvotes: " + json.thumbs_down + "\n\nExample: " + json.example;
mybot.reply(msg, definition);
}
else {
var apology = "sorry, I couldn't find a definition for: " + term;
mybot.reply(msg, apology);
}
});
}
//Hatter
if (message === hatter) {
mybot.sendMessage(msg, "https://pbs.twimg.com/media/CM5gg9YVAAAVMcn.png");
return;
}
//Commands
if (message === commands) {
mybot.sendMessage(msg, "Available commands:[/] giphy | img | define");
return;
}
});
mybot.login(env["discord_email"], env["discord_pass"]);
Line 105 = api.summonerByName(term, 'na', function(results){
Line 111 = var defIndex = message.indexOf(def);
Line 111 contains the next statement after line 105, so it makes perfect sense.
api.summonerByName() is an asynchronous method, so its callback (lines 106 and 107) will be called only when there are results available, but the rest of your program will continue to run.

Javascript function logic

I have 3 js functions passing into each other for a blackjack game,
Hit() - Which gets a new card
checkCard() - which checks the card isnt in the users hand already
userTotal () - totals the value of the card and displays it in the DOM
The same card can appear more than once. the major flaw is with checking the card against others in an array of userCards
My logic is wrong. Could someone help me?
function hit() {
var cards = 2;
userIndex++;
var rankSelect = Math.floor(Math.random() * 13);
var suitSelect = Math.floor(Math.random() * 4);
var card = (rank[rankSelect] + suit[suitSelect]);
checkCard(card);
}
function checkCard(card) {
//if card = card in used array, select new card
for (i=0;i<=userCards.length;i++){
if (card = userCards[i] ) {
//selectCards(card)
var newRank = Math.floor(Math.random()*13);
var newSuit = Math.floor(Math.random()*4);
var newCard = (rank[newRank] + suit[newSuit]);
document.getElementById('userCards').innerHTML += "<td id=" + "UserCard" + "><img src="+"includes/images/cards/"+ newCard + ".png >"
userCards[userCards.length] = newCard;
userTotal();
} else {
userCards[userIndex] = card;
document.getElementById('userCards').innerHTML += "<td id=" + "UserCard" + "><img src="+"includes/images/cards/"+ card + ".png >"
userTotal();
}
}
}
function userTotal(userTotal){
var userTotal = 0;
for (i=0;i<userCards.length;i++){
var value = userCards[i];
if(userCards[i].charAt(0) == "a"){
value = parseInt((prompt("ACE, 1 or 11?")));
userTotal = userTotal + value;
document.getElementById("userTotal").innerHTML = userTotal;
} else if (userCards[i].charAt(0) == "k" || userCards[i].charAt(0) == "q" || userCards[i].charAt(0) == "j"){
value = 10;
userTotal = userTotal + value;
document.getElementById("userTotal").innerHTML = userTotal;
}else if (userCards[i].charAt(0) == "1" || userCards[i].charAt(1) == "0"){
value = 10;
userTotal = userTotal + value;
document.getElementById("userTotal").innerHTML = userTotal;
} else {
value = parseInt(userCards[i].charAt(0));
userTotal = userTotal + value;
document.getElementById("userTotal").innerHTML = userTotal;
}
if (userTotal > 21){
document.getElementById("userTotal").innerHTML = "Bust";
//document.getElementById("hit").disabled = true;
}
}
}
When you are inside 'checkCard' and if you get a card already in hand then you are again fetching a random card but this time you are not checking whether its already in hand or not.
You need to keep checking card until you won't get a fresh one.
replace this line :
var newCard = (rank[newRank] + suit[newSuit]);
with
card = (rank[newRank] + suit[newSuit]);
checkCard(card);
Try below :
function hit() {
var cards = 2;
userIndex++;
var rankSelect = Math.floor(Math.random() * 13);
var suitSelect = Math.floor(Math.random() * 4);
var card = (rank[rankSelect] + suit[suitSelect]);
checkCard(card);
}
function checkCard(card) {
//if card = card in used array, select new card
for (i = 0; i <= userCards.length; i++) {
if (card = userCards[i]) {
//selectCards(card)
var newRank = Math.floor(Math.random() * 13);
var newSuit = Math.floor(Math.random() * 4);
card = (rank[newRank] + suit[newSuit]);
chekCard(card);
document.getElementById('userCards').innerHTML += "<td id=" + "UserCard" + "><img src=" + "includes/images/cards/" + card + ".png >"
userCards[userCards.length] = card;
userTotal();
} else {
userCards[userIndex] = card;
document.getElementById('userCards').innerHTML += "<td id=" + "UserCard" + "><img src=" + "includes/images/cards/" + card + ".png >"
userTotal();
}
}
}
function userTotal(userTotal) {
var userTotal = 0;
for (i = 0; i < userCards.length; i++) {
var value = userCards[i];
if (userCards[i].charAt(0) == "a") {
value = parseInt((prompt("ACE, 1 or 11?")));
userTotal = userTotal + value;
document.getElementById("userTotal").innerHTML = userTotal;
} else if (userCards[i].charAt(0) == "k" || userCards[i].charAt(0) == "q" || userCards[i].charAt(0) == "j") {
value = 10;
userTotal = userTotal + value;
document.getElementById("userTotal").innerHTML = userTotal;
} else if (userCards[i].charAt(0) == "1" || userCards[i].charAt(1) == "0") {
value = 10;
userTotal = userTotal + value;
document.getElementById("userTotal").innerHTML = userTotal;
} else {
value = parseInt(userCards[i].charAt(0));
userTotal = userTotal + value;
document.getElementById("userTotal").innerHTML = userTotal;
}
if (userTotal > 21) {
document.getElementById("userTotal").innerHTML = "Bust";
//document.getElementById("hit").disabled = true;
}
}
}

Categories

Resources