Beginner JavaScript: using src - javascript

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.

Related

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

<!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.

html not responding to outside js file changes

//index.php
<head>
<script src="/js/test.js"></script>
<style></style>
</head>
<body>
<script>
callalert();
</script>
</body>
//test.js
function callalert() {
alert('Allertt');
}
eg: i change the fn completely to: callalert(msg) {
var msg;
alert(msg);
}
//and html to:
callalert('Hello!');
//and it wont change, it still says "Allertt"
Anything would be appreciated!
So recently i've tried to implement some javascript libraries to a webpage. But html wont call anything from other js files. I tried many things, calling simple functions from js files, and somtimes it works but when I delete the test, function the page will display the same result as the functions is still there. It will take a long time for it to respond to the changes of the js.
I even tried from diffrent devices.
Anything would be appreciated!
Edit: When i posted this i modified the function from 'Allertt' to 'Hello!'.
Now, that I checked after 5hrs the script is updated. Also, yes this is running online on a server.
I have prepared an example for you, which works perfectly:
HTML FILE
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<script>
myFun();
</script>
</body>
</html>
External JS
function myFun(){
alert('test');
}
This calls myFun from external file, on every refresh, like it should.

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.

Access javascript method from another file in HTML

The question is trivial, but I'm dumb as rock with JS, and I'd like to save myself some of the precious time I need. For some reasons, nothing happens when I call a method from a javascript file in HTML:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script src = "game.js"></script>
<button onclick = "init()">Start</button>
</body>
</html>
And game.js:
function init(){
alert("external fn clicked");
}
Needless to say, the alert does not appear as expected. What am I missing?
The reason was entirely trivial - the console is actually useful (ctrl+shift +j on Windows and Chrome). The js did not load properly due to a syntax error.

My first dig at jQuery

I'm a complete newbie as far as jQuery is concerned. I also don't know much of JavaScript except for some very basic stuff.
I'm following this tutorial here: http://docs.jquery.com/How_jQuery_Works
And nothing's working! :-)
I created a folder on my machine's hard drive here: C:\rnd\jQuery
Then, in that folder, I put the jquery.x.x.js file that I downloaded from the jQuery website and I created a test.html file and wrote the following code in it:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<style type="text/css">
a.test { font-weight: bold; }
</style>
<script type="text/javascript">
$.(document).ready(function() {
$("a").addClass("test");
$("a").click(function(event) {
alert("Thanks for visiting.");
event.preventDefault();
});
});
</script>
</head>
<body>
jQuery
</body>
</html>
It just does the normal behavior of taking me to the jQuery website. I ran it on Chrome, IE and Firefox. I have JavaScript enabled in the browsers. It's all the same everywhere. It doesn't do anything that I expected it to do. It just takes me to the website.
Except on IE, it shows me that message box saying an error occurred in your script. When I click "Yes" to debug, it opens up the debugger but it doesn't highlight any line of code so I don't really know what's happening.
Then, when I had the following line to my code:
$("a").hide("slow");
And my complete code looks like this:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<style type="text/css">
a.test { font-weight: bold; }
</style>
<script type="text/javascript">
$.(document).ready(function() {
$("a").addClass("test");
$("a").click(function(event) {
alert("Thanks for visiting.");
event.preventDefault();
$("a").hide("slow");
});
});
</script>
</head>
<body>
jQuery
</body>
</html>
At this, nothing different happens in Firefox and Chrome, but in IE, it breaks again into the debugger, this time with this line highlighted in yellow, and it reports that the identifier jQuery is not defined.
(function($) {
$.fn.textDropShadow = function(){
$(this).html('<span class="jq-shadow">'+$(this).html()+'</span><span>'+$(this).html()+'</span>');
return $(this);
}
})(jQuery);
And that, I believe is some JavaScript code on the jQuery website.
I feel completely lost. Any help would be appreciated.
Update:
I have my complete HTML and it is valid XHTML. It's too bad the browser displays that as an HTML response stream and I can't even get it to show up here as a script. Damn! How do you make HTML show up here?
I can see one issue. You have a . following the $ in the document ready statement.
$.(document).ready(function()
^--- remove the .!
It should look like this:
$(document).ready(function()
First off make sure you have the jQuery library referenced before writing any jQuery code (or loading any plugins)
<script type="text/javascript" src="{path to jquery.x.x.js}" ></script>
Also, it should be $(document).ready(function() { });
not $.(document)
Obviously the problem was an extra dot in the $.document part however here is a tip for you when learning jquery.
You may find yourself in the situation that you have another javascript library running on the page and it's using the $ symbol too. A good way to keep your jquery separate from the other library but still share the $ symbol is to alias $ inside your jquery init statement.. like so.
// the dollar symbol doesn't exist outside of this as we started it with jQuery so i personally like this approach.
jQuery(document).ready(function($) {
$('#...');
});
Did you include the line:
<script type="text/javascript" src="jquery.js"></script>
You need to show more of your page for us to know what's wrong.

Categories

Resources