js .click() not working in if statements - javascript

The problem I am having is inside my if statements, the .clicks() do not work. I need i button to be clicked and rerun the script but it isnt working. The SetTimeout(start,5000) helps it repeate but makes the script run several times at once.
document.getElementById('sound-toggle').onclick = function() {
var startingBet = 5;
startingBet = parseFloat(startingBet);
document.getElementById('bet-bt').onclick = function () {
function start() {
//show if it is getting chip amount
//var rr = document.getElementById('bet-rb-2').innerHTML; //neerdsa classs s3elec5to9r
//var rr = document.getElementById('bet-rb-2').innerHTML;
//
setTimeout(start,5000);
//select the result of the spin
var result = document.getElementById('result-text').innerHTML;
alert(result.length);
if (result.length == 5) { //lost
alert('lost');
//document.getElementById("bet-bt").click();
break;
} else if ( result.length == 4) { //won
alert('won');
//document.getElementById("bet-bt").click();
break;
} else {
alert('something is wrong' );
///document.getElementById("bet-bt").click();
break;
}
}
start();
};
};

may be try something like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#sound-toggle').click(function(){
var startingBet = 5;
startingBet = parseFloat(startingBet);
});
$('#bet-bt').click(function(){
setTimeout(start,50);
});
});
function start() {
//show if it is getting chip amount
//var rr = document.getElementById('bet-rb-2').innerHTML; //neerdsa classs s3elec5to9r
//var rr = document.getElementById('bet-rb-2').innerHTML;
//
//select the result of the spin
var result = document.getElementById('result-text').innerHTML;
alert(result.length);
if (result.length == 5) { //lost
alert('lost');
} else if ( result.length == 4) { //won
alert('won');
//document.getElementById("bet-bt").click();
} else {
alert('something is wrong' );
///document.getElementById("bet-bt").click();
}
}
</script>

Related

Have to call alert for rest JS to run on Iphone (safari)

I'm having trouble with JS code not executing on iPhone if I don't call alert before if statement. This is my code:
submitHandler = (e) => {
e.preventDefault();
var dataFromForm = $("#send").serialize();
alert(); // Without this the code below wont execute on iphne
if (window.localStorage) {
if (localStorage.getItem("timeout")) {
const timePrev = localStorage.getItem("timeout");
const timeNow = Math.round(new Date().getTime() / 1000);
if (timeNow - timePrev >= 300) {
var available = true;
} else {
var available = false;
document.getElementById("message").innerHTML =
'<span class="fail"> Spam protection</span>';
}
} else {
var available = true;
}
} else {
var available = true;
}
if (available) {
$.post("mail.php", dataFromForm, function (data) {
document.getElementById("message").innerHTML = "";
console.log(data);
data = JSON.parse(data);
console.log(data);
if (data.statusBool === true) {
document.getElementById("message").innerHTML =
'<span class="success">' + data.status + "</span>";
document.getElementById("name").value = "";
document.getElementById("email").value = "";
document.getElementById("msg").value = "";
var timenow = Math.round(new Date().getTime() / 1000);
localStorage.setItem("timeout", timenow);
} else {
document.getElementById("message").innerHTML =
'<span class="fail">' + data.status + "</span>";
}
});
}
setTimeout(function () {
document.getElementById("message").innerHTML = "";
}, 3000);
};
code below alert doesn't execute if I don't put alert before that statement.
Does anyone know how to solve this, or have an idea of what could I use instead of alert, so it's not visible for the user?
Answer by #Chris G
jsfiddle.net/rqht1kzo
localStorage.setItem('timeout', new Date().getTime() / 1000 - 400);
var available = false;
const timePrev = window.localStorage && window.localStorage.getItem('timeout');
if (timePrev) {
const timeNow = Math.round(new Date().getTime() / 1000);
if (timeNow - timePrev >= 300) available = true;
}
if (available) {
console.log("it's available")
} else {
document.getElementById('message').innerHTML = '<span class="fail"> fail message</span>';
}

