why this console.log() function doesn't work? - javascript

<!DOCTYPE html>
<html>
<head>
<title>LearnJS</title>
</head>
<body>
<script>
console.log('hello World\nThis is me');
alert("This is an \nalert.");
</script>
</body>
</html>
I have tried this code and run in TORCH borwser... The only output shown is alert But it doesn't display output of console.log...
What is the possible solution...
I have use
document.write('hello World\nThis is me');
But this code doesn't feed new line so i was supposed to use console.log...

It is working fine here :). Run Code Snippet
<!DOCTYPE html>
<html>
<head>
<title>LearnJS</title>
</head>
<body>
<script>
console.log('hello World\nThis is me on console');
alert("This is an \nalert.");
document.write("This is an document.write.");
</script>
</body>
</html>
Note:
developers use console.log() for logging useful information on browser console
document.write() modifies what user sees in the browser by adding additional content to DOM.
alert()'s are used to alert end users who access the web page on browser.
N.B If you're in confusion about How stackoverflow.com shows console.log() on a browser div. Then see here https://stackoverflow.com/a/20256785/1138192 it is kind of overriding the default behavior of console.log() to show the messages on browser div. Hope this helps :)

console.log() only displays in the developer console of the browser. It does not display on the web page itself.
Your code is not feeding a new line because \n only shows in the source code not on the page. To display a new line in HTML on the page you need to use a <br> tag or use other form of spacing.
So, instead of:
document.write('hello World\nThis is me');
You could use:
document.write('hello World<br>This is me');
However, rather than using document.write(), you may prefer to write to a specific element in the page. Below I give an element an id of data and then use the JavaScript code to write to this element.
<!DOCTYPE html>
<html>
<body>
<div id="data">You can put text here or leave it blank. It will be replaced.</div>
<script>
document.getElementById("data").innerHTML = "Hello world<br>This is me";
</script>
</body>
</html>
Notice also, I need to place the document.getElementByID("data") script after the div is created. If I place it before it will not be able to find it. The script code is therefore placed at the end of the <body> section. There are better ways to do this (such as placing JavaScript code in an external file and using defer), but for your purposes this should work quite well.

Related

HTML will not execute JavaScript functions

I am trying to get a very simple javascript project going, but I cannot get any function to execute. Here is a simple example. It is obviously just an example. I have tried everything I can think of to get the browser to recognize that I am trying to call a function that has been defined, but it never does anything but just display the text, rather than call anything. In the below example, I simply get a page with the text: "varTimesTwo(3);"
<!DOCtype html>
<html>
<body>
<script>
function varTimesTwo(oneVar){
return (oneVar * 2)
}
</script>
varTimesTwo(3);
</body>
</html>
your code is wrong, you have to place varTimesTwo(3); inside the script tag, like this:
<!DOCtype html>
<html>
<body>
<script>
function varTimesTwo(oneVar){
return (oneVar * 2)
}
varTimesTwo(3);
</script>
</body>
</html>
Keep all JavaScript code in the script tags, or better yet, in a file
separate from the html file using <script src="myjsfile.js"></script>
You can use document.write(string) to write a string to the document.
This string is treated as HTML so you need to use <p>text</p> or <br> to get line breaks.
<!DOCtype html>
<html>
<body>
<script>
function varTimesTwo(oneVar){
return (oneVar * 2)
}
document.write("3 times two is "+varTimesTwo(3));
</script>
</body>
</html>
Alternatively, you can use window.alert(string) or simply alert(string) to pop up an alert box. But if you have turned off pop-ups in the browser, these will not pop up.
<!DOCtype html>
<html>
<body>
<script>
function varTimesTwo(oneVar){
return (oneVar * 2)
}
alert("3 times two is "+varTimesTwo(3));
</script>
</body>
</html>
console.log(string) writes to the debugging console, which you can see on many browsers with either control-shift-J or F12.
The javascript debugging console is also useful for learning javascript without messing with input and output. Anything you type in the JS console is immediately executed, so you can define functions there and play with them without having to write additional code to write the output or read input.
Finally, these techniques are insufficient for most websites as they are actually used. Instead, what is done is to define an html container element and change the text or html that is inside. jQuery provides a browser-independent method of manipulating the document to change items on the page.

