Unable to link a self-executing function with html? - javascript

I am very new to Java Script. I am studying with the help of video lectures, and trying to solve the examples discussed. In the chapter Anonymous Self executing function, I am unable to link self execute function.
My codes are as follows:
Html::
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8";
</head>
<body>
<p id="message">
</p>
<script src="my2.js"> </script>
<script src="my.js"> </script>
</body>
</html>
my.js:
( function()
{
function Format(num) {
return Math.floor(num);
}
ShowMessage("You are viewing a lesson in section" + Format(9.1));
}());
my2.js:
functon ShowMessage(msg)
{
document.getElementById("message").innerHTML += Format(msg);
}
function Format(msg)
{
return "<p>" + msg + "</p>";
}
Please help me.

Is this it?
(function()
{
function Format(num) {
return Math.floor(num);
}
ShowMessage("You are viewing a lesson in section" + Format(9.1));
})();
I think you messed the brackets.
Still, this happens in javascript because you are evaluating a function as an expression.
This means that your function is only giving scope to a piece of code, and since you call it after closing de scope })();, it gets evaluated as an expression.
Following that logic, you can even do:
!function()
{
function Format(num) {
return Math.floor(num);
}
ShowMessage("You are viewing a lesson in section" + Format(9.1));
}();
That the function is also run.
[EDIT] You missed the closing '>' in your meta tag too.

