I wrote HTML document and linked to my JS document.
when I execute the HTML file on my browser it only shows the "Click me!" button, but what I expected it to do was to show the result of my math function when clicked. But .. nothing happens. I'm very new to JavaScript so I'm sure this is a simple answer, but Googling isn't helping ... I appreciate any insight to what I'm doing wrong here.
Here's the code from HTML file:
<!DOCTYPE html>
<html lang=""en">
<head>
<meta charset="UTF-8">
<script src="JS/main.js"></script>
</head>
<body>
<p id="Math">
<button onclick="myFunction()">Click me!</button>
</p>
</body>
</html>
Here's the JS file:
function myFunction(a, b) {return a * b;}
document.getElementById("Math") .innerHTML = myFunction(13, 4);
Not sure what are you trying to do, but if you want to change the content of the "Math" element, you must call the function with parameters (eg: onclick="myFunction(1,3)") and that function should replace the content:
function myFunction(a, b) {
document.getElementById("Math").innerHTML = a * b;
}
<p id="Math">
<button onclick="myFunction(3,4)">Click me!</button>
</p>
Also if you want to preserve the button after clicking, this should be located outside the "Math" element to avoid being removed when replacing innerHTML
You’re including you script file in the header, so it runs before the dom is available. When it executes, it won’t be able to find your id, so nothing will happen. You likely will see an error in the console that your document.getElementById call is returning undefined. Either include it at the end of the body, or add a defer tag:
<script src="JS/main.js" defer></script>
Also, as soon as the code runs, it overwrites the content of the p tag, including the button. Make the p and the button siblings.
One error in your html appears to be caused by an extra " in your lang attribute for your opening html tag. Try deleting it.
<html lang="en">
Related
I wrote a function in JS code, and I want to run it from HTML, but I don't see any reaction, when I run the site.
I will show you example of html code and js code.
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="test.js">
<script src="test.js"></script>
</head>
<body onload="add()">
<p id="add2"></p>
</body>
</html>
Here starts JS code
function add(a,b,c,d) {
return a + b + c + d;
}
document.getElementById("add2").innerHTML = add(5,10,15,20);
I hope I wrote it clearly and someone will tell me, what did I do wrong?
Your JavaScript code is in the head, which is before the body and everything else, so the JavaScript runs before the p element has been created (html is run line by line). To fix this issue, you can try putting the JavaScript at the end of the document, for example after body.
When a browser loads an HTML page, it reads your HTML from top-to-bottom.
So ordering is important.
There are complexities of course. I'm not talking about deferred or asynchronous scripts here. But the top-to-bottom simplification helps us understand your problem.
Your script is inside test.js, so it will be loaded and run before [body] is ready.
But test.js has this line:
document.getElementById("add2").innerHTML = add(5,10,15,20);
This line is not inside a function, so the browser will try to run it immediately.
The call to add() will work because it has been declared in the file. But document.getElementById("add2") will not, because it is an instruction to access the following HTML in the [body]:
<p id="add2"></p>
But the [body] has not been "read" yet, so the JavaScript DOM API does not know about it.
However, you have partially solved the problem already using the onload attribute of the [body] tag. You've just used the wrong function with it.
That onload is an instruction to run a function after [body] has been completely read. So if you changed your document.getElementById line to be inside a function:
function runWhenBodyHasLoaded () {
document.getElementById("add2").innerHTML = add(5,10,15,20);
}
And told the [body] tag to run the function after everything has loaded:
<body onload="runWhenBodyHasLoaded()">
Then <p id="add2"></p> will be ready in time to access it with document.getElementById.
Or with jQuery:
https://jsfiddle.net/bdgu8s4h/1/
Also consider loading your JS at the end (of body)
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="test.css">
</head>
<body>
<p id="add2"></p>
<script type="text/javascript" src="test.js"></script>
</body>
</html>
JS (jQuery):
$(document).ready(function() {
function add(a,b,c,d) {
return a + b + c + d;
}
$('#add2').html(add(5,10,15,20));
});
Hope this also helped, cheers
i'd like to isolate the javascript code from the html code in two diferent files, originally I had this code:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<p id="body">HTML Text</p>
</body>
</html>
<script>
$(document).ready(function () {
$("#body").text("JS Text");
});
</script>
and the output of the <-p-> was the expected "JS Text".
Then I tried to isolate the js script to another file (script.js):
window.onload = function(){
var text = document.getElementById('body');
text.innerHTML ='JS Text';
}
I've also make the reference at the html file:
<script type="text/javascript"src="scripts.js"></script>
but then the output text is no longer the expected (JS Text) but (HTML text)
what else do I need to make the js script work again?
First, it is invalid to place anything after the closing HTML tag, so while your first bit of code worked, it was invalid.
If you remove the JavaScript and place it in its own file, it will continue to work as long as you reference the file properly (use a relative reference and test the file on a web server) and place the script element just prior to the closing body tag so that when the script is processed and attempts to find the right DOM element, the DOM will have been loaded at that time.
FYI:
If you have JQuery in the referenced script file, then your
script that references JQuery will need to occur in the HTML prior
to the script that uses it.
The type attribute in the script tag has not been needed in
several years.
It's not a good idea to name anything body so that you won't cause
confusion with the body element.
Don't use .innerHTML when the string you are working with doesn't
contain any HTML. .innerHTML has security and performance
implications. Use .textContent instead.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<p id="body">HTML Text</p>
<script src="relativePathToFile.js"></script>
</body>
</html>
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.
In the below html, the front button doesn't respond while the back button changes the content of the tag.
<!DOCTYPE html>
<html>
<body>
<p id ="para">Initial text. </p>
<button onClick=document.getElementById('para').innerHTML="move front">
front
</button>
<button onClick=document.getElementById('para').innerHTML="back">
back
</button>
</body>
</html>
In the below, both the buttons change the content of the tag.
<!DOCTYPE html>
<html>
<body>
<p id ="para">Initial text. </p>
<button onClick=document.getElementById('para').innerHTML="movefront">
front
</button>
<button onClick=document.getElementById('para').innerHTML="back">
back
</button>
</body>
</html>
Why does a bank space make a button unresponsive?
That is just invalid HTML.
You have to put quotes around your whole onclick attribute value, otherwise it will end at the space.
onClick = document.getElementById('para').innerHTML="move // cut off here
front" // a second (meaningless) attribute for your button tag.
Please consider this syntax:
<button onclick="document.getElementById('para').innerHTML='move front'">front</button>
You are probably having issues if you are using this technique.
I am sorry but this is not how you attach a click event to elements in modern javascript, at least if you want to work with what's called "good practices".
The better method would be to attach a click event to a desired element using javascript.
I will give you a short code example.
First the HTML - I will use your original HTML (modified a bit):
<!DOCTYPE html>
<html>
<body>
<p id ="para">Initial text. </p>
<button id="frontBtn"> front </button>
<button id="backBtn"> back </button>
</body>
</html>
As you can see, I have removed your "onclick" events from the buttons, and assigned an id to each button.
Second, we will write some javascript to properly attach a click event to each one of the buttons, and of course execute the change of text as you originally was intending to do:
if you are familiar with jQuery then this will do:
$('#frontBtn').on('click',function(){
$('#para').html('move front');
});
$('#backBtn').on('click',function(){
$('#para').html('back');
});
This can also be done with vanilla (native) javascript:
document.getElementById("frontBtn").addEventListener("click", function(){
document.getElementById("para").innerHTML = "move front";
});
document.getElementById("backBtn").addEventListener("click", function(){
document.getElementById("para").innerHTML = "back";
});
Now we have a nicely structured event handler for each button, more code can be easily added.
As for where to insert your javascript ?
You can add the javascript to your html document by using script tags in your html document head like this:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
// your code here..
</script>
</head>
<body>
....
....
Or even better - create a separate script file and load it at the bottom of your html page like this:
<!DOCTYPE html>
<html>
<head>
....
</head>
<body>
....
....
<script type="text/javascript" src="scripts.js"></script>
</body>
</html>
This is the better way to attach events to elements, using javascript.
Imagine if you try to write 50-100 lines of code inline ? impossible! but with an event handler function you can do it easily.
Things will basically work better and your project will be much easier for you to maintain.
Hope it helps a bit!
I have been trying to use the document.getElementByID to pull information from an HTML file from an external JS file and it does not seem to be working. Does the document.getElementByID only work if it is inline with the HTML file or can it work properly on an external JS file? The JS file is called upon within the HTML document properly because other functions are working.
First off, make sure you're using document.getElementById("xxx"), not document.getElementByID("xxx") (note the difference in capitalization at the end). Your question refers to document.getElementByID("xxx") so that could be the problem right here.
Second, you must make sure that the function is executed AFTER the relevant DOM items have been parsed by the browser. If you are putting the document.getElementById in an external JS file that is loaded in the <head> section and is executed immediately after it loads, then the DOM will not yet be ready.
You have several options:
1) Place the external JS file <script> tags at the end of the body, right before the </body> tag. This will not only load/display your page faster, but will guarentee that the DOM is parsed before anything in that JS file can run.
<body>
Your HTML here
<script type="text/javascript" src="myscript.js"></script>
</body>
2) Since you have jQuery, put your immediately executed code inside of a $(document).ready(fn) block so that jQuery will hold back the execution until the DOM is ready. If you do it this way, then you can put your code anywhere (including in the <head> section if you want).
$(document).ready(function() {
// put your page initialization code here
});
3) Put your code anywhere you want, but don't have any of it execute immediately. Instead, put all your initialization code in an intialization function (let's call it myPageInit() that you call from:
$(document).ready(myPageInit);
4) Put your code anywhere you want, but don't have any of it execute immediately. Instead, put all your initialization code in an intialization function (let's call it myPageInit() that you call from a script right before the </body> tag with this:
<script type="text/javascript">myPageInit()</script>
Does the document.getElementByID only work if it is inline with the HTML file
No.
can it work properly on an external JS file?
Yes.
You're probably calling document.getElementById() before the DOM is ready.
My suggestion is to do this:
window.onload = function () {
// document.getElementById() code here
}
Then your document.getElementById() would not execute until every element on the page has fully loaded.
If you put the script in the <head> then the body hasn't loaded yet and so the elements aren't there.
Either defer the script by using jQuery's functions, or put the script at the end of the body.
window.onload = function() {
document.getElementById("demo").innerHTML = "My First JavaScript";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>js in ts</title>
<script src="app.js"></script>
</head>
<body>
<h2>JavaScript in Body</h2>
<p id="demo"></p>
</body>
</html>