Issue using addEventListener() in Javascript - javascript

I am making a battleships game, and I am currently working on placing your own boats. I want to be able to click, and one square on the grid to change color. I am adding event listeners to each tile through a nested for() loop, and getting each button to reference itself when the function is run.
The issue is, some of the tiles are changing color when I click on them, but others are not, and there is no pattern I can make out as to which change and which do not, as sometimes, I can click two or three times, and it will change color. The code is here. (I also added a color selector).
var x_client = 0;
var y_client = 0;
var battlefield_client = "";
for (y_client = 1; y_client < 11; y_client++) {
battlefield_client += "<tr>";
for (x_client = 1; x_client < 11; x_client++) {
battlefield_client += "<td onclick = '' class = 'tile' style='border: 3px solid black;' id=" + "cell_client_" + x_client + "_" + y_client + "><pre> </pre></td>";
}
battlefield_client += "</tr>";
}
$(document).ready(function() {
$("#tableGrid_client").html(battlefield_client); //loads table
for (y_client = 1; y_client < 11; y_client++) {
for (x_client = 1; x_client < 11; x_client++) {
boatStatusClient = document.getElementById('cell_client_' + x_client + "_" + y_client);
boatStatusClient.addEventListener("click", function(){boatGrid.placeBoat_client()});
}
}
document.getElementById("redButton").addEventListener("click", function(){boatGrid.colorSelect()});
document.getElementById("orangeButton").addEventListener("click", function(){boatGrid.colorSelect()});
document.getElementById("yellowButton").addEventListener("click", function(){boatGrid.colorSelect()});
document.getElementById("greenButton").addEventListener("click", function(){boatGrid.colorSelect()});
document.getElementById("blueButton").addEventListener("click", function(){boatGrid.colorSelect()});
document.getElementById("violetButton").addEventListener("click", function(){boatGrid.colorSelect()});
document.getElementById("brownButton").addEventListener("click", function(){boatGrid.colorSelect()});
document.getElementById("blackButton").addEventListener("click", function(){boatGrid.colorSelect()});
}); //This is for the color selector.
colorSelect : function() {
colorPick = event.target || event.srcElement;
colorPick = colorPick.id
console.log(colorPick);
if (colorPick == redButton) {
colorSelect = "red";
}
else if (colorPick == orangeButton) {
colorSelect = "orange";
}
else if (colorPick == yellowButton) {
colorSelect = "yellow";
}
else if (colorPick == greenButton) {
colorSelect = "green";
}
else if (colorPick == blueButton) {
colorSelect = "blue";
}
else if (colorPick == violetButton) {
colorSelect = "purple";
}
else if (colorPick == brownButton) {
colorSelect = "brown";
}
else if (colorPick == blackButton) {
colorSelect = "black";
}
console.log(colorSelect);
},
placeBoat_client : function() {
var demoColor = "orange"
var source_client = event.target.id;
console.log(source_client);
source_client.id = document.getElementById(source_client.id);
document.getElementById(source_client).style.backgroundColor = demoColor;
},
}

I have applied some fixes:
-Loops now use local variables to count iteration, so loop runs and uses its own variable. Next loop is not allowed to write over a variable in a different scope.
-You were adding anonymous functions were just function names were expected as
parameters. The second parameter inside an 'addEventListener' sets a call just
receiving function name, otherwise it is redundant.
-Changed a variable name to make it different from selectColor().
-Functions & variables on top of script, so are the first thing to be read.
-Small things like missing semicolons, extra commas, brackets, etc.
Here you go, hope it helps:
//var x_client = 0;
//var y_client = 0;
var battlefield_client = "";
var setColor='';
function colorSelect (){
colorPick = event.target || event.srcElement;
colorPick = colorPick.id;
console.log(colorPick);
if (colorPick == redButton) {
setColor = "red";
}
else if (colorPick == orangeButton) {
setColor = "orange";
}
else if (colorPick == yellowButton) {
setColor = "yellow";
}
else if (colorPick == greenButton) {
setColor = "green";
}
else if (colorPick == blueButton) {
setColor = "blue";
}
else if (colorPick == violetButton) {
setColor = "purple";
}
else if (colorPick == brownButton) {
setColor = "brown";
}
else if (colorPick == blackButton) {
setColor = "black";
}
console.log(setColor);
}
//---end of colorSelect
function placeBoat_client () {
var demoColor = "orange";
var source_client = event.target.id;
console.log(source_client);
source_client.id = document.getElementById(source_client.id);
document.getElementById(source_client).style.backgroundColor = demoColor;
}
for (var y_client = 1; y_client < 11; y_client++) {
battlefield_client += "<tr>";
for (var x_client = 1; x_client < 11; x_client++) {
battlefield_client += "<td onclick = '' class = 'tile' style='border: 3px solid black;' id=" + "cell_client_" + x_client + "_" + y_client + "><pre> </pre></td>";
}
battlefield_client += "</tr>";
}
$(document).ready(function() {
$("#tableGrid_client").html(battlefield_client); //loads table
for (var y_client = 1; y_client < 11; y_client++) {
for (var x_client = 1; x_client < 11; x_client++) {
boatStatusClient = document.getElementById('cell_client_' + x_client + "_" + y_client);
boatStatusClient.addEventListener("click", /*boatGrid.*/placeBoat_client, false);
}
}
document.getElementById("redButton").addEventListener("click", /*boatGrid.*/colorSelect, false);
document.getElementById("orangeButton").addEventListener("click", /*boatGrid.*/colorSelect, false);
document.getElementById("yellowButton").addEventListener("click", /*boatGrid.*/colorSelect, false);
document.getElementById("greenButton").addEventListener("click", /*boatGrid.*/colorSelect, false);
document.getElementById("blueButton").addEventListener("click", /*boatGrid.*/colorSelect, false);
document.getElementById("violetButton").addEventListener("click", /*boatGrid.*/colorSelect, false);
document.getElementById("brownButton").addEventListener("click", /*boatGrid.*/colorSelect, false);
document.getElementById("blackButton").addEventListener("click", /*boatGrid.*/colorSelect, false);
}); //end of ready