Looks like you've got a few typos in your code:
In your HTML code (line 5):
<meta charset="UTF-8"> <!-- ">" instead of ";" -->
In my2.js:
function ShowMessage(msg) { // you forgot an "i" in your code
The first one will be corrected automatically in most browsers (however: you should avoid this). But the second one will raise an error and you can't call ShowMessage() anymore.

You misspelled function in my2.js
function ShowMessage(msg)
{
document.getElementById("message").innerHTML += Format(msg);
}
function Format(msg)
{
return "<p>" + msg + "</p>";
}

Related

Can you print a page in a function being defined in javascript?

I have (had 2 years ago lol) been working on a web page that prints everything on it, and need to define a function that gets a value, replaces the text box with the value, hides the print button, and prints the page.
<!DOCTYPE HTML>
<HTML>
<head>
<title>KB documents</title>
</head>
<body>
<style>
body {
text-align:center;
}
</style>
<div id="hidden">
<textarea cols="125" rows="30" id="value"></textarea>
</div>
<button id="button" onclick="print()">print document</button>
<script>
function print() {
var value = document.getElementById("value").value;
document.getElementById("hidden").innerHTML = "<p>" + value + "</p>";
document.getElementById("button").style.display = "none";
window.print()
}
</script>
</body>
</html>
It works perfectly--with the exception of printing the page, the most important part.
Thanks in advance.
Your function print on the top level is overwriting the built-in window.print. Use a different variable name so that window.print does not get reassigned:
<button id="button" onclick="doPrint()">print document</button>
<script>
function doPrint() {
var value = document.getElementById("value").value;
document.getElementById("hidden").innerHTML = "<p>" + value + "</p>";
document.getElementById("button").style.display = "none";
window.print()
}
But it would be better to avoid inline handlers, they have way too many problems to be worth using nowadays, such as a demented scope chain and quote escaping issues. Attach event listeners properly using Javascript with addEventListener instead.
document.querySelector('#button').addEventListener('click', () => {
var value = document.getElementById("value").value;
document.getElementById("hidden").innerHTML = "<p>" + value + "</p>";
document.getElementById("button").style.display = "none";
window.print()
});

Can anyone help me figure out what's wrong in this peice of javascript?

Hey every I am getting an error in this following piece of code, I am using HTML & JAVASCRIPT.
Can any help me fix this out?
I am getting Undefined error.
Here is the code.
<script type="text/javascript">
var x;
function setvar() {
var x = "Hello World";
}
function alt() {
alert(x);
}
</script>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body onload="setvar();">
<button onclick="alt();">Do it!!</button>
</body>
</html>
It is a scoping issue. if you use var inside a function, that variable will only exist in the scope of that function.
So what you could do is this:
var x;
function setVar() {
x = 'Hello World';
}
function alt() {
alert(x);
}
By removing var in the setVar function, you're updating the var that is created outside the function.
Hope that makes sense.

Javascript if statement issue: No display in the webpage

I have a VERY BASIC knowledge of javascript and I was looking forward to learn some conditional statement in javascript. So I went on and entered this code in a HTML file called "index.html":
<!DOCTYPE html>
<html>
<head>
<title>A sample webpage</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
And the result that came was completely normal. A title called "Sample Webpage" appeared.
But the next code what I entered created problems in the result,
var myNumber = window.prompt("Enter number: ");
parseFloat(myNumber);
document.write(myNumber);
The result comes as expected.
if (myNumber > 15) {
document.write(<p>Good! You've passed! </p>);
}
else {
document.write(<p>You failed! Try again next time.</p>);
}
But when I add this if statement which gives an output based on the user's input, I get a blank page. I don't understand what is the reason for this. Are there any problems in the syntax?
It also seems to me that it doesn't execute the first part of the code I've written, it completely wants all of the code. I feel this is normal but doesn't it have to actually execute the "document.write" code?
Way I see it, you need to quote your strings in document.write(string).
like this:
if (myNumber > 15) {
document.write("<p>Good! You've passed! </p>");
}
else {
document.write("<p>You failed! Try again next time.</p>");
}
I hope it is useful for you. Thank you.
document.write takes a string as argument. You pass it HTML.
Just change
document.write(<p>Good! You've passed! </p>);
to
document.write('<p>Good! You've passed! </p>');
to make it work. A better approach is to add
<p id="message"></p>
to the page and where you have
document.write('<p>Good! You've passed! </p>');
you can use
document.getElementById('message').textContent='Good! You've passed!';
document.getElementById("myButton").addEventListener('click', function() { // when clicked
let myNumber = window.prompt("Enter number: ");
myNumber = parseFloat(myNumber); // convert to number from string
document.getElementById('number').textContent = myNumber;
const msg = document.getElementById('number'); // output container
if (myNumber > 15) {
msg.textContent = 'Good! You\'ve passed!' // escaping the quote
}
else {
msg.textContent = 'You failed! Try again next time.';
}
});
// above can be written using a so called ternary:
// msg.textContent = myNumber > 15 ? 'Good! You\'ve passed!' : 'You failed! Try again next time.'
<!DOCTYPE html>
<html>
<head>
<title>A sample webpage</title>
</head>
<body>
<p id="number"></p>
<p id="message"></p>
<button type="button" id="myButton">Did you pass?</button>
<script src="script.js"></script>
</body>
</html>

Why is my output repeating?

I want to alert "running function cannons" then when I press ok I want it just to say "cannon ship sails off to 14 degrees" but it keeps printing the alert within my output.
JS
function alertMessage (message) {
alert (message);
}
alertMessage("the Battle has begun");
function alertShip (ship, number) {
alert (ship);
document.write (ship + "the ship sails off to " + number + "degrees");
}
alertShip("running function cannons", 14);
HTML
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Functions</title>
<!-- This links to the js code specific for this page -->
<script src="functions.js"></script>
</head>
<body>
<div id="output"> </div>
<div id="output2"> </div>
</body>
</html>
Try removing the ship parameter from the document.write and replacing the statement with this:
document.write("cannon ship sails off to " + number + " degrees");
Then, you should be able to get your desired output.
*p.s.: if you're doing this on a text editor and trying to run this on a browser, you can consider changing the tag to this: .
I hope this helps!
don't give them the same variable to output .. alert (ship) then document.write (ship+.....).
Try this instead
function alertShip (ship, number) {
alert (ship);
document.write ("Cannon ship sails off to " + number + "degrees");

Basic HTML Function Call with buttons

I'm trying to learn basic HTML and Javascript, and am not sure what is wrong with this code. It is probably a very simple error and I'm sorry if it is. When I try clicking the buttons, Chrome says in the console that "correct" and "incorrect" are not defined, but I have checked the syntax for the functions and I can't see what is wrong. Thanks for your help :)
<!DOCTYPE html>
<html>
<head>
<title>Question 1</title>
</head>
<body>
<p>Q1: What is the height of the Eiffel Tower?</p>
<br>
<script>
function incorrect()
{
document.getElementById("feedback").innerHTML =
"incorrect!
<br>
Next Question";
}
function correct()
{
document.getElementById("feedback").innerHTML =
"Correct!
<br>
Next Question";
}
</script>
<button onclick="incorrect()">767m</buttton>
<br>
<button onclick="incorrect()">442m</button>
<br>
<button onclick="correct()">324m</button>
<br>
<button onclick="incorrect()">278m</button>
<p id="feedback"></p>
</body>
You have confusing ""(double quotes) in the innerHTML strings. Try this:
instead of "q2.htm" use 'q2.htm'
<script>
function incorrect()
{
document.getElementById("feedback").innerHTML =
"incorrect!<br><a href='q2.htm'>Next Question</a>";
}
function correct()
{
document.getElementById("feedback").innerHTML =
"Correct!<br><a href='q2.htm'>Next Question</a>";
}
</script>
If you look at the console log in Chrome (press F12 to enter Developer Tools where you can see the log), you will see an error message “Unexpected token ILLEGAL”. The reason is that you have line breaks inside a JavaScript string, which is not permitted, so the function definitions fail in parsing. Moreover, you are using quotes inside a quoted string, which isn’t permitted either. Use single quotes (') as inner quotes or (in this case) just omit them, e.g.
function incorrect()
{
document.getElementById("feedback").innerHTML =
"incorrect!<br><a href=q2.htm>Next Question</a>";
}
This works:
<script>
function incorrect()
{
document.getElementById("feedback").innerHTML =
"incorrect!<br><a href='q2.htm'>Next Question</a>";
}
function correct()
{
document.getElementById("feedback").innerHTML =
"Correct!<br><a href='q2.htm'>Next Question</a>";
}
</script>
You have to put them on the same line or use concatenation.

Categories