Javascript: Using IF condition with imgTmp - javascript

The script below works. However, I would like to use it along with a conditional IF statement to say "If the state is Online, then changeIt.style.visibility = 'visible'; else/if not then changeIt.style.visibility = 'hidden';
I really tried, but didn't manage to use IF with imgTmp.
function checkimage() {
var imgTmp = new Image();
imgTmp.onload = function() {
printState("Online");
};
imgTmp.onerror = function() {
printState("Offline");
};
imgTmp.src = "http://xxx/test.png?_=" + (+new Date());
}
function printState(state) {
document.getElementById("div1").innerHTML = " + state + ";
}
printState();
setInterval(checkimage, 200);

Just edit your printState or, create other function to change the something you want visibility...
function printState(state) {
document.getElementById("div1").innerHTML = " + state + ";
if (state === 'Online') {
changeIt.style.visibility = 'visible';
} else {
changeIt.style.visibility = 'hidden';
}
}

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>';
}

Why doesn't my IF Statement work in JavaScript?

Can someone explain why my if statement doesn't work in the displayStorageSizeToConvert() function? Please and thank you!
var userInput = document.getElementById("userInput");
var kbButton = document.getElementById("k");
var mbButton = document.getElementById("mbButton");
var KilobyteDisplay = document.getElementById('KilobyteDisplay');
var megabyteDisplay = document.getElementById('megabyteDisplay');
var submitButton = document.getElementById('submit');
function displayStorageSizeToConvert() {
if (kbButton.clicked === true) {
return convertFrom.innerHTML = "KB";
}
else {
return convertFrom.innerHTML = "MB";
}
}
function convertStorageSizeFrom() {
if(convertFrom.value === "KB") {
KilobyteDisplay.innerHTML = userInput.value + " KB";
megabyteDisplay.innerHTML = userInput.value / 1000 + " MB";
}
}
It doesn't look like you're invoking your function anywhere.
Also, you should attach this function to a click handler:
function displayInKB() {
convertFrom.innerHTML = "KB";
}
function displayInMb() {
convertFrom.innerHTML = "MB";
}
kbButton.addEventListener('click', displayInKb);
mbButton.addEventListener('click', displayInMb)
You are not currently ever calling/triggering displayStorageSizeToConvert().
I think you are wanting to create a listener. You can add it like this:
kbButton.addEventListener('click', () => convertForm.innerHTML = "KB")

How to break from Jquery click callback function