Related

JS Alert when items collected?

I have created a maze game where the user must collect all the coins in the maze, however I am trying to make an alert appear once the user has collected all the coins, not in any particular order just in general. The alert is being very troublesome at the moment and not working correctly and I'm not sure where I am going wrong based off my research into the matter. I am new to JavaScript so apologies for any clear mistakes.
EDIT I GOT TOLD TO REPHRASE MY QUESTION MORE DIRECTLY - SO THIS ISN'T A DUPLICATE QUESTION. I ALSO HAVE A MAP DECLARDED BUT CANNOT UPLOAD AS IT'S TOO MUCH CODE.
Also, when I say not working correctly, it will appear at random counts as supposed to when the last reward has been collected.
var el = document.getElementById('game');
function drawWorld(){
el.innerHTML = '';
for(var y = 0; y < map.length ; y = y + 1) {
for(var x = 0; x < map[y].length ; x = x + 1) {
if (map[y][x] === 1) {
el.innerHTML += "<div class='borders'></div>";
} else if (map[y][x] === 2) {
el.innerHTML += "<div class='reward'></div>";
} else if (map[y][x] === 3) {
el.innerHTML += "<div class='ground'></div>";
} else if (map[y][x] === 5) {
el.innerHTML += "<div class='character'></div>";
} else if (map[y][x] === 4) {
el.innerHTML += "<div class='ship'></div>";
}
}
el.innerHTML += "<br>";
}
winGame();
}
function restartGame(){
window.location.reload();
}
function winGame(){
if (!map[5].includes(2) && !map[2].includes(2) &&
!map[3].includes(2) && !map[2].includes(2) && !map[4].includes(2)
&& !map[2].includes(2))
alert("Well done!");
}
drawWorld();
document.onkeydown = function(event){
if (event.keyCode === 37){
if ( map[character.y][character.x-1] !== 1){
map[character.y][character.x] = 3;
character.x = character.x - 1;
map[character.y][character.x] = 5;
drawWorld();
}
} else if (event.keyCode === 38){
if ( map[character.y-1][character.x] !== 1){
map[character.y][character.x] = 3;
character.y = character.y - 1;
map[character.y][character.x] = 5;
drawWorld();
}
} else if (event.keyCode === 39){
if ( map[character.y][character.x+1] !== 1){
map[character.y][character.x] = 3;
character.x = character.x + 1;
map[character.y][character.x] = 5;
drawWorld();
}
} else if (event.keyCode === 40){
if ( map[character.y+1][character.x] !== 1){
map[character.y][character.x] = 3;
character.y = character.y + 1;
map[character.y][character.x] = 5;
drawWorld();
}
}
console.log(map)
}

Ignore user input after certain point

Is there a way I can kill / break out of user input on my tic tac toe board after a winner has been declared? I tried using break in the isFull() function after the alert was sent of who won but it still would accept user input in the table afterwords.
Here is a link to show you it running:
https://jsfiddle.net/n1kn1vLh/2/
function TicTacToe() {
this.board = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
];
this.showhtml = toHTML;
this.player2 = "O";
this.player1 = "X";
this.turn = "";
}
function toHTML() {
var player = '';
var displayplayer = document.getElementById("displayMessage");
var htmlStr = '';
var gametable = document.getElementById("tictable");
var cell = '';
for (var i = 0; i < this.board.length; i++) {
htmlStr += '<tr>';
for (var j = 0; j < this.board[i].length; j++) {
if (this.board[i][j] == 0) {
this.board[i][j] = cell;
htmlStr += ("<td data-i=\"" + i + "\" data-j=\"" + j + "\">" + this.board[i][j] + "</td>");
}
gametable.addEventListener("click", clickHandler, false);
}
htmlStr += '</tr>';
}
gametable.innerHTML = htmlStr;
if (this.turn == this.player1 || this.turn == "") {
player += ("<p>It is " + this.player1 + "'s turn.</p>");
displayplayer.innerHTML = player;
return this.turn = "X";
} else {
player += ("<p>It is " + this.player2 + "'s turn.</p>");
displayplayer.innerHTML = player;
return this.turn = "O";
}
function clickHandler(event)
{
if (tic.turn == tic.player1) {
if (event.target.innerHTML == ''){
event.target.innerHTML = tic.turn;
tic.board[event.target.dataset.i][event.target.dataset.j] = tic.turn;
tic.turn = tic.player2;
document.getElementById("displayMessage").innerHTML = "<p>It is " + tic.turn + "'s turn.</p>";
isFull();
return tic.turn;
} else {
alert('Invalid Move! Try again.');
}
} else {
if (event.target.innerHTML == '') {
event.target.innerHTML = tic.turn;
tic.board[event.target.dataset.i][event.target.dataset.j] = tic.turn;
tic.turn = tic.player1;
document.getElementById("displayMessage").innerHTML = "<p>It is " + tic.turn + "'s turn.</p>";
isFull();
return tic.turn;
} else {
alert('Invalid Move! Try again.');
}
}
}
function isFull() {
for (var i = 0; i < tic.board.length; i++) {
if(tic.board[i][0] == tic.board[i][1] && tic.board[i][0]==tic.board[i][2] && tic.board[i][0]!=0){
alert(tic.board[i][0]+" Wins");
return;
}
}
for (var i = 0; i < tic.board.length; i++) {
if(tic.board[0][i] == tic.board[1][i] && tic.board[0][i]==tic.board[2][i] && tic.board[0][i]!=0){
alert(tic.board[0][i]+" Wins");
return;
}
}
if(tic.board[0][0]==tic.board[1][1] && tic.board[0][0] == tic.board[2][2] && tic.board[0][0]!=0){
alert(tic.board[0][0]+" Wins");
return;
}
if(tic.board[0][2]==tic.board[1][1] && tic.board[0][2] == tic.board[2][0] && tic.board[2][0]!=0){
alert(tic.board[1][1]+" Wins");
return;
}
}
}
tic = new TicTacToe();
tic.showhtml();
You can remove the eventListener when someone wins:
function isFull() {
for (var i = 0; i < tic.board.length; i++) {
if(tic.board[i][0] == tic.board[i][1] && tic.board[i][0]==tic.board[i][2] && tic.board[i][0]!=0){
alert(tic.board[i][0]+" Wins");
document.getElementById("tictable").removeEventListener('click', clickHandler);
return;
}
}
for (var i = 0; i < tic.board.length; i++) {
if(tic.board[0][i] == tic.board[1][i] && tic.board[0][i]==tic.board[2][i] && tic.board[0][i]!=0){
alert(tic.board[0][i]+" Wins");
document.getElementById("tictable").removeEventListener('click', clickHandler);
return;
}
}
if(tic.board[0][0]==tic.board[1][1] && tic.board[0][0] == tic.board[2][2] && tic.board[0][0]!=0){
alert(tic.board[0][0]+" Wins");
document.getElementById("tictable").removeEventListener('click', clickHandler);
return;
}
if(tic.board[0][2]==tic.board[1][1] && tic.board[0][2] == tic.board[2][0] && tic.board[2][0]!=0){
alert(tic.board[1][1]+" Wins");
document.getElementById("tictable").removeEventListener('click', clickHandler);
return;
}
}
add the following in you isFull()
document.getElementById('user input').disabled = true;