My tic tac toe game (jquery) is not working properly. Lost Part is not working properly

The 'Win' and 'Draw' parts are showing up on time, but the 'Lost' part doesn't show the message 'you lost'until I click on an empty cell once again. Please check out my code and help me find any errors.
Below is my code:
Marked is a class that changes the opacity of the clicked cell.
1,2,3...are the id's of respective cells in the table(html).
I tried delay() too instead of setTimeout(), but it didn't work as well.
$(document).ready(function() {
var timer;
var x = 0;
$("td").click(function() {
if($(this).text()=='') {
$(this).text("0").addClass("marked");
x = 1;
}
}).click(function() {
if(x==1) {
timer = setTimeout(function() {
var choose = $("td").not(".marked");
var random = choose[Math.floor(Math.random()*choose.length)];
$(random).text("X").addClass("marked");
},1000);
x=0;
showResult();
}
});
function showResult() {
var one = $("#1").text();
var two = $("#2").text();
var three = $("#3").text();
var four = $("#4").text();
var five = $("#5").text();
var six = $("#6").text();
var seven = $("#7").text();
var eight = $("#8").text();
var nine = $("#9").text();
if(one==two && two==three)
result(one)
else if (four==five && five==six)
result(four)
else if(seven==eight && eight==nine)
result(seven)
else if (one==four && four==seven)
result(one)
else if (two==five && five==eight)
result(two)
else if (three==six && six==nine)
result(three)
else if (one==five && five==nine)
result(one)
else if(three==five && five==seven)
result(three);
else {
var z = $("td").not(".marked");
if(z.length == 0) {
$("p").text("Draw!");
$("td").removeClass("marked");
$("td").text("");
$("#demo1").append('<img src="https://media.tenor.com/images/54c63f726505bfdb455eb4c29e626ad8/tenor.gif">');
clearTimeout(timer);
}
}
}
function result(y) {
var result = y;
if(result=="X"){
clearTimeout(timer);
$("p").text("You Lost!");
$("td").removeClass("marked");
$("td").text("");
$("#demo1").append('<img src="https://media.tenor.com/images/08902a85a6107684f8614846f4a54218/tenor.gif">');
}
if(result=="0") {
$("td").text("");
$("p").text("You Won!");
$("#demo1").append('<img src="https://i.gifer.com/4OuC.gif">');
$("td").removeClass("marked");
clearTimeout(timer);
}
}
});
You are calling showResult immeadiately when the user clicked, so it cant't recognize the X put into the table one second later.
Just do:
$("td").click(function() {
[...]
}).click(function() {
if (x == 1) {
timer = setTimeout(function() {
var choose = $("td").not(".marked");
var random = choose[Math.floor(Math.random() * choose.length)];
$(random).text("X").addClass("marked");
/******** ADD ANOTHER CHECK HERE ********/
showResult();
}, 1000);
x = 0;
showResult();
}
});
It might also be a good idea to add a return to showResult that returns false when a result was achieved. This way you could do something like
x = 0;
if (showResult()) {
timer = setTimeout(function() {
[...]
}
}
And the user can't get a loose message right after a win message.
Also: Why do you need the 2 click listeners? You can just use the if statement in the top one and then you don't need the (x == 1)

Progress bar not resetting

I'm creating a countdown of 10 seconds, and at the end, some functions triggers.
These functions that recall the countdown function to start again. However, when it's called again, the bar is still full, resulting in a loop.
Here's the countdown function.
function LoadTime() {
firebase.auth().onAuthStateChanged(User => {
if(User) {
var RemainTime = 10;
var DownTime = setInterval(function(){
document.getElementById("progressBar").value = 10 - --RemainTime;
if(RemainTime <= 0)
clearInterval(DownTime);
if (RemainTime == 0){
storewager();
if (Roulette.bet == 1) {
RouOutcome();
}
else {
LoadTime();
}
}
},1000);
} else {
alert("please login");
}
});
}
I want this functions to reset the progress bar each time it's triggered. Been stuck on this for a while, so any help is much appreciated.
EDIT:
Here's the tree of the functions.
Page load --> LoadTime --> (end of countdown) --> (Outcome process) --> RouOutcome() --> LoadTime().
Seems to be when LoadTime is triggered when it's already finished once, it seems to run the process multiple times. It may be to do with the alert boxes causing issues for the countdown.
Been stuck on this for hours, so any help is much appreciated.
EDIT 2:
Here's are the relevant functions in the correct order. This is assuming the users picks a bet option, and enters a bet. I'm trying to create roulette. Is it possible that the issue could be with the alerts?
function LoadTime() {
Roulette.load = 1;
CoinFlip.load = 0;
document.getElementById().style.visibility = "hidden";
firebase.auth().onAuthStateChanged(User => {
if(User) {
console.log("user is logged in");
Roulette.choice = 0;
var RemainTime = 15;
var DownTime = setInterval(function(){
document.getElementById("progressBar").value = 15 - --RemainTime;
if(RemainTime <= 0)
clearInterval(DownTime);
if (RemainTime == 0){
storewager();
if (Roulette.bet == 1) {
RouOutcome();
}
else {
LoadTime();
}
}
},1000);
} else {
alert("please login");
}
});
}
function storewager(){
var UserID = firebase.auth().currentUser.uid;
firebase.database().ref("Users").child(UserID).child("coinbet").set(0);
var coinwager = document.getElementById("coininput").value;
if (coinwager > 0) {
Roulette.bet = 1;
var balref = firebase.database().ref("Users").child(UserID).child("coinbet");
firebase.database().ref("Users").child(UserID).child("coinbet").set(coinwager);
var coinref = firebase.database().ref();
coinref.child("coinbet").set(coinwager);
BalVer();
}
else {
alert("No bet was placed");
Roulette.bet = 0;
LoadTime();
}
}
function BalVer(){
var UserID = firebase.auth().currentUser.uid;
var dbRoot = firebase.database().ref("Users").child(UserID);
dbRoot.once("value", snap => {
var cData = snap.val();
var cBet = cData.coinbet;
var uBal = cData.userbalance;
var BalUp = uBal-cBet;
if (BalUp < 0) {
alert("You do not have enough balance")
var BetWipe = firebase.database().ref("Users").child(UserID).child("coinbet").set(0);
}
else {
changeuserbal();
}
});
}
function changeuserbal(coinwager){
var UserID = firebase.auth().currentUser.uid;
var dbRoot = firebase.database().ref("Users").child(UserID);
dbRoot.once("value", snap => {
var cData = snap.val();
var cBet = cData.coinbet;
var uBal = cData.userbalance;
var BalUp = uBal-cBet;
firebase.database().ref("Users").child(UserID).child("userbalance").set(BalUp);
if (CoinFlip.load == 1) {
CoinOutcome();
}
else {
RouOutcome();
}
});
}
function RouOutcome(UserID) {
var OutCome = 0 + (Math.random() * 10000);
var UserID = firebase.auth().currentUser.uid;
if (OutCome <= 10000) {
if (Roulette.choice == 1) {
alert("You won");
var dbRoot = firebase.database().ref("Users").child(UserID);
dbRoot.once("value", snap => {
var cData = snap.val();
var cBet = cData.coinbet;
var uBal = cData.userbalance;
var WinBal = cBet * 2 + uBal
var NewBal = firebase.database().ref("Users").child(UserID).child("userbalance").set(WinBal);
//UpdateBal();
Roulette.comp = 1;
LoadTime();
});
}
else {
alert("you lost/didn't place bet");
Roulette.comp = 1;
LoadTime();
}
}
else if ((OutCome >= 4738) && (OutCome <=9474)) {
var UserID = firebase.auth().currentUser.uid;
if (Roulette.choice == 2) {
alert("You won");
var dbRoot = firebase.database().ref("Users").child(UserID);
dbRoot.once("value", snap => {
var cData = snap.val();
var cBet = cData.coinbet;
var uBal = cData.userbalance;
var WinBal = cBet*2+uBal
var NewBal = firebase.database().ref("Users").child(UserID).child("userbalance").set(WinBal);
//UpdateBal();
LoadTime();
});
}
else {
alert("you lost/didn't place bet");
LoadTime();
}
}
else {
var UserID = firebase.auth().currentUser.uid;
if (Roulette.choice == 3) {
alert("You won");
var dbRoot = firebase.database().ref("Users").child(UserID);
dbRoot.once("value", snap => {
var cData = snap.val();
var cBet = cData.coinbet;
var uBal = cData.userbalance;
var WinBal = cBet*14+uBal
var NewBal = firebase.database().ref("Users").child(UserID).child("userbalance").set(WinBal);
//UpdateBal();
LoadTime();
});
}
else {
alert("you lost/didn't place bet");
LoadTime();
}
}
}
Thanks very much for your help, if you need any more info please say.
Here is an example I created for you to follow. You don't show you attempt at resetting the bar so this is the best I can do at explaining for now.
var pBar = document.getElementById("progressBar");
var pText = document.getElementById("progressText");
startTimer();
function startTimer() {
var downIncrement = 10;
var DownTime = setInterval(function() {
var currentValue = pBar.getAttribute("aria-valuenow");
var newValue = currentValue - downIncrement;
pBar.setAttribute("aria-valuenow", newValue);
pBar.style = "width:" + newValue + "%";
pText.textContent = newValue / 10;
if (newValue <= 0) {
console.log("time is up!");
clearInterval(DownTime);
var Roulette = storewager();
if (Roulette.bet == 1) {
RouOutcome();
} else {
LoadTime();
}
}
},
1000);
}
function storewager() {
console.log("done with store wager");
return {
bet: 1
};
}
function RouOutcome() {
console.log("done with RouOutcome");
// restart progress bar
LoadTime();
}
function LoadTime() {
pBar.setAttribute("aria-valuenow", 100);
pBar.style = "width: 100%";
pText.textContent = "10";
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="progress">
<div id="progressBar" class="progress-bar" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width:100%">
<span id="progressText">10</span>
</div>
</div>

How to replicate a typing effect using jQuery/JavaScript?

How to have the exact typing effect used on this page? https://www.braintreepayments.com/
<span class="writer" data-writer-command="['PayPal?', 'Apple Pay?', 'Venmo?', 'Bitcoin?']">Ve</span>
Here is the JSFiddle with the extracted library from the website : http://jsfiddle.net/8g6dsp0p/1/
You can initialize the script with this following code :
<span class="writer" data-writer-command="['PayPal?', 'Apple Pay?', 'Venmo?', 'Bitcoin?']"></span>
<script>
$(document).ready(function() {
new Writer
});
</script>
var word = "Venmo";
var cur = 1;
var intrvl = setInterval(function () {
$('.writer').html(word.slice(0,cur));
if(cur >= word.length) {
clearInterval(intrvl);
}
else{
cur++;
}
}, 500);
JSBin
The above jsBin has the code you require. it is not neatly formatted but code is correct.
Again to reproduce the code
<span clas="writer"></span>
var words = ["Venmo", "alright", "done", "ok"];
var curWord = 0;
function writeWord(word, deleteWord) {
var cur;
if(deleteWord){
cur = deleteWord.length;
var delIntrvl = setInterval(function () {
if(!cur) {
clearInterval(delIntrvl);
if(curWord < (words.length - 1)) {
writeWord(words[++curWord],"");
}
else {//if you dont need continous looping remove this else statement
curWord = 0;
writeWord(words[curWord],"");
}
}
else{
var reqWrd = deleteWord.slice(0,cur);
console.log(reqWrd);
$('.writer').html(reqWrd);
cur--;
}
}, 200);
}
else {
cur=1;
var intrvl = setInterval(function () {
if(cur >= word.length) {
clearInterval(intrvl);
writeWord("",word);
}
else{
var reqWrd = word.slice(0,cur);
console.log(reqWrd);
$('.writer').html(reqWrd);
cur++;
}
}, 200);
}
}
writeWord(words[curWord], "");
Updating the code and also providing jsBin for continous looping
ContinousLoopJsBin

can anybody help me how to deal this 2 javascript conflict

The First Script that allows me to create a moving clouds and loop after if reaches the end
// dvdp - volll - iphone alert
var agent=navigator.userAgent.toLowerCase();
var is_iphone = (agent.indexOf('iphone')!=-1);
// TJP - volll
var stispace=new Array();
var jumpspace=new Array();
var skyspace=new Array; skyspace['dir']=-1; skyspace['place']=0;
var smokespace=0;
var shipspace=0;
var cloudspace=new Array();
var stagespace=2000;
cloudspace[1]=new Array(); cloudspace[1]['w']=219; cloudspace[1]['p']=2000;
cloudspace[2]=new Array(); cloudspace[2]['w']=128; cloudspace[2]['p']=1050;
cloudspace[3]=new Array(); cloudspace[3]['w']=51; cloudspace[3]['p']=1200;
cloudspace[4]=new Array(); cloudspace[4]['w']=112; cloudspace[4]['p']=120;
cloudspace[5]=new Array(); cloudspace[5]['w']=219; cloudspace[5]['p']=130;
cloudspace[6]=new Array(); cloudspace[6]['w']=219; cloudspace[6]['p']=1020;
cloudspace[7]=new Array(); cloudspace[7]['w']=219; cloudspace[7]['p']=1400;
var movespace='';
var scrollspace=0;
function $(id) {
return document.getElementById(id);
}
function smoothto(whereto) {
wheretoreal=whereto;
if(scrollspace == 1) {return false;}
if(whereto == 'section_about_who') { whereto='section_about';}
if(whereto == 'section_about_contact') { whereto='section_about';}
scrollspace=1;
wheretoscroll=0;
wherefromscroll=topget();
for(smt=0;smt<pag_sections_name.length;smt++) {
if(smt>0) {wheretoscroll+=pag_sections_height[smt-1]}
if(pag_sections_name[smt] == whereto) {smt=pag_sections_name.length;}
}
if(wherefromscroll==wheretoscroll) {
scrollspace=0;
window.location='#'+wheretoreal;
return false;
}else{
window.paused=1;
clearInterval(int_TJPfloat);
clearInterval(int_TJProllsky);
}
$('vollltv').style.height='0';
tmp=new Array();
steps=20;
for(smt=1;smt<=steps;smt++) {
pt=smt/steps;
if(pt == .5) {
multi=1.5
} else {
multi=(Math.sqrt(Math.abs(2*pt-1))*(2*pt-1)/Math.abs(2*pt-1)+1)/2;
}
multi=Math.sqrt(smt/steps);
tmp[smt]='window.scroll(0,'+(wherefromscroll+(wheretoscroll-wherefromscroll)*multi)+');';
}
tmp[steps]+="window.location='#"+wheretoreal+"';$('vollltv').style.height='278px'; scrollspace=0;";
tmp[steps]+=" window.int_TJProllsky=undefined; window.int_TJProllsky=setInterval('TJProllsky();',200);";
tmp[steps]+="window.int_TJPfloat=undefined; window.int_TJPfloat=setInterval('TJPfloat();',50);";
tmp[steps]+="window.paused=0; ";
//alert(tmp.join("\n"));
ttt=Math.random();
stispace[ttt]=tmp;
setTI(ttt,10);
return false;
}
function volllresize() {
d=document.body.clientWidth;
if(d && d>1000) {
stagespace=d;
}
if($('inter4')) {
if (self.innerHeight) {
ch = self.innerHeight;
}
else if (document.documentElement && document.documentElement.clientHeight) {
ch = document.documentElement.clientHeight;
}
else if (document.body) {
ch = document.body.clientHeight;
}
if(ch>600) {
$('inter4').style.height=(ch-534)+'px';
}
}
}
function volllinit(section) {
if(section == 'inter0' && !is_iphone) {
volllresize();
window.onresize=volllresize;
for(i=1;i<cloudspace.length;i++) {
cloudspace[i]['p']*=d/1000;
}
//if(tmp.split('#')[1] == '' || tmp.split('#')[1] == 'section_main') {
// setTimeout('scroll(0,200);',100);
//}
}
else if(section == 'about') {
window.int_TJPfloat=setInterval("TJPfloat();",50);
tmp=location.href+'#';
}
}
window.paused=0;
function TJPmovecloud(cid,pos) {
if(pos > stagespace && window.paused>0 ) {
return;
}
if(pos+cloudspace[cid]['w']>stagespace) {
$('s_cloud'+cid).style.width=stagespace-pos+'px';
} else {
$('s_cloud'+cid).style.width=cloudspace[cid]['w']+'px';
}
$('s_cloud'+cid).style.left=pos+'px';
}
function TJPfloat() {
sy=Math.floor(Math.sin(smokespace)*20+20);
sy2=Math.floor(Math.sin(smokespace)*10+10);
sx=Math.floor(Math.cos(smokespace)*3+3);
//if(smokespace==0) {alert('about.css-be belerakni:'+sy+'px 0 0 '+sx+'px');}
$('g_wave1').style.margin=sy+'px 0 0 '+sy+'px';
$('g_wave2').style.margin=sy2+'px 0 0 '+sy2+'px';
smokespace+=.05; if(smokespace>2*Math.PI) {smokespace-=2*Math.PI;}
if($('inter1')) {
for(i=1;i<cloudspace.length;i++) {
if(cloudspace[i]['p'] >= stagespace) {cloudspace[i]['p']=-cloudspace[i]['w'];}
else if(cloudspace[i]['p'] <= -cloudspace[i]['w']) {cloudspace[i]['p']=stagespace;}
cloudspace[i]['p']-=1+cloudspace[i]['w']/200;
TJPmovecloud(i,cloudspace[i]['p']);
}
}
}
The Second script is the one that creates the bouncing effect like the one on tim van damme
<script type="text/javascript" charset="utf-8">
$('.navigation').each(function () {
var $links = $(this).find('a'),
panelIds = $links.map(function() { return this.hash; }).get().join(","),
$panels = $(panelIds),
$panelwrapper = $panels.filter(':first').parent(),
delay = 500,
heightOffset = 40; // we could add margin-top + margin-bottom + padding-top + padding-bottom of $panelwrapper
$panels.hide();
$links.click(function () {
var link = this,
$link = $(this);
// ignore if already visible
if ($link.is('.selected')) {
return false;
}
$links.removeClass('selected');
$link.addClass('selected');
document.title = 'jQuery look: Tim Van Damme - ' + $link.text();
if ($.support.opacity) {
$panels.stop().animate({opacity: 0 }, delay);
}
$panelwrapper.stop().animate({
height: 0
}, delay, function () {
var height = $panels.hide().filter(link.hash).css('opacity', 1).show().height() + heightOffset;
$panelwrapper.animate({
height: height
}, delay);
});
});
$links.filter(window.location.hash ? '[hash=' + window.location.hash + ']' : ':first').click();
});
</script>
This is the error I received
TypeError: Result of expression '$('.navigation')' [null] is not an object. Can anybody please explain to me why this error occur?
You receive this error because if the following function in the first code:
function $(id) {
return document.getElementById(id);
}
This overlaps with jQuery's $ function which is required by the second piece of code. rewrite the first piece of code to use jQuery's $() function or rename $() in the first piece of code and find/replace.
Do you have html elements with the class name "navigation" in your code?

Categories

Resources