I'm doing a coding challenge that requests we ask just one multiple choice question - if the answer is correct, it prints a congrats and exits the program. if wrong, it offers the user the chance to try again or exit the program. I've only been coding for a few weeks and it still simpler for me to use if/else if for this - but we need to use a Do While loop. Below is what i have so far and any advice would be appreciated:
let answer = [""]
do {
prompt("What shape is the Earth? \nA: Square\nB: Triangle\nC: Round\nD: Flat");
} while (answer != C);
console.log("I'm sorry you're an idiot.")
let retry = alert("Try again? Y/N")
if (retry == Y) {
//how to reset loop from here?
}
else if (retry == N) {
//how to exit program?
}
if(answer === C) {
console.log("Congratulations! You're not an idiot :)")
}
Let's put your code in a snippet:
let answer = [""]
do {
prompt("What shape is the Earth? \nA: Square\nB: Triangle\nC: Round\nD: Flat");
} while (answer != C);
console.log("I'm sorry you're an idiot.")
let retry = alert("Try again? Y/N")
if (retry == Y) {
//how to reset loop from here?
}
else if (retry == N) {
//how to exit program?
}
if(answer === C) {
console.log("Congratulations! You're not an idiot :)")
}
Now click the Run code snippet button above and watch what happens.
Do you see the error message? That is the first thing to fix, and this is your first step in learning how to debug your code.
Debugging is one of the most valuable skills you will need in programming. For JavaScript in a browser, you will want to get familiar with the Developer Tools that are built into every browser. If you use Chrome or the new Edge browser, here is a guide to the Chrome DevTools.
The DevTools include an interactive Console where you can see error messages and type in expressions to see what they do. They also include a Source view where you can set breakpoints in your source code and look at your variables, and many other debugging features.
A Stack Overflow snippet like the one above has a built-in Console so you can see the error message right here in the page. For code you're running in your own web page, use the browser's developer tools to see errors, test expressions, set breakpoints, and view your variables.
I kind of get all my coding information from the internet rather than a class, and certain answers I can't really understand so hopefully I'll get a simple answer to a possibly stupid question.
In a part of my website, I've got a button which brings up a window.prompt and it asks the viewer if they would like to go to one page (I've called it Timeline because it's a timeline of my art portfolio) or to the other. The prompt works perfectly fine, and I attempted to code it so that if, for example, the user typed in "Timeline" the webpage would automatically redirect them to the Timeline page (which for me is empty at the moment) and vice versa if they typed in "Term 1" (the name of the other page.) I found out about window.location.replace and assumed that it would work if I tried to get it to redirect the user, but when I run my webpage nothing happens after I type in the prompt window. I checked the Developer Tools on Chrome and it didn't report any errors, so is it just me typing some stuff wrong?
function promptFunction() {
var choice = window.prompt ("Would you like to go to the Timeline or to Term 1?")
if (choice === "Timeline")
function redirTime() {
window.location.replace() ("Timeline.html");
}
else if (choice ==="timeline")
function redirTime() {
window.location.replace() ("Timeline.html");
}
else if (choice ==="Term 1")
function redirFirstTerm() {
window.location.replace() ("Term 1.html")
}
else if (choice ==="term 1")
function redirFirstTerm() {
window.location.replace() ("Term 1.html")
}
};
This again is probably me looking for an answer that's right under my nose, so if the answer is something obvious, sorry ^^'
Edit: I've got an answer now; thank you very much! (I did think it was something to do with the way I was typing it, sorry)
The code you posted creates, based on choice a function, but the function is never executed (or you omitted this code).
Additionally the window.location.replace()("...") part is wrong. It calls the replace function on window.location with no arguments and uses the result of this function call again as function an passes e.g. "Timeline.html" as argument.
If all you want to do is setting the location, assign it directly, e.g. window.location = "https://stackoverflow.com" or in your case window.location.href = "Timeline.html" (see https://developer.mozilla.org/en-US/docs/Web/API/Window/location).
I made a javascript function and I am trying to execute it in the javascript area. However, it will not run. When I run the code it just does nothing. I am using Github, so if you want my full code, go to https://github.com/TheNumnut/Wars-of-Shares/blob/master/Login/index.html
I am trying to make a Login page for a game. I would rather use forms than prompts but I have not been able to do that. If somebody could tell me how to use forms I will greatly appreciate it.
This is my code:
function checkCookie(checkusername, checkpassword) {
if (getCookie("username") != "") {
setCookie("username", checkusername, 365);
setCookie("password", checkpassword, 365);
}
else {
if (checkusername != getCookie("username") {
alert("Username wrong");
}
else {
if (checkpassword != getCookie("password") {
alert("Password wrong");
}
}
}
window.open("https://thenumnut.github.io/Wars-of-Shares/", "_self");
}
checkCookie(prompt("Username"), prompt("Password: ");
Please have a look at my other code in Github, because it also has not been working. Especially the profile page. None of the clickable text and links have been working. The link to the Profile Page is https://github.com/TheNumnut/Wars-of-Shares/blob/master/Profile/index.html
Your JS code has syntax errors.
You're missing an extra ) in the 7th, 11th and 42th line.
You can press F12 on your browser and check the console tab, where javascript errors are displayed.
However, I need to agree with the other users that this login method is not a good practice and it's very easy to bypass.
JavaScript source is available to the user of any website. Since the JavaScript runs in the user's browser, the code has to be transferred to the user's browser so the browser knows what to do. This means I as the user can view the source. In this case, by viewing the source I can see the line:
window.open("https://thenumnut.github.io/Wars-of-Shares/", "_self");
So I can bypass your log in page just by looking at the page source and going straight to https://thenumnut.github.io/Wars-of-Shares/
In Firefox 3, I was able to write a custom confirmation popup with:
window.onbeforeunload = function() {
if (someCondition) {
return 'Your stream will be turned off';
}
}
Now in Firefox 4, it does not show my custom message. The default message that it provides is not even accurate to what my application does.
Can this default message be overridden?
From MDN:
Note that in Firefox 4 and later the returned string is not displayed to the user. See Bug 588292.
This "Bug" is actually a (imho questionable) feature.. so there's no way to display the message in Firefox 4. If you think it should be changed, comment on that bug so the Firefox developers will know that people actually want to be able to show a custom string.
Addition to the above Answer, I have improved the workaround.
I have used jquery here. you can use default javascript funciton as well.
$(window).bind('beforeunload', function() {
if(/Firefox[\/\s](\d+)/.test(navigator.userAgent) && new Number(RegExp.$1) >= 4) {
if(confirm("Are you Sure do you want to leave?")) {
history.go();
} else {
window.setTimeout(function() {
window.stop();
}, 1);
}
} else {
return "Are you Sure do you want to leave?";
}
});
Tested and working in firefox 11 as well. :)
My workaround is to show alert in onbeforeunload:
window.onbeforeunload=function() {
if ( /Firefox[\/\s](\d+)/.test(navigator.userAgent) && new Number(RegExp.$1) >= 4) {
alert("Blah blah. You have to confirm you are leaving this page in the next dialogue.");
}
return "Blah blah.";
}
(It shows two dialogues in Firefox, one dialogue elsewhere.)
Try implementing it with a confirm message,
window.onbeforeunload=function(){
return confirm("Are you sure??");
}
of course when the user confirms then the FF4 message is shown,
so you maybe better display this once per site on login/visit.
A cookie should do the trick.
How can I print a message to the error console, preferably including a variable?
For example, something like:
print('x=%d', x);
Install Firebug and then you can use console.log(...) and console.debug(...), etc. (see the documentation for more).
console.error(message); // Outputs an error message to the Web Console
console.log(message); // Outputs a message to the Web Console
console.warn(message); // Outputs a warning message to the Web Console
console.info(message); // Outputs an informational message to the Web Console. In some browsers it shows a small "i" in front of the message.
You also can add CSS:
console.log('%c My message here', "background: blue; color: white; padding-left:10px;");
More info can be found here: https://developer.mozilla.org/en-US/docs/Web/API/console
Exceptions are logged into the JavaScript console. You can use that if you want to keep Firebug disabled.
function log(msg) {
setTimeout(function() {
throw new Error(msg);
}, 0);
}
Usage:
log('Hello World');
log('another message');
One good way to do this that works cross-browser is outlined in Debugging JavaScript: Throw Away Your Alerts!.
Here is a solution to the literal question of how to print a message to the browser's error console, not the debugger console. (There might be good reasons to bypass the debugger.)
As I noted in comments about the suggestion to throw an error to get a message in the error console, one problem is that this will interrupt the thread of execution. If you don't want to interrupt the thread, you can throw the error in a separate thread, one created using setTimeout. Hence my solution (which turns out to be an elaboration of the one by Ivo Danihelka):
var startTime = (new Date()).getTime();
function logError(msg)
{
var milliseconds = (new Date()).getTime() - startTime;
window.setTimeout(function () {
throw( new Error(milliseconds + ': ' + msg, "") );
});
}
logError('testing');
I include the time in milliseconds since the start time because the timeout could skew the order in which you might expect to see the messages.
The second argument to the Error method is for the filename, which is an empty string here to prevent output of the useless filename and line number. It is possible to get the caller function but not in a simple browser independent way.
It would be nice if we could display the message with a warning or message icon instead of the error icon, but I can't find a way to do that.
Another problem with using throw is that it could be caught and thrown away by an enclosing try-catch, and putting the throw in a separate thread avoids that obstacle as well. However, there is yet another way the error could be caught, which is if the window.onerror handler is replaced with one that does something different. Can't help you there.
If you use Safari, you can write
console.log("your message here");
and it appears right on the console of the browser.
To actually answer the question:
console.error('An error occurred!');
console.error('An error occurred! ', 'My variable = ', myVar);
console.error('An error occurred! ' + 'My variable = ' + myVar);
Instead of error, you can also use info, log or warn.
If you are using Firebug and need to support IE, Safari or Opera as well, Firebug Lite adds console.log() support to these browsers.
The WebKit Web Inspector also supports Firebug's console API (just a minor addition to Dan's answer).
A note about 'throw()' mentioned above. It seems that it stops execution of the page completely (I checked in IE8) , so it's not very useful for logging "on going processes" (like to track a certain variable...)
My suggestion is perhaps to add a textarea element somewhere in your document and to change (or append to) its value (which would change its text) for logging information whenever needed...
As always, Internet Explorer is the big elephant in rollerskates that stops you just simply using console.log().
jQuery's log can be adapted quite easily, but is a pain having to add it everywhere. One solution if you're using jQuery is to put it into your jQuery file at the end, minified first:
function log()
{
if (arguments.length > 0)
{
// Join for graceful degregation
var args = (arguments.length > 1) ? Array.prototype.join.call(arguments, " ") : arguments[0];
// This is the standard; Firebug and newer WebKit browsers support this.
try {
console.log(args);
return true;
} catch(e) {
// Newer Opera browsers support posting erros to their consoles.
try {
opera.postError(args);
return true;
}
catch(e)
{
}
}
// Catch all; a good old alert box.
alert(args);
return false;
}
}
Visit https://developer.chrome.com/devtools/docs/console-api for a complete console api reference
console.error(object[Obj,....])\
In this case, object would be your error string
function foo() {
function bar() {
console.trace("Tracing is Done here");
}
bar();
}
foo();
console.log(console); //to print console object
console.clear('console.clear'); //to clear console
console.log('console.log'); //to print log message
console.info('console.info'); //to print log message
console.debug('console.debug'); //to debug message
console.warn('console.warn'); //to print Warning
console.error('console.error'); //to print Error
console.table(["car", "fruits", "color"]);//to print data in table structure
console.assert('console.assert'); //to print Error
console.dir({"name":"test"});//to print object
console.dirxml({"name":"test"});//to print object as xml formate
To Print Error:- console.error('x=%d', x);
console.log("This is the outer level");
console.group();
console.log("Level 2");
console.group();
console.log("Level 3");
console.warn("More of level 3");
console.groupEnd();
console.log("Back to level 2");
console.groupEnd();
console.log("Back to the outer level");
console.log("your message here");
working for me.. i'm searching for this.. i used Firefox.
here is my Script.
$('document').ready(function() {
console.log('all images are loaded');
});
works in Firefox and Chrome.
The simplest way to do this is:
console.warn("Text to print on console");
To answer your question you can use ES6 features,
var var=10;
console.log(`var=${var}`);
This does not print to the Console, but will open you an alert Popup with your message which might be useful for some debugging:
just do:
alert("message");
With es6 syntax you can use:
console.log(`x = ${x}`);