Prevent .appendChild from creating inside already filled div?

I am trying to create a tic tac toe game where you can play against Math.floor(Math.random()) playing as O, with user is playing as X. But when I click, it sometimes creates O in an already filled box.
I just want to allow one P tag per div.
WARNING: code extremely messy and over complicated(sorry).
html:
<body onload="createDivs()">
<p id="demo"></p>
</body>
css:
div {
border: solid 2px black;
width: 300px;
height: 300px;
float: left;
border-right: none;
border-top: none;
overflow: hidden;
}
JavaScript:
var alternate = "O";
var count = 0;
function createDivs() {
var t;
var ai;
var trackId = [];
for (i = 0; i < 9; i++) {
var d = document.createElement("DIV");
document.body.appendChild(d);
d.onclick = function() {
if (count > 8) {
return
}
var xP = document.createElement("P");
var oP = document.createElement("P");
var childCount = "childID" + count;
xP.setAttribute("id", childCount);
trackId.push(childCount);
/*
alert(trackId.toString());
*/
count++;
oP.setAttribute("id", "childID" + count);
count++;
if (alternate == 'O') {
t = document.createTextNode("X");
alternate = 'X';
xP.appendChild(t);
this.appendChild(xP);
this.onclick = function() {};
/*
for (aa = 0; aa < 9; aa++) {
var zed = "D"+aa;
var bb = document.getElementById(zed).innerText;
while (bb == 'X' || bb == 'O') {
zed = Math.floor(Math.random() * 9);
}
}
*/
if (count > 9) {} else {
while (zed == 'X' || zed == 'O') {
var r = Math.floor(Math.random() * 9);
var zed = document.getElementById("D" + r).innerHTML;
var zob = "D" + r;
document.getElementById("demo").innerHTML = testConcat;
}
ai = document.createTextNode("O");
alternate = 'O';
oP.appendChild(ai);
d.appendChild(oP);
}
}
}
var ii = document.createAttribute("id");
ii.value = "D" + i;
d.setAttributeNode(ii);
var z = "D" + i;
if (i == 3 || i == 6) {
document.getElementById(z).style.clear = "left";
}
}
}
There were few issues in the code but the main problem was that when you are looking for the next empty slot, you are checking if the innerHTML of the Div is equal to "X" or "O". You can not use this logic since you are appending the p tag inside the div which has "X" or "O" as text.
So when you do document.getElementById("D"+r).innerHTML inside the while loop you will either get empty(this will work for you) or one of
<p>X</p>
<p>O</p>
(this will start causing problem) as this will make the code to append the child again on the same Div.
You should better check for the child elements inside a Div and if there is already a child element(slot is already filled) , code should look for another empty slot.
here is the updated code snippet
function createDivs() {
var t;
var ai;
var trackId =[];
var count = 0;
var alternate = "O";
for (i=0; i<9; i++) {
var d = document.createElement("DIV");
document.body.appendChild(d);
d.onclick = function() {
if (count > 8) {
return
}
var xP = document.createElement("P");
var oP = document.createElement("P");
var zed = "X";
var zod;
var childCount = "childID"+count;
xP.setAttribute("id", childCount);
trackId.push(childCount);
/*
alert(trackId.toString());
*/
count++;
oP.setAttribute("id", "childID"+count);
count++;
if (alternate == 'O') {
t = document.createTextNode("X");
alternate = 'X';
xP.appendChild(t);
this.appendChild(xP);
this.onclick = function() {};
if (count > 9) {
}
else
{
while (zed == 'X' || zed == 'O')
{
var r = Math.floor(Math.random() * 9);
if(document.getElementById("D"+r).childElementCount == 0)
zed = "";
zob = "D"+r;
}
ai = document.createTextNode("O");
alternate = 'O';
oP.appendChild(ai);
document.getElementById(zob).appendChild(oP);
}
}
}
var ii = document.createAttribute("id");
ii.value = "D" + i;
d.setAttributeNode(ii);
var z = "D" + i;
if (i == 3 || i == 6) {
document.getElementById(z).style.clear = "left";
}
}
}
Plunker : http://plnkr.co/edit/FgQ5KbNEvBpnag9mn9qO?p=preview
Hope this will help you.
If you want to add jQuery you could do that with if ($(this).find("p").length == 0)
Here as a jsfiddle

