why is this if statement not doing anything? [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Believe me the HTML won't be necessary on this one since the if statement only deals with the cBox variable. What this does is, create or close a div upon clicking a button, i've tested the functions and they work, what's not working however is the way these functions are called, I've logged the outputs but i get neither of them displayed in the console, this means the code is not running through the if statement for some reason.
Also tried with if (cBox == null) and it doesn't work ...
btnPress.onclick = function formConfirm() {
var cBox = document.getElementById('cBox');
console.log(" but cbox is "+cBox);
if(cBox) {
closecBox();
console.log("cbox exists, closing ...");
} else {
opencBox();
console.log("cbox does not exist, creating...");
}
};

I am not sure i understand your question but if your code is like this seems to work fiddle
function closeBox(elem){
elem.parentNode.removeChild(elem);
}
function openBox(el){
var el = document.createElement('div');
el.setAttribute("id", "cBox");
document.body.appendChild(el);
}
var btnPress = document.getElementById('button');
btnPress.onclick = function formConfirm() {
var cBox = document.getElementById('cBox');
if(cBox) {
closeBox(cBox)
console.log("cbox exists, closing ...");
} else {
openBox(cBox);
console.log("cbox does not exist, creating...");
}
};
If i did not understand your question sorry for having done wasting time.

Guys thank you for all the replies, your hints were definitely helpful for solving this problem, i made so many changes that i lost track but this is the working code
var btnPress = document.getElementById('theBtn');
btnPress.onclick = function formConfirm() {
var cBox = document.getElementById('confirmBox');
console.log("cbox is "+cBox);
if(cBox) {
console.log("cbox exists, closing ...");
closecBox();
} else {
opencBox();
console.log("cbox does not exist, creating...");
}
};
function opencBox() {
var cBox = document.createElement('div');
cBox.id = "confirmBox";
document.body.appendChild(cBox);
cBox.style.display="inline";
};
function closecBox() {
var cBox = document.getElementById('confirmBox');
cBox.style.display="none";
document.body.removeChild(cBox);
};
I also used display style to test some other stuff with animations :) once again, thank you so much for all the comments! They really helped me out figuring the solution!

Related