I am making my own version of simon Game, but the callback function inside click is not existing after user press wrong input. As a result function handler.patternRepeatPlayer() is getting called recursively for each element of array pattern.I want a solution to break from the else after callinghandler.patternRepeatPlayer just once. The program is working fine in strict mode, but only in non-strict mode inside else , I am not able to break from else.
-- can access the project on Git.
https://github.com/santosh1357/simonGame.git
The flow is like from html -> Function simonnGame.PatternGen from PatternGen -> handler.PatternRepeatPlayer -> PatternRepPlayer -> PatternMatcher -> userInput(here if wrong user input in non-strict mode) -> patternRepeatPlayer
This case is failing as in this case else is not existing after calling the function only once.
//Problematic Function.
userInput: function(){
var userPattern = new Array();var id;
$('img').click(function(){
id = parseInt(this.id,10); userPattern.push(id);handler.effect(id);
if(userPattern.indexOf(id) !== simonGame.PATTERN.indexOf(id)){
if($('.chkStrict:checked').val() === "on"){
var audio = new Audio('sounds/wrong.mp3');
audio.play();
setTimeout(function(){window.location.reload(true)},1000);
} else {
var audio = new Audio('sounds/wrong.mp3');
audio.play();
userPattern.length = 0;
handler.repeatFlag = true;
handler.patternRepeatPlayer(); ****//this is getting called recursivelly rather than quiting after calling once****
return ;
}
}
//End Problematic Functiom
I think there is some misunderstanding on how click callback functions work.
//Fullcode
var simonGame = {
COUNT: 0,
PATTERN: [],
SOUND:[{file:'sounds/sa.mp3'},{file:'sounds/re.mp3'},{file:'sounds/ga.mp3'},{file:'sounds/ma.mp3'},{file:'sounds/pa.mp3'},{file:'sounds/dha.mp3'},{file:'sounds/nee.mp3'}],
patternGen: function(){
var randomId;
randomId = Math.floor(Math.random() * 7);
simonGame.PATTERN.push(randomId);
if(simonGame.COUNT > 20){
alert("You have won the game!!");
window.location.reload(true);
}
simonGame.COUNT += 1;
//debugger;
//console.log("increase count true calling count display " + simonGame.COUNT);
handler.countDisplay();
//console.log("count gen true calling patternPlayer with PATTERN " + simonGame.PATTERN );
handler.patternRepeatPlayer();
}, //close patternGen
patternMatcher: function(genPattern){
//console.log("inside patternMatch");
var genPattern = simonGame.patternGen;
//setTimeout(function(){
//console.log("PATEERN: " + simonGame.PATTERN + "COUNT " + simonGame.COUNT );
//calling user input
console.log("calling user Input");
handler.userInput();
setTimeout(function(){
if(handler.repeatFlag === false){ //execute count gen only if repeat flag is false inside user INPUT
genPattern();
}
},simonGame.COUNT*2000);
//console.log("pattern check true, calling pattern gen");
//},simonGame.COUNT*5000); //c`enter code here`lose setTimeout
}, //close patternMatcher
} //close simonGame
var handler = {
countRepPlayer: 0,
repeatFlag: false,
patternRepeatPlayer: function(){
var repeater = setInterval(function(){
handler.effect(simonGame.PATTERN[handler.countRepPlayer]);
handler.countRepPlayer += 1;
if(handler.countRepPlayer > simonGame.COUNT){
clearInterval(repeater);
//setTimeout(function(){
simonGame.patternMatcher();
//},1000);
handler.countRepPlayer = 0;
}
},1000);//close sestInterval
}, //close patternRepeatPlayer
effect: function(id){
var img = document.getElementById(id);
if(img !== null && id !== undefined){
$( img ).fadeIn(100).fadeOut(100).fadeIn(100);//fadeOut(200).fadeIn(200);
//debugger;
var audio = new Audio(simonGame.SOUND[id].file);
audio.play();
//console.log("id inside effect " + id)
}
},//close effect
countDisplay: function(){
document.getElementById("count").innerHTML = "Count: " + simonGame.COUNT;
}, //close countIncrease
userInput: function(){
var userPattern = new Array();var id;
$('img').click(function(){
id = parseInt(this.id,10);
userPattern.push(id);
handler.effect(id);
console.log(" user " + userPattern);
console.log(" pattern " + simonGame.PATTERN);
if(userPattern.indexOf(id) !== simonGame.PATTERN.indexOf(id)){
console.log(" WRONG USER INPUT ");
if($('.chkStrict:checked').val() === "on"){
var audio = new Audio('sounds/wrong.mp3');
audio.play();
setTimeout(function(){window.location.reload(true)},1000);
} else {
console.log("inside else " );
var audio = new Audio('sounds/wrong.mp3');
audio.play();
userPattern.length = 0;
handler.repeatFlag = true;
handler.patternRepeatPlayer(); ****//this is getting called recursivelly rather than quiting after calling once**.**
return ;
}
}
//reset the userPattern Array
if(userPattern.length === simonGame.PATTERN.length){
userPattern.length = 0;
}
}); //close click.
}
} //close handler
Yes, It will be called recursively, because you set interval for it.
Here you can modify your code:
patternRepeatPlayer: function(){
var repeater = setInterval(function(){
handler.effect(simonGame.PATTERN[handler.countRepPlayer]);
handler.countRepPlayer += 1;
if(handler.countRepPlayer > simonGame.COUNT){
clearInterval(repeater);
//setTimeout(function(){
simonGame.patternMatcher();
//},1000);
handler.countRepPlayer = 0;
}
},1000);//close sestInterval
}
To: (EDITED)
function myCallbackFunction(repeater){
handler.effect(simonGame.PATTERN[handler.countRepPlayer]);
handler.countRepPlayer += 1;
if(handler.countRepPlayer > simonGame.COUNT){
clearInterval(repeater);
simonGame.patternMatcher();
handler.countRepPlayer = 0;
}
}
patternRepeatPlayer: function(){
var repeater = setInterval(function() {myCallbackFunction(repeater);}, 1000);
}
And where you need to call it once, just call myCallbackFunction(repeater)

scope of "this" in module.exports

I am turning a React.js component into a Common.js module using module.exports and am having an issue accessing "this" in the context of the component element from one of it's methods.
Below is the entire component. I have placed a comment above the line where the problem occurs. I did try a less verbose example at first but I do not think it was sufficient to explain the issue.
var React = require('react');
var GSAP = require('gsap');
var Psychedelicon = React.createClass({
cycleColors: function() {
var touchPlatforms = ['iPhone', 'iPad', 'iPod', 'Android', 'Linux armv7l', 'WinCE'];
isTouch = false;
iDevice = false;
isDroid = false;
plat = navigator.platform;
if(plat === 'iPhone' || plat === 'iPad' || plat === 'iPod') {
isTouch = true;
iDevice = true;
}
else if (plat === 'Linux armv7l' || plat === 'Android') {
isTouch = true;
isDroid = true;
}
else {
for (var i = 0; i < touchPlatforms.length; i++) {
if (plat === touchPlatforms[i]) {
isTouch = true;
break;
}
else {
isTouch = false;
}
}
}
var isIE = false
if (navigator.userAgent.toLowerCase().indexOf('msie') > -1 || navigator.userAgent.toLowerCase().indexOf('trident') > -1) {
isIE = true
}
var isFF = false
if (navigator.userAgent.toLowerCase().indexOf('firefox') != -1) {
isFF = true
}
if(!isTouch) {
var ColorSwirl = function(colorSet,defaultColor,time) {
var storedResult;
var randomColor = function(theArray) {
var result = theArray[Math.floor(Math.random() * (theArray.length))];
if(result === storedResult){
return(defaultColor)
}
else {
storedResult = result;
return(result);
}
}
var theLuckyColors = {top:randomColor(colorSet),bottom:randomColor(colorSet)};
var swirl = function(){
//!!!!On this line the problem occurs onUpdateParams must reference the element accepting the execution event (onMouseEneter)
TweenLite.to(theLuckyColors, time, {colorProps:{top:randomColor(colorSet), bottom:randomColor(colorSet)}, onUpdate:colorize, onUpdateParams:[this],onComplete:swirl});
}
gradients
var colorize = function(el) {
if(isIE) {
TweenLite.set(el, {
backgroundImage:'-ms-radial-gradient(center,circle cover,' + theLuckyColors.top + ' 0%, ' + theLuckyColors.bottom + ' 100%)'
});
}
else if(isFF) {
TweenLite.set(el, {
backgroundImage:'-moz-radial-gradient(center,circle cover,' + theLuckyColors.top + ' 0%, ' + theLuckyColors.bottom + ' 100%)'
});
}
else {
TweenLite.set(el, {
backgroundImage:'radial-gradient(circle,' + theLuckyColors.top + ', ' + theLuckyColors.bottom + ')',
backgroundImage:'-webkit-radial-gradient(circle,' + theLuckyColors.top + ', ' + theLuckyColors.bottom + ')'
});
}
}
swirl();
}
ColorSwirl(['red','green','#4B0082','#9F00FF','yellow','orange'],'blue',.15);
}
},
stopTheCycle: function() {
},
render: function() {
return (
<a className="psychedelicon" href={this.props.href} target={this.props.target} onMouseEnter={this.cycleColors} onMouseLeave={this.stopTheCycle}>
<i className={"fa fa-" + this.props.icon}></i>
</a>
)
}
});
module.exports = Psychedelicon;
So far I have tried to bind "this" to the the element receiving the event:
onMouseEnter={this.cycleColors.bind(this)}
and I got: `'You are binding a component method to the component. React does this for you automatically in a high-performance way, so you can safely remove this call.'
I also tried:
onMouseEnter={this.cycleColors.call(Psychedelicon)}
and
onMouseEnter={this.cycleColors.bind(Psychedelicon)}
which both produced no error but did not work
I know that the function otherwise works because when I change
onUpdateParams:[this]
to
onUpdateParams:['.psychedelicon']
The component produces the desired behavior, except that it effects all of the components at the same time (which I need to avoid hence needing to use "this").
I must be missing something. Any help is appreciated.
So I was able to solve my own problem. Here is the code that did the trick:
var React = require('react');
var GSAP = require('gsap');
var $ = require('jquery')
var Psychedelicon = React.createClass({
componentDidMount: function() {
var that = React.findDOMNode(this.refs.psicon);
$(that).hover(function() {
//detect device type for Psychedelicon
var touchPlatforms = ['iPhone', 'iPad', 'iPod', 'Android', 'Linux armv7l', 'WinCE'];
isTouch = false;
iDevice = false;
isDroid = false;
plat = navigator.platform;
if(plat === 'iPhone' || plat === 'iPad' || plat === 'iPod') {
isTouch = true;
iDevice = true;
}
else if (plat === 'Linux armv7l' || plat === 'Android') {
isTouch = true;
isDroid = true;
}
else {
for (var i = 0; i < touchPlatforms.length; i++) {
if (plat === touchPlatforms[i]) {
isTouch = true;
break;
}
else {
isTouch = false;
}
}
}
//sniff the for ie
var isIE = false
if (navigator.userAgent.toLowerCase().indexOf('msie') > -1 || navigator.userAgent.toLowerCase().indexOf('trident') > -1) {
isIE = true
}
//sniff for firefox
var isFF = false
if (navigator.userAgent.toLowerCase().indexOf('firefox') != -1) {
isFF = true
}
//Begin ColorSwirl on non-touch devices
if(!isTouch) {
//Define the Color Sets
var ColorSwirl = function(colorSet,defaultColor,time) {
//Pick random color. If the color is the same as the previous one pick blue instead.
var storedResult;
var randomColor = function(theArray) {
var result = theArray[Math.floor(Math.random() * (theArray.length))];
if(result === storedResult){
return(defaultColor)
}
else {
storedResult = result;
return(result)
}
}
//Pick our colors for the initial state
var theLuckyColors = {top:randomColor(colorSet),bottom:randomColor(colorSet)};
//Start swirling
$(that).addClass('swirling');
var swirl = function(){
if($(that).hasClass('swirling')) {
TweenLite.to(theLuckyColors, time, {colorProps:{top:randomColor(colorSet), bottom:randomColor(colorSet)}, onUpdate:colorize, onUpdateParams:[that],onComplete:swirl});
}
}
//Detect Browser and Pass Psychedelicon the appropriate radial gradients
var colorize = function(el) {
if(isIE) {
TweenLite.set(el, {
backgroundImage:'-ms-radial-gradient(center,circle cover,' + theLuckyColors.top + ' 0%, ' + theLuckyColors.bottom + ' 100%)'
});
}
else if(isFF) {
TweenLite.set(el, {
backgroundImage:'-moz-radial-gradient(center,circle cover,' + theLuckyColors.top + ' 0%, ' + theLuckyColors.bottom + ' 100%)'
});
}
else {
TweenLite.set(el, {
backgroundImage:'radial-gradient(circle,' + theLuckyColors.top + ', ' + theLuckyColors.bottom + ')',
backgroundImage:'-webkit-radial-gradient(circle,' + theLuckyColors.top + ', ' + theLuckyColors.bottom + ')'
});
}
}
swirl();
}
ColorSwirl(['red','green','#4B0082','#9F00FF','yellow','orange'],'blue',.15);
}
},function() {
var theLuckyColors = {top:'#FFFFFF',bottom:'#FFFFFF'};
var stopNow = function(time){
$(that).removeClass('swirling');
TweenLite.to(theLuckyColors, time, {colorProps:{top:'#FFFFFF', bottom:'#FFFFFF'}, onUpdate:whiteWash, onUpdateParams:[that]});
}
var whiteWash = function(el) {
TweenLite.set(el, {
backgroundImage:'-ms-radial-gradient(center,circle cover,#FFFFFF 0%, #FFFFFF 100%)',
backgroundImage:'-moz-radial-gradient(center,circle cover,#FFFFFF 0%, #FFFFFF 100%)',
backgroundImage:'radial-gradient(circle,#FFFFFF,#FFFFFF)',
backgroundImage:'-webkit-radial-gradient(circle,#FFFFFF,#FFFFFF)'
});
}
stopNow(.15);
});
},
render: function() {
return (
<a className="psychedelicon" ref="psicon" href={this.props.href} target={this.props.target} onMouseEnter={this.cycleColors} onMouseLeave={this.stopTheCycle}>
<i className={"fa fa-" + this.props.icon}></i>
</a>
)
}
})
module.exports = Psychedelicon;
Here is how I got from the problem to the solution:
When I was unable to produce a result by using "call" as was suggested by #Alexander O'Mara, i required jQuery to speed up testing and added the variable
var that = $(this)
to the component's outermost scope, so that I could access the component itself from the scope of the inner functions like so:
//Note that onUpdateParams now references "that" which is equal to "this" in the scope of the actual component.
TweenLite.to(theLuckyColors, time, {colorProps:{top:randomColor(colorSet), bottom:randomColor(colorSet)}, onUpdate:colorize, onUpdateParams:[that],onComplete:swirl});
this failed again so I logged the value of "this" to the console and saw that I was actually referencing the component's constructor and not the rendered output!
I had a look at the docs again and saw that I could reference the rendered output on every render instance by using a reactjs attribute called "refs". I needed only to give the rendered element a "ref" attribute:
render: function() {
return (
<a className="psychedelicon" ref="psicon" href={this.props.href} target={this.props.target} onMouseEnter={this.cycleColors} onMouseLeave={this.stopTheCycle}>
<i className={"fa fa-" + this.props.icon}></i>
</a>
)
}
and reference the ref in my method, which I decided to run out of "componentDidMount" instead.
var that = React.findDOMNode(this.refs.psicon);
Now, everytime I reference "that" I am referencing the rendered element itself (pretty impresive considering it's re-rendering every .15 seconds on mouseover) and everything is peachy!
UPDATE: This answer does not apply to React, but was in response to a more-general previous version of the question.
This looks like another argument for not using the onclick attribute, but you could use the call or apply method, and pass this as the first argument.
<div id="foo" onClick="Module.addClass.call(this)"></div>
However you might want to consider using addEventListener or jQuery's event delegation instead.

How to execute this function without clicking on a button

So this is a part of greasemonkey userscript. It's an adviser for an online game. At the end of it i've got this:
function do_login() {
// var loc = reg2.exec(document.location.href);
//Auto backing to login page
if (document.location.href.search("logout") != -1) {
window.setTimeout(function () {
document.location.href = "http://www" + gamepage;
}, 100);
}
else {
//login
try {
var logindata = explode(GM_getValue("logindata", "[]"));
}
catch (err) {
var logindata = new Array;
}
unsafeWindow.showDiv("login_div");
$("login_div").style.zIndex = "20";
$("login_div").getElementsByClassName("kh_btn")[0].addEventListener("click", function () {
var currServer = $("l_server").value;
var currUser = $("l_loginname").value.toLowerCase();
GM_setValue(lng + "_" + currServer + "_username", currUser);
}, false);
function submit_login(currUserNr) {
$("l_server").value = logindata[currUserNr][1];
$("l_loginname").value = logindata[currUserNr][2];
$("l_password").value = logindata[currUserNr][3];
$("login_div").getElementsByClassName("kh_btn")[0].click();
}
var newdiv = createElement("div", {style: "position:absolute;top:0px;left:0px;width:412px;padding:10px;background-color:#999;-moz-border-radius:10px;"}, $("login_div"));
for (var v = 0; v < logindata.length; v++) if (logindata[v][1] != "0") {
var newbutton = createElement("button", {type: "button", class: "cursorclickable", id: "autologin" + v, style: "width:200px;height:20px;margin:3px;"}, newdiv, texte["server"] + " " + logindata[v][1] + "." + logindata[v][0] + ": " + logindata[v][2]);
newbutton.addEventListener("click", function () {
submit_login(this.id.replace("autologin", ""));
}, false);
}
newdiv = null;
newbutton = null;
}
}
It's executed when script finds "logout" in the url.
Now, everything works, it's entering main-page, creating a button, the button itself works, but now i would like to execute "onlick" automatically.
You could select the element and then invoke the .click() method:
document.querySelector('#myElement')[0].click();

Categories

Resources