How use a js text injected into console of Firefox to change Background Image of Site - Sample Provided

So I only have this example, but it does exactly what I want to do; but it also does a bunch of other stuff- and for the wrong site. (This js provided is just the example that I know it's possible I just don't know how to get "only that" piece and ONLY that).
I want a small js text that I can inject into the console pop up CTRL-SHIFT-K of Firefox, that will change the background image of the website (same site used in this script).
But that's all I want. I just want to make my own background when on the site.
The script here does change the background (its a command in the begining (background image JPG).
How would I isolate that into a short snip of js... that I could use as a standalone to only do just that and nothing more?
I tried to modify this, and did reading up on scripting JS, but I dont code, so I only have gotten errors.
Any help would be so much appreciated! :)
The Background lines of code begin at LINE 45-46. - THIS IS ALL I WANT - ONLY A SMALL SCRIPT TO DO JUST THE BACKGROUND, EVERYTHING ELSE GONE
THANK YOU!
var flameBot, betspeed, aftermanualtrigger, swaplosscount, swapcount, loop, loopenabled, betData, condition, profit, target, losscount, totalloss, totalwin, currentbet, basebet, mainmult, initmult, result, afterwin, UI = '',
UI2 = '';
profit = 0;
var streakcounter = [];
var balance;
var winstreak = 0;
betspeed = 613;
loopcount = 0;
betstarted = false;
loopenabled = false;
aftermanualtrigger = false;
afterwin = false;
var consecutive = 0,
singlewin = 0;
swaplosscount = 0;
var conseclossenabled = false;
var swapnextwin = false;
swapcount = 0;
var firstInit = true;
if (firstInit == true) {
balance = Math.floor($('div.hero span.btn__text.select div').text()*1e8);
}
flameBot = {
initialize: {
init1: function () {
var lib = '<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/dark-hive/jquery-ui.css" /><script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>';
$(lib).appendTo('head');
setTimeout(function () {
flameBot.initialize.init2();
}, 1000);
},
init2: function () {
losscount = 0;
totalloss = 0;
totalwin = 0;
$('.hero__main').empty().css('width', '550px') & $('.hero__main').css("padding", "0") & $(UI).appendTo('.hero__main') &
$('#flameBot').tabs() & $('button').button().css('font-size', '13px').css('padding', '5px');
$('#stats th').css("width", "20%").css("font-size", "14px");
$('#hilo, #resetorzero').buttonset();
$('#flameBot li').css('font-size', '15px');
$('#flameBot #resetorzero').css('font-size', '13px');
$('#flameBot div[role=tabpanel] td').css('padding', 1);
$('.hero__main').css('margin-top', '-75px');
$('#stats2 th').css('width', '6.25%');
var css = '',
backgroundurl = 'http://cdn.wonderfulengineering.com/wp-content/uploads/2014/01/HD-backgrounds-3.jpg';
css += '<style id="paraDark">';
css += 'header, .tabs, .slideout__content__inside, .chat__you *, .btn, .hero__main, .rollrow-dark, .rollbox--prominent, .chat__input-holder{background-color:#121212 !important;color:#ccc !important;}';
css += 'time{color:#ccc !important;}';
css += 'div.tabs > div > div.live-data-header > div{background-color:#111111;border-top:1px solid #777; border-bottom:1px solid #777;}';
css += '.btn,.btn--secondary.btn--active,.btn--secondary.btn--selector, .btn--submit:last-child{border:1px solid #777 !important;background-color:#242130 !important;color:#ccc!important;}';
css += '.btn:hover,.btn--secondary.btn--active:hover,.btn--secondary.btn--selector:hover{border:1px solid #777 !important;background-color:#322E47 !important;color:#ccc!important;}';
css += '.hero{margin-bottom:0px;background:url("' + backgroundurl + '") no-repeat 50% 50%;}';
css += '.slideout *{color:#ccc;}';
css += '.tabs{padding-top:20px;border-top:1px solid #777 !important;}';
css += 'header{border: 1px solid #777 !important;border-left:none !important;border-right:none !important;}';
css += '.rollrow-thin, .rollrow-dark .chat__input-holder {background-color:#212121;}';
css += '.input{background-color:#323232 !important;color:#ccc;}';
css += '.action-open-slideout{background-color:#121212 !important;}';
css += 'span.admin{color:white !important}';
css += '</style>';
$(css).appendTo('head');
$('#stats2, #stats3').css('margin-left', '10px');
$('#stats3 th').css('width', '25%').css('text-align', 'center');
$('#stats3').css('width', '50%').css('text-align', 'center');
$('<center><button onclick="flameBot.API.bet();" class="btn btn--primary btn--huge btn--limited btn--block text--center" id="spinner2">Roll</button></center>').appendTo('.hero__main');
$('#resetorzero').css('font-size', '11px');
$('#lastbet th').css('text-align', 'center');
$('#lastbet th').css('padding', '3px');
$('#lastbet tr').css('border-top', '1px solid #fff');
$('#lastbet3 > tbody > tr').css('background', '#181818', 'important');
$('#lastbet2 > tbody').css('background', '#181818');
$('.hero__main').css('border', '1px solid #777');
for (i = 0; i < $('#stats2 th').length; i++) {
streakcounter.push(0);
}
for (i = 0; i < $('#stats2 th').length; i++) {
var lol = $('#stats2 th')[i];
lol.textContent = (i + 1).toString() + "(" + streakcounter[i] + ")";
}
$('#resetstats').click(function () {
streakcounter = [];
for (i = 0; i < $('#stats2 th').length; i++) {
streakcounter.push(0);
}
for (i = 0; i < $('#stats2 th').length; i++) {
var lol = $('#stats2 th')[i];
lol.textContent = (i + 1).toString() + "(" + streakcounter[i] + ")";
}
totalwin = 0;
totalloss = 0;
profit = 0;
consecutive = 0,
singlewin = 0;
winstreak = 0;
losscount = 0;
flameBot.API.addRow();
});
$('#start').click(function () {
looptimes = 999999999;
if (loopenabled === false) {
loopenabled = true;
loop = setInterval(function () {
if (loopcount >= looptimes) {
clearInterval(loop);
loopcount = 0;
loopenabled = false;
} else {
if (betstarted === true) {} else {
flameBot.API.bet();
}
}
}, betspeed);
}
});
$('#stop').click(function () {
clearInterval(loop);
loopenabled = false;
loopcount = 0;
});
$('#setparams').click(function () {
flameBot.API.setParams();
})
}
},
tools: {
dec2Sat: function (decimal) {
return (Math.floor(decimal * 1e8));
},
token: function () {
return localStorage.token;
},
satToDec: function (satoshi) {
return ((satoshi / 1e8).toFixed(8));
},
},
API: {
onLoss: function () {
totalloss++;
losscount++;
if (afterwin === true) {
afterwin = false;
flameBot.API.setParams();
}
if (winstreak >= 2) {
consecutive++;
$('#consecutive').text(consecutive);
winstreak = 0;
}
if (winstreak == 1) {
singlewin++;
$('#single').text(singlewin);
winstreak = 0;
}
if ($('#swaplossesenabled').is(':checked') === true) {
swaplosscount++;
if (swaplosscount >= $('#swaplosses').val()) {
swapnextwin = true;
swaplosscount = 0;
}
}
if ($('#afterlossesenabled').is(':checked') === true) {
if (losscount >= $('#afterlosses').val()) {
if ($('#aftermanualenabled').is(':checked') === true) {
if (aftermanualtrigger === true) {} else {
var r = prompt("Enter '1' to reset to base. Enter '2' to bet 0 until win. Enter '3' to stop.");
if (r == 1) {
aftermanualtrigger = false;
currentbet = basebet;
losscount = 0;
} else if (r == 2) {
aftermanualtrigger = true;
currentbet = 0;
} else {
clearInterval(loop);
aftermanualtrigger = false;
loopenabled = false;
}
}
} else {
if ($('input:radio[name=resetorzero]:checked').val() == 'orzero') {
currentbet = 0;
} else if ($('input:radio[name=resetorzero]:checked').val() == 'orstop') {
clearInterval(loop);
loopenabled = false;
} else if ($('input:radio[name=resetorzero]:checked').val() == 'resetor') {
losscount = 0;
currentbet = basebet;
}
}
} else {
if (losscount == $('#startlosses').val()) {
currentbet = currentbet * $('#initialmultiplier').val();
} else if (losscount > $('#startlosses').val()) {
currentbet = currentbet * $('#mainmultiplier').val();
}
}
} else {
if (losscount == $('#startlosses').val()) {
currentbet = currentbet * $('#initialmultiplier').val();
} else if (losscount > $('#startlosses').val()) {
currentbet = currentbet * $('#mainmultiplier').val();
}
}
flameBot.API.addRow();
},
onWin: function () {
if ($('#betdivisorenabled').is(':checked') === true) {
basebet = Math.floor(balance/$('#betdivisor').val());
}
winstreak++;
conseclossenabled = false;
if (swapnextwin === true) {
flameBot.API.swap();
swapnextwin = false;
}
if ($('#afterwinenabled').is(':checked') == true) {
if (afterwin === false) {
afterwin = true;
}
}
if (aftermanualtrigger === true) {
aftermanualtrigger = false
}
totalwin++;
swaplosscount = 0;
var streak = losscount;
if (losscount >= 250) {
losscount = 250;
}
streakcounter[losscount - 1] ++;
losscount = 0;
currentbet = basebet;
flameBot.API.addRow();
},
setParams: function () {
losscount = 0;
aftermanualtrigger = false;
swaplosscount = 0;
swapcount = 0;
initmult = $('#initialmultiplier').val();
mainmult = $('#mainmultiplier').val();
if ($('#betdivisorenabled').is(':checked') === true) {
basebet = Math.floor(balance/$('#betdivisor').val());
currentbet = basebet;
} else {
basebet = flameBot.tools.dec2Sat($('#basebet').val());
currentbet = basebet;
}
if ($('input:radio[name=hilo]:checked').val() == 'hi') {
condition = '>';
target = (99.99 - (99 / $('#chance').val())).toFixed(2);
} else if ($('input:radio[name=hilo]:checked').val() == 'lo') {
condition = '<';
target = (99 / $('#chance').val()).toFixed(2);
} else if ($('input:radio[name=hilo]:checked').val() == 'swap') {
condition = '<';
target = 0 + (99 / $('#chance').val()).toFixed(2);
}
},
addRow: function () {
var bettable = '',
bettab = '#lastbet2';
bettable += '<tr><td>' + flameBot.tools.satToDec(result.bet.amount) + '</td>';
bettable += '<td>' + result.bet.multiplier + 'x' + '</td>'; /* return bet payout */
bettable += '<td>' + (result.bet.target).toFixed(2) + '</td>'; /* return target*/
bettable += '<td>' + result.bet.roll + '</td>'; /* return roll */
bettable += '<td id="proff">' + flameBot.tools.satToDec(result.bet.profit) + '</td></tr>';
var stattable = '',
stattab = '#lastbet3';
stattable += '<tr><td style="color:blue;">' + flameBot.tools.satToDec(result.user.balance) + '</td><td style="color:white;">' + losscount + '</td><td style="color:blue;">' + totalwin + '</td><td style="color:white;">' + totalloss + '</td><td id="profit">' + (profit).toFixed(8) + '</td></tr>';
$(stattab).empty();
$(stattab).prepend(stattable);
stattable = '';
if ($(bettab + ' tbody tr').length >= 30) {
$(bettab + ' tr').last().remove();
$(bettab).prepend(bettable);
bettable = '';
} else if ($(bettab).length < 30) {
$(bettab).prepend(bettable);
bettable = '';
}
for (i = 0; i < $('#stats2 th').length; i++) {
var lol = $('#stats2 th')[i];
lol.textContent = (i + 1).toString() + "(" + streakcounter[i] + ")";
}
$('#stats2 th:nth-child(19)').text('>' + $('#stats2 th:nth-child(19)').text());
$('#lastbet2 *, #lastbet3 *, #lastbet *, #proff').css('text-align', 'center');
$('#lastbet2 *, #lastbet3 *, #lastbet *').css('width', '20%');
$('#lastbet *').css('padding', '5px');
$('#lastbet *').css('border-bottom', '1px solid #ccc');
$('#result-1').css('padding', '5px');
$('#lastbet2 *, #lastbet3 *, #proff').css('padding', '5px');
$('#lastbet > tbody > tr > th:nth-child(2)').css('border-top', '1px solid #ddd');
if (profit >= 0) {
$('#profit').css('color', 'blue');
} else {
$('#profit').css('color', 'white');
}
if (result.bet.win === true) {
$('#proff:first').css('color', 'blue');
} else {
$('#proff:first').css('color', 'white');
}
betstarted = false;
},
bet: function () {
betstarted = true;
if ($('#maxbetenabled').is(':checked') === true) {
if ((currentbet / 1e8) >= $('#maxbet').val()) {
$('#setparams').click();
}
}
if ($('#afterwinenabled').is(':checked') === true) {
if (afterwin === true) {
currentbet = ($('#afterwinamount').val() * 1e8).toFixed(8);
}
}
if ($('#clossenabled').is(':checked') === true) {
if (losscount >= $('#clossafter').val()) {
if (conseclossenabled === false) {
conseclossenabled = true;
currentbet = Math.floor($('#clossbet').val() * 1e8);
}
}
}
var betData = {
amount: currentbet,
condition: condition,
target: target,
};
$.ajax({
url: 'https://api.primedice.com/api/bet?access_token=' + flameBot.tools.token(),
type: 'POST',
data: betData,
datatype: 'jsonp',
success: function (data) {
result = data;
balance = result.user.balance;
profit = parseFloat(profit) + parseFloat(flameBot.tools.satToDec(data.bet.profit));
if ($('input:radio[name=hilo]:checked').val() == 'swap') {
swapcount++;
if (swapcount >= $('#swapevery').val()) {
flameBot.API.swap();
swapcount = 0;
}
}
if (data.bet.win === true) {
$('span.btn__text.select div').text(flameBot.tools.satToDec(result.user.balance)).css('color', 'blue');
flameBot.API.onWin();
} else {
$('span.btn__text.select div').text(flameBot.tools.satToDec(result.user.balance)).css('color', 'white');
flameBot.API.onLoss();
}
},
error: function (errorThrown) {
betstarted = false;
}
});
},
seedChange: function () {
function seedgen() {
var seed = '';
var seedlength = 10;
var charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!##$%^&*()';
for (var i = 0; i <= seedlength; i++)
seed += charset.charAt(Math.floor(Math.random() * charset.length));
return seed;
}
var s = seedgen(),
url = 'https://api.primedice.com/api/seed?access_token=' + localStorage.token,
sData = {
seed: s
};
$.ajax({
url: url,
type: 'POST',
data: sData,
datatype: 'json',
success: function (data, textStatus, jqXHR) {
data2 = data;
$('#currentseed').val(data2.seeds.client);
},
error: function (jqXHR, textStatus, errorThrown) {
return false;
}
});
},
swap: function () {
if (condition == '<') {
condition = '>';
target = (99.99 - (99 / $('#chance').val())).toFixed(2);
} else if (condition == '>') {
condition = '<';
target = (99 / $('#chance').val()).toFixed(2);
}
},
}
}
var UI = '';
UI += '<table style="margin:0; text-align:center; border-bottom: 1px solid #fff;border-top: 1px solid #fff;"id="stats">';
UI += '<thead><tr><th style="text-align:center;padding:3px;">Balance</th><th style="text-align:center;padding:3px;">Loss Streak</th><th style="text-align:center;padding:3px;">Total Wins</th><th style="text-align:center;padding:3px;">Total Losses</th><th style="text-align:center;">Total Profit</th></tr></thead><tbody></tbody><table id="lastbet3"></table></table>';
UI += '<table id="lastbet">';
UI += '<tr><th>Bet</th><th>Payout</th><th>Game</th><th>Roll</th><th>Profit</th></tr></table>';
UI += '<div style="max-height:150px !important;font-size:12px;overflow-y: scroll;overflow-x: hidden;"><table id="lastbet2"></table></div>';
UI += '<div id="flameBot" style="width:550px"><ul><li>';
UI += 'Basic Settings</li>';
UI += '<li>On Loss</li>';
UI += '<li>Loss - Adv.</li>';
UI += '<li>On Win</li>';
//UI += '<li style="margin:8px;font-size:9px;margin-left:15px;text-align:center;"><span>FlameBot - v1.0</span></li>';
UI += '</ul>';
UI += '<div id="basic" style="font-size:17.5px;">';
UI += '<table style="display:table;"><thead><tr><th>Basebet: </th><th>Chance:</th></tr></thead><tbody><tr><td><input id="basebet" placeholder="ex. 0.00001000" type="text"></td><td><input id="chance" placeholder="ex. 10 for 10x, 2 for 2x, etc." type="text"></td></tr></tbody><thead><tr><th>High/Low/Swap:</th><th>Swap Every:</th></tr></thead><tbody><tr><td><div id="hilo"><input type="radio" id="hi" value="hi" name="hilo"><label for="hi">High</label> <input type="radio" id="lo" value="lo" name="hilo" checked="checked"><label for="lo">Low</label> <input type="radio" id="swap" value="swap" name="hilo"><label for="swap">Swap</label> </div></td><td><input id="swapevery" placeholder="# of rolls" type="text"></td></tr></tbody></table></div>';
UI += '<div id="onloss" style="font-size:17.5px;">';
UI += '<table style="display:table;"><thead><tr><th>Start Multipling: </th><th>Main Multiplier:</th></tr></thead><tbody><tr><td><input id="startlosses" style="text-align:center;" placeholder="after # of losses"type="text"></td><td><input id="mainmultiplier" style="text-align:center;" placeholder="2, 4, etc."type="text"></td></tr></tbody><thead><tr><th>Initial Multiplier</th><th>Max Bet: <input type="checkbox" id="maxbetenabled"></th></tr></thead><tbody><tr><td><input id="initialmultiplier" style="text-align:center;" placeholder="2, 4, etc."type="text"></td><td><input id="maxbet" style="text-align:center;" placeholder="ex. 0.001" type="text"></td></tr><tr><th>After: <input type="checkbox" id="clossenabled"></th><th>Change Bet To:</th></tr></thead></tr><tbody><tr><td><input id="clossafter" style="text-align:center;" placeholder="# of consecutive loss"type="text"></td><td><input id="clossbet" style="text-align:center;" placeholder="ex. 0.00100000"type="text"></td></tr></tbody></tbody><thead><tr><th>Divisible Basebet:</th><th>Basebet Divisor:</th></tr></thead><tbody><tr><td><input id="betdivisorenabled" style="text-align:center;" type="checkbox"></td><td><input id="betdivisor" style="text-align:center;" placeholder="ex. 0.00100000"type="text"></td></tr></tbody></tbody></table>';
UI += '</div>';
UI += '<div id="onlosstreak" style="font-size:17.5px;">';
UI += '<table style="display:table;"><thead><tr><th>After: <input type="checkbox" id="afterlossesenabled"></th><th>Either: </th></tr></thead><tbody><tr><td><input id="afterlosses" style="text-align:center;" placeholder="# of losses"type="text"></td><td><div id="resetorzero"><input type="radio" id="resetor" value="resetor" name="resetorzero"><label for="resetor">Reset to Base</label><input type="radio" id="orzero" value="orzero" name="resetorzero" checked="checked"><label for="orzero">Roll 0 to Win</label><input type="radio" id="orstop" value="orstop" name="resetorzero" checked="checked"><label for="orstop">Stop</label></div></td></tr></tbody><thead><tr><th>Manualy Choose?</th><th>Swap After: <input id="swaplossesenabled" type="checkbox"></th></tr></thead><tbody><tr><td><input id="aftermanualenabled" type="checkbox"></td><td><input id="swaplosses" style="text-align:center;" placeholder="# of losses" type="text"></td></tr></tbody></table>';
UI += '</div>';
UI += '<div style="font-size:17.5px;" id="onwin">';
UI += '<table style="display:table;"><thead><tr><th>After Win:</th><th>Bet X Until Loss </th></tr></thead><tbody><tr><td><input type="checkbox" id="afterwinenabled"></td><td><input type="text" placeholder="ex. 0.00002000" id="afterwinamount"></td></tr></tbody></table>';
UI += '</div>';
UI += '<div id="controlstat">';
UI += '<center><div id="toolbar" class="ui-widget-header ui-corner-all"><div id="buttonz"><span id="startstop"><button id="start">Start</button><button id="stop">Stop</button></span><span id="set"><button id="setparams">Set Params</button><button id="resetstats">Reset Stats</button><br><button id="save">Save Settings</button><button id="load">Load Settings</button></div></center><br>';
UI += '<table style="margin:3px;"id="stats2">';
UI += '<span style="font-weight:bold;">Loss Streaks:</span>';
UI += '<thead><tr><th>1</th><th>2</th><th>3</th><th>4</th><th>5</th><th>6</th><th>7</th><th>8</th><th>9</th><th>10</th></tr>';
UI += '<tr><th>11</th><th>12</th><th>13</th><th>14</th><th>15</th><th>16</th><th>17</th><th>18</th><th>19</th><th>20</th></tr>';
UI += '<tr><th>21</th><th>22</th><th>23</th><th>24</th><th>25</th><th>26</th><th>27</th><th>28</th><th>29</th><th>30</th></tr>';
UI += '<tr><th>31</th><th>32</th><th>33</th><th>34</th><th>35</th><th>36</th><th>37</th><th>38</th><th>39</th><th>40</th></tr>';
UI += '<tr><th>41</th><th>42</th><th>43</th><th>44</th><th>45</th><th>46</th><th>47</th><th>48</th><th>49</th><th>50</th></tr>';
UI += '<tr><th>51</th><th>52</th><th>53</th><th>54</th><th>55</th><th>56</th><th>57</th><th>58</th><th>59</th><th>60</th></tr>';
UI += '<tr><th>61</th><th>62</th><th>63</th><th>64</th><th>65</th><th>66</th><th>67</th><th>68</th><th>69</th><th>70</th></tr>';
UI += '<tr><th>71</th><th>72</th><th>73</th><th>74</th><th>75</th><th>76</th><th>77</th><th>78</th><th>79</th><th>80</th></tr>';
UI += '<tr><th>81</th><th>82</th><th>83</th><th>84</th><th>85</th><th>86</th><th>87</th><th>88</th><th>89</th><th>90</th></tr>';
UI += '<tr><th>91</th><th>92</th><th>93</th><th>94</th><th>95</th><th>96</th><th>97</th><th>98</th><th>99</th><th>100</th></tr></thead></table>';
UI += '<table style="margin:3px;"id="stats3">';
UI += '<span style="font-weight:bold;">Wins:</span>';
UI += '<thead><tr><th>Single:</th><th>Consecutive:</th></tr>';
UI += '<tr><th id="single">0</th><th id="consecutive">0</th></tr></thead></table>';
UI += '</div>';
UI += '</div>';
flameBot.initialize.init1();
The Background lines of code begin at LINE 45-46.
THANK YOU!
small js text that I can inject into the console pop up CTRL-SHIFT-K of Firefox, that will change the background image of the website (same site used in this script)
The code that you have posted (after view page source) is a static HTML page. You can change the background image of that html by adding following to line 36.
$('body').css('background-image','url(path/to/yourimage.png)');
Example :
flameBot = {
initialize: {
init1: function () {
var lib = '<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/dark-hive/jquery-ui.css" /><script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>';
$('body').css('background-image','url(path/to/yourimage.png)');
$(lib).appendTo('head');
setTimeout(function () {
flameBot.initialize.init2();
}, 1000);
},
However , this will only work as a static HTML page ( Much like opening a text file on your browser , except you will be doing it with a new image).

How to hide rows in a form until they are clicked using javascript.?

I need to hide rows until they are clicked. I didn't initially write the code and I was having hard time fixing the issues. It's for an advanced order form for a private jet company. The form is supposed to have only 2 visible legs and then you'll be able to click on add a leg button to add a leg, instead it shows 15 legs.
jQuery(document).ready(function () {
jQuery('.trip-type').change(function () {
if (jQuery(this).val() == "multi-leg") {
jQuery("#addleg").css("display", "block").hide().end();
for (var i = 2; i <= 3; i++) {
jQuery('.to_leg_' + i).val('');
jQuery('.to_leg_' + i).attr('data-code', "");
jQuery('.to_leg_' + i).attr('data-name', "");
jQuery('.to_leg_' + i).attr('data-real-city', "");
jQuery('.to_leg_' + i).attr('data-country', "");
jQuery('.to_leg_' + i).attr('data-latitude', "");
jQuery('.to_leg_' + i).attr('data-longitude', "");
}
for (var n = 3; i <= 5; i++) {
jQuery('.from_leg_' + i).val('');
jQuery('.from_leg_' + i).attr('data-code', "");
jQuery('.from_leg_' + i).attr('data-name', "");
jQuery('.from_leg_' + i).attr('data-real-city', "");
jQuery('.from_leg_' + i).attr('data-country', "");
jQuery('.from_leg_' + i).attr('data-latitude', "");
jQuery('.from_leg_' + i).attr('data-longitude', "");
}
var allElements = jQuery('#multileg-block').find("div.row");
for (var i = 0; n < allElements.length; i++) {
if (jQuery(allElements[i]).hasClass("non-one-way") === true) {
jQuery(allElements[i]).removeClass('non-one-way');
jQuery(allElements[i]).removeClass(i);
jQuery(allElements[i]).css("display", "none");
jQuery(allElements[i]).attr('attribute', "");
}
}
var trelements = jQuery('#multi-table').find("tbody tr.multileg-table");
for (var i = 1; i < trelements.length; i++) {
if (jQuery(trelements[i]).hasClass('non-one-way') === true) {
jQuery(trelements[i]).removeClass("non-one-way");
jQuery(trelements[i]).css("display", "none");
jQuery(trelements[i]).attr('attribute', "");
}
}
$('.info-distances tbody tr.multileg-info:eq(0)').addClass('non-one-way');
} else {
jQuery("#addleg").css("display", "none");
jQuery('.info-distances tbody tr:eq(1)').removeClass('non-one-way');
var mutrelements = jQuery('.info-distances').find("tbody tr.multileg-info");
for (var i = 1; i < mutrelements.length; i++) {
if (jQuery(mutrelements[i]).hasClass('non-one-way') === true) {
jQuery(mutrelements[i]).removeClass("non-one-way");
}
}
}
});
jQuery('#addleg').on("click", function () {
var allElements = jQuery('#multileg-block').find("div.row");
for (var i = 0; i < allElements.length; i++) {
if (jQuery(allElements[i]).hasClass("non-one-way") == false) {
jQuery(allElements[i]).addClass('non-one-way');
jQuery(allElements[i]).addClass(i);
jQuery(allElements[i]).css("display", "block");
jQuery(allElements[i]).attr('attribute', i);
break;
}
}
var trelements = jQuery('#multi-table').find("tbody tr.multileg-table");
for (var i = 0; i < trelements.length; i++) {
if (jQuery(trelements[i]).hasClass('non-one-way') === false) {
jQuery(trelements[i]).addClass("non-one-way");
jQuery(trelements[i]).css("display", "table-row");
jQuery(trelements[i]).attr('attribute', i);
break;
}
}
var mutrelements = jQuery('.info-distances').find("tbody tr.multileg-info");
for (var i = 1; i < mutrelements.length; i++) {
if (jQuery(mutrelements[i]).hasClass('non-one-way') === false) {
jQuery(mutrelements[i]).addClass("non-one-way");
break;
}
}
});
jQuery('.Leg_remove').on("click", function () {
jQuery(this).parent().parent().css('display', 'none');
jQuery(this).parent().parent().removeClass('non-one-way');
index = parseInt(jQuery(this).parent().parent().attr('attribute'));
jQuery('.non-one-way[attribute=' + index + ']').removeClass('non-one-way').css('display', 'none');
index += 2;
jQuery('.info-distances tbody tr:eq(' + index + ')').removeClass('non-one-way');
});
}); < /script>

Categories

Resources