Uncaught ReferenceError: html is not defined [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 days ago.
This post was edited and submitted for review 2 days ago.
Improve this question
I am just using Javascript here, to make a login page that using captcha. But it throw an error when I tried to produce it. It was saying that html is not defined, I already tried to check the code, but still could not figure it out what went wrong here.
here is the Javascript code that I think the problem is:
(function () {
const fonts =['cursive', 'sans-serif', 'serif', 'monospace'];
let captchaValue = "";
function generateCaptcha(){
let value = btoa(Math.random()*100000000);
value = value.substr(0,5+Math.random()*5);
captchaValue= value;
}
function setCaptcha() {
captchaValue.split("").map((char)=> {
const rotate = -20 + Math.trunc(Math.random()*30);
const font = Math.trunc(Math.random()*fonts.length);
return `<span
style="
transform:rotate(${rotate}deg);
font-family: ${fonts[font]};
"
>
${char}
</span>`;
}).join("");
document.querySelector(".login-form .captcha .preview").innerHTML = html;
}
function initCaptcha(){
document.querySelector(".login-form .captcha .captcha-refresh").addEventListener('click', function(){
generateCaptcha();
setCaptcha();
});
generateCaptcha();
setCaptcha();
}
initCaptcha();
})();
Please helping me to solve this problem, since I am a beginner so I really got no idea when I am getting this error.
Your problem seems to be in this line of code:
document.querySelector(".login-form .captcha .preview").innerHTML = html;
you are setting the innerHTML of the ".preview" element to html which you didn't define anywhere in your code.
I'm not sure of what you want to set it to, but this is merely a guess, you can change the setCaptcha to the following:
function setCaptcha() {
let html = captchaValue.split("").map((char)=> {
const rotate = -20 + Math.trunc(Math.random()*30);
const font = Math.trunc(Math.random()*fonts.length);
return `<span
style="
transform:rotate(${rotate}deg);
font-family: ${fonts[font]};
"
>
${char}
</span>`;
}).join("");
document.querySelector(".login-form .captcha .preview").innerHTML = html;
}

If statements JavaScript, maths will not work in my else statement what am I doing wrong? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
This question is pretty straightforward. I am making a number guessing game and I am now adding an attempts function to my game. Every failed attempt should add 1 to my attempts variable:
var numberwang = Math.floor(Math.random() * 6);
var attempts = 0;
console.log(numberwang);
console.log(attempts);
document.getElementById("guessbutton").onclick = function(e) {
e.preventDefault();
if (document.getElementById("guess").value == numberwang) {
alert("That's numberwang!");
attempts = 0;
console.log("Attempts:",attempts)
} else {
alert("That's not numberwang, try again");
attempts = attempts + 1;
console.log("Attempts:",attempts)
}
}
<p>Guess a number</p>
<form><input type="text" id="guess"><button id="guessbutton">Guess</button></form>
However the else statement argument doesn't work. Each attempt does not add anything to my attempts variable. Can anyone see what is wrong? Thanks in advance.
Note: the else statement is not working for anything mathematical.
You are defining a variable everytime you click.
Removing the "var" from inside the if/else block
<p>Guess a number</p>
<form><input type="text" id="guess"><button id="guessbutton">Guess</button></form>
<script type="text/javascript">
var numberwang = Math.floor(Math.random() * 6);
var attempts = 0;
console.log(numberwang);
console.log(attempts);
document.getElementById("guessbutton").onclick = function(e) {
e.preventDefault();
if (document.getElementById("guess").value == numberwang) {
alert("That's numberwang!");
attempts = 0;
} else {
alert("That's not numberwang, try again");
attempts = attempts + 1;
}
}
</script>
Your problem is that when you use the var keyword, you are making a new variable. You should remove the var inside both the if and the else. This will let you change the outer attempts variable, and not the new one that you define by using the var.
var numberwang = Math.floor(Math.random() * 6);
var attempts = 0;
document.getElementById("guessbutton").onclick = function(e) {
e.preventDefault();
if (document.getElementById("guess").value == numberwang) {
alert("That's numberwang!");
attempts = 0;
} else {
alert("That's not numberwang, try again");
attempts = attempts + 1;
}
console.log("Attempts is: "+attempts);
}
<p>Guess a number</p>
<form><input type="text" id="guess"><button id="guessbutton">Guess</button></form>
I think that I understand what you are having a problem with. You expect what is already logged to the console to change when the variable changes. That's not how console.log works. It only logs the current value of the variable. If you want to see the new value, you should log it again, in this case after each guess is made.

Can a javascript file call a function defined in the main html file? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I can't seem to get this to work. I am including a javascript file with functions in it, but one of the functions in the file I want to be defined inside the main HTML file, not the javascript file. This isn't working however.
Here's what I want:
//testFile.js
$(function() {
$(window).scroll(function() {
var Scroll = $(window).scrollTop();
var Width = $(window).width();
var Height = $(window).height();
var Offset;
doParallax();
});
function Parallax(Obj, /*OffX, OffY,*/ ModifierX, ModifierY, Wait) {
var ScrollT = $(window).scrollTop();
var ScrollL = $(window).scrollLeft();
var OffsetY = ScrollT - $(Obj).data("InitialTopOffset");
var OffsetX = ScrollL - $(Obj).data("InitialLeftOffset");
var SpeedX = OffsetX*ModifierX + XOff;
var SpeedY = OffsetY*ModifierY + YOff;
if (Wait) {
if (ScrollT >= $(Obj).data("InitialTopOffset")) {
$(Obj).stop(true, false).css( "background-position", (ScrollL+SpeedX) + "px " + (-OffsetY-SpeedY) + "px", 50, "linear");
}
}
else {
$(Obj).stop(true, false).css( "background-position", (ScrollL+SpeedX) + "px " + (-OffsetY-SpeedY) + "px", 50, "linear");
}
}
});
//
//main HTML file
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function doParallax() {
XOff = ( $(window).width() - ( $(window).width()*0.9 ) ) / 2;
Parallax(".parallax3", 0, -0.55, true);
}
</script>
<script src="testFile.js"></script>
</head>
<body>
...
</body>
</html>
I haven't been able to find anything from doing google searches or from searching on Stack Exchange. But assuming that it isn't working means that I can't do this, but is there a way to achieve the desired result?
EDIT: Actual code examples
This is invalid:
<script src="testFile.js">
function somethingElse() {
alert("Called");
}
</script>
A script tag either references a script or contains a script. Not both. Separate them into their own tags:
<script src="testFile.js"></script>
<script>
function somethingElse() {
alert("Called");
}
</script>
(Of course, this is ignoring the fact that the contrived example never calls doSomething(), but I assume that's just an oversight in the example.)
Note also that there may be a scope issue depending on when you call this function. If doSomething() is invoked before somethingElse() is in scope, that could be a problem. You may be able to hoist it to the top of the current scope by defining it like this though:
var somethingElse = function() {
alert("Called");
}
Not sure if that's even an issue here though, since the code in the question doesn't actually invoke any functions.
Edit: Since the question has drastically changed...
In a comment above you mention the problem:
The console is actually now saying that Parallax() is not defined.
This is because that function exists only within the scope of the function you're using in the document.ready handler. To simplify:
$(function () {
// anything created here only exists here
});
// so you can't call it here
If you have functions which need to be invoked outside that scope, define them outside of that scope:
$(function () {
// perform document ready handler actions here
});
var Parallax = function() {
//...
}
var doParallax = function() {
//...
}

Javascript "onclick" attribute on button automatically running [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm using a for loop to dynamically name and fill buttons (with text and with code). One thing I had a problem with was dynamically allocating onclick functionality to the buttons, but I seemed to have fixed it with:
document.getElementById(ID_HERE).onclick = FUNCTION();
The problem is when I add this code, the buttons trigger themselves on the load of the webpage instead of the click.
I put the full code below for both the HTML and the Javascript.
JavaScript:
var routes = "";
var elem = "";
var locationid = "50017"
var currentRoute = "the Londinium Way"
function possibleRoutes(){
document.write("<div id='container'>");
document.write("<center><b> Welcome to ");
document.write(currentRoute);
document.write("!<br>")
document.write("Your options are:");
for (i = 0; i<routes.length;i++){
var options = routes[i];
var temp = "button" + i
document.write("<button id='button'></button>");
document.getElementById('button').id = temp;
document.getElementById(temp).innerHTML=routes[i][0];
document.getElementById(temp).onclick = getRoutes(routes[i][1]);
console.log(routes[i]);
console.log(routes[i][1]);
}
document.write("<br><img src='http://192.168.1.151:8000/map.jpg'>");
document.write("</b></center></div>");
}
function getRoutes(locationid) {
var routesURL = 'http://cors.io/?u=http://orbis.stanford.edu/api/sites/' + locationid;
$.ajax({
type: 'GET',
url: routesURL
}).done(function(data) {
console.dir(data);
dataParsed = JSON.parse(data);
currentRoute = dataParsed.prefname;
routes = dataParsed.routes;
console.log(routes);
clearScreen();
});
}
function clearScreen(){
if (document.contains(document.getElementById("container"))){
elem = document.getElementById("container");
elem.remove();
}
possibleRoutes();
}
HTML:
<html>
<head>
<title> Londinium Trail </title>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="http://192.168.1.151:8000/scripts/game.js"> </script>
</head>
<body>
<script>
getRoutes(50017);
</script>
</body>
</html>
JAVASCRIPT
Try to use addEventListener instead :
document.getElementById(ID_HERE).addEventListener("click", myFunction);
JQUERY
If you're using jquery :
$('body').on('click', '#ID_HERE', myFunction);
Take a look at addEventListener vs onclick.
Hope this helps.
The issue is that you are calling the function by using FUNCTION();
Since your code appears to be using JQuery, consider using the .on method to attach a click listening:
$(document).on('click', '#ID_HERE', function(){
function_to_run();
});

How to change image on click [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
So I want to change an image onClick and change it back oClick.
This is my current code, but for some reason it doesn't work. I can't find out what's wrong with it.
var newsrc = "suspects.png";
var newsrc = "questionmark.png";
function changeImage() {
if ( newsrc == "suspects.png" ) {
document.images["img"].src = "/images/suspects.png";
document.images["img"].alt = "suspects";
newsrc = "questionmark.png";
}; else {
document.images["img"].src = "/images/questionmark.png";
document.images["img"].alt = "questionmark";
newsrc = "suspects.png";
};
};
I´m pretty sure it´s good like this... Why doesn´t it work?
Toggle a image only checking the source
function toggle(){
var img=document.getElementById('img');
img.src=img.src=='url1'?'url2':'url1';// needs to be the full url.
}
Regarding you code:
you define newsrc 2 times and so the first one is lost.newsrc is always "questionmark.png"
}; else{
should be
}else{
and
if you have suspects set then you want questionmark if clicked, and not suspects.so invert the if content.
should be
if suspects then questionmark else suspects
you have
if suspects then suspect else questionmark.
DEMO
http://jsfiddle.net/SLkHu/
Remove extra semicolons ; in your code
It should be
function changeImage() {
if ( newsrc == "suspects.png" ) {
document.images["img"].src = "/images/suspects.png";
document.images["img"].alt = "suspects";
newsrc = "questionmark.png";
} else {
document.images["img"].src = "/images/questionmark.png";
document.images["img"].alt = "questionmark";
newsrc = "suspects.png";
}
}

Categories