Using Chrome Developer Tab for realtime html and javascript testing

In Google chrome web browser
about:blank gives an empty page and F12 gives you access to Developer Tab.
Right-clicking a source in Elements gives Edit as Html Option in Developer Tab
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<div>
<button id="myBtn">Button</button>
</div>
<div id="demo">
</div>
<script>
document.getElementById("myBtn").addEventListener("click", function () {
document.getElementById("demo").innerHTML = "Hello World";
});
</script>
</body>
</html>
Above is a JavaScript snippet which I copied in. But JavaScript code is not executing. Is this work flow of real time html editing not supported in chrome ?
Your script would ran, if it existed there when the page gets loaded. After the page has loaded, no script tags will just run when edited in.
You could wrap everything inside the script tags into a function and call that I think, however.
One other, but kind of a useless and technical trick that might let you run JavaScript, by editing in elements after the page has loaded, looks something like this:
If you add that in to the loaded page's HTML, the script inside that input-element's onfocus-attribute should run. This, however, is no proper way to do anything other than Cross-Site Scripting (XSS).
You can use a template literal, document.write() at console. At about:blank page press F12, at console enter
var html = `<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<div>
<button id="myBtn">Button</button>
</div>
<div id="demo">
</div>
<script>
document.getElementById("myBtn").addEventListener("click", function () {
document.getElementById("demo").innerHTML = "Hello World";
});
</script>
</body>
</html>`;
document.write(html);
then click <button> element.
You can alternatively click Sources -> Snippets, type or paste the above javascript at center window, click right-pointing triangle at right panel to run javascript at Snippets. You can also right-click at Snippets panel to create a new snippet to run.

Is it possible to define a function in <body> tag of <html> and call it form the <script> tag

I am new to HTML and Javascript, and I have a strange doubt
Is it possible to define a function in "body" tag of html and call it form the "script" tag
Till now i am trying this...
<!DOCTYPE html>
<html>
<head>
<script>
myFunction()
</script>
</head>
<body>
function myFunction()
{
alert("Hello World!");
}
</body>
</html>
No not possible. Browser only understands javascript within the <script> tag.
It will not work, try this,
<html>
<body>
<script>// don't miss script tags for javscript code
function myFunction()
{
alert("Hello World!");
}
</script>
<script>
myFunction(); // call if you have defined function earlier
</script>
</body>
</html>
IMHO:
<html>
<head>
<script>
function myFunction()
{
alert("Hello World!");
}
myFunction();
</script>
</head>
<body>
</body>
</html>
or you can use body Onload.
No U cant do it.....U should put js function within the script tag.....
you can do like this
<!DOCTYPE html>
<html>
<head>
<script>
myFunction();
function myFunction()
{
alert("Hello World!");
}
</script>
</head>
<body>
</body>
</html>
<html>
<head>
</head>
<body>
<script>
function myFunction()
{
alert("Hello World!");
}
myFunction()
</script>
</body>
</html>
I agree with Rohan but just to check I removed the 2nd pair of script tags and called the function in the same script block as it was defined and it worked but this is not normally the way things are done and this is not normally the use of an embedded JavaScript (js)
Doing a little extra research to find the best/optimum place for embedded js appears to be at the bottom of a webpage before the /body (closing body) tag
Here's a link to Yahoo's "speed up your website" guide:
Yahoo! Developer Network: Best Practices for Speeding Up Your Web Site
and here's the text from the page that refers to embedded js:
Put Scripts at the Bottom
tag: javascript
The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames.
In some situations it's not easy to move scripts to the bottom. If, for example, the script uses document.write to insert part of the page's content, it can't be moved lower in the page. There might also be scoping issues. In many cases, there are ways to workaround these situations.
An alternative suggestion that often comes up is to use deferred scripts. The DEFER attribute indicates that the script does not contain document.write, and is a clue to browsers that they can continue rendering. Unfortunately, Firefox doesn't support the DEFER attribute. In Internet Explorer, the script may be deferred, but not as much as desired. If a script can be deferred, it can also be moved to the bottom of the page. That will make your web pages load faster.
Also, if you go to the site and click the JavaScript tag you get a whole list of optimisations and tips - refer to the image!

Adding JavaScript code with jQuery.html()

<!DOCTYPE HTML>
<html>
<head>
<script src="js/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function() {
var x="<script>alert('hello world');</script>";
$("#div_one").html(x);
});
</script>
</head>
<body>
<div id="div_one">
</div>
</body>
</html>
Why does this not work? I'd expect the JS code between the script tags to be interpreted and see an alert message ...
What I want to do:
I have written a set of functions that add and delete items from an array depending on the user input (JavaScript). Then, I have a function that draws() a ul-list of the items held in the array. Behind each item, I want to provide a remove link, which calls a JavaScript function that removes the item from the array and then calls drawList() to redraw the list.
If there weren't that security policy, I'd simply do it as in the code shown above.
That is some weird browser bug I believe. For some reason you can't have </script> inside the script block.
Change to
var x="<scr"+"ipt>alert('hello world');</scr"+"ipt>";
Example on jsFiddle
That is not a bug. The problem is here:
<script>
$(document).ready(function() {
var x="<script>alert('hello world');</script>";
$("#div_one").html(x);
});
</script>
The browser thinks the first <script> tag is associated with the </script> inside your code.
As you can see, the code is shown in the DOM instead of executing.
To further prove it, see this example:
http://jsfiddle.net/DerekL/Ah8Qz/
var x = $("<script>").html("alert('hello world');");
$("#div_one").append(x);
If you avoid the </script> closing tag, then there will be no problem because the HTML parser will ignore any open <script> tag inside <script>.
So to sum up,
Browsers does not have security in place to stop scripts being injected into your page.
This is no where near a browser bug.

Beginner JavaScript: using src

EDIT:[Honestly this works fine you can read my edit comment below.]
So I am very new to JavaScript. This book I have tells me that I can write the script code in another file that has a .js extension. What it doesn't tell me is what should be in that .js extension.
<html>
<head>
<title>Title of Document</title>
<script src="path/to/file/fileName.js"></script>
</head>
<body>
The content of
your page goes here.
</body>
</html>
Lets say I wanted to make an alert message in the java script file. Inside the "fileName.js" would all I write be:
alert("This is an alert box");
and then save it and call it quits? Cause that is what I have so far and nothing doing.
EDIT:
Ok I want to add this in for anyone in trouble like I was. Turns out, this works perfectly. The comments below are a great help for further information. But the thing I did not realize was that on my Mac I needed to start the path to file at /Users. I feel dumb but at least I figured it out. Thanks all for your help.
Use " instead of ”:
<script src="path/to/file/fileName.js"></script>
^ ^
Generally your js files will have objects and Methods that are called/used from you main page.
So you html wiil look like :
<html>
<head>
<title>Title of Document</title>
<script src="path/to/file/fileName.js"></script>
</head>
<body onload="showAlert();">
The content of
your page goes here.
</body>
</html>
and you js will look like:
function showAlert(){
alert("This is an alert box");
}
Look into events and listeners. For example, if you want the alert to come up when the page loads, your html file would have:
<body onload="functionName()">
</body>
And you javascript file would have:
function functionName() {
alert("alert message");
}
Usually you would write your Javascript code as a series of functions that you can call whenever you need. So yes, you can write a single statement the way you did but most times its functions.

Categories

Resources