Repel ifElse statement - javascript

I consider myself a novice on Javascript language, and i have a problem with my code. I am trying to simulate a simple if else statement, that relates to if your repel runs out, the program will ask you to use another one. However when i try to run it on Chrome, nothing is printed out on the screen.
Here is my code:
<html>
<head>
</head>
<body>
<script type = "javascript/text">
var repelsInBag = 10;
if (repelsInBag > 1){
document.write("Would you like to use another repel?");
}else{
document.write("Repel effect has ran out");
}
</script>
</body>
</html>
Thanks in advance !
Stephen

The problem is with your script tag:
<script type = "javascript/text">
Is incorrect and needs to be flipped around:
<script type = "text/javascript">
Or just remove it altogether, it's not needed.
<script>

You should create a page that will validate as HTML5 and remove the type attribute entirely.
http://validator.w3.org/
From https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script
If this (type) attribute is absent, the script is treated as JavaScript.

Related

Is it possible to use javascript to modify a script element?

Is there a way to use javascript to modify a script element?
Like for example:
HTML:
<script id="something" src="/js/file.js"></script>
Javascript:
var something = document.getElementById("something");
something.src = "/js/anotherfile.js"
Is it possible? Because I have a bit of code that works like that and it sort of doesn't work
To be specific, here's the code:
<!DOCTYPE html>
<html>
<head>
<title>MyohTheGod's Website</title>
<link rel="icon" type="image/x-icon" href="/supercorn.gif" defer>
</link>
<link id="css" href="/css/dark.css" rel="stylesheet" type="text/css">
</link>
<script src="/js/particles.js" defer></script>
<script src="/js/header.js"></script>
<script src="/js/theme.js"></script>
<script>window.alert("Welcome to the Home of MyohTheGod. You can play games, check out our web proxies, and more. Also, please do check out the About page. Press OK to continue...");</script>
</head>
<body>
-snip-
</body>
<script id="foot" src="/js/footer.js"></script>
</html>
<script>
-snip-
</script>
var css = document.getElementById("css");
var foot = document.getElementById("foot");
function toggleDLmode(m) {
-snip-
if (dlmodebool) {
css.href = "/css/dark.css"
foot.src="/js/dark-footer.js"
} else {
css.href = "/css/index.css"
foot.src="/js/footer.js"
}
}
-snip-
It is working, do you inspect it? It does changed, but maybe you're thinking, "hm why this /js/anotherfile.js is not downloaded?". Well because of the script tag is already rendered and already downloaded, so you can't do that. What you can do though add NEW script tag.
Maybe this will help How to dynamically change the script src?. This links would explain more why your code "does not work".
There certainly is. You can use document.scripts which returns an collection that you can iterate through like an array. You can change the code using the innerHTML property very much like a normal element. See here https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection
Edited to add: If you've got a html page with multiple script tags, the document.script collection has each script in the order they appear. The code below will log out the source (src tag) or the actual javascript for each script element.
You can also 'write' javascript by setting the innerHTML property.
IMHO it's a bit of a solution that's looking for a problem but at least it gives you access to the number of scripts you have.
[...document.scripts].forEach(script => {
if (script.src != '') {
console.log("Script source:" + script.src);
} else {
console.log(script.innerHTML);
}
});

Function tag seems to not work?

I am trying to write a simple "Choose your own adventure" style game in Javascript format, mainly because its simple to write, but I have run into a problem. I am trying to get the javascript to run on page load, but it wont start. I am just left with a blank page.
Here is the code:
<!doctype html>
<body>
<title>Dungeons and Dwarves</title>
<script type="text/javascript>
function begin() {
alert("Welcome to Dungeons and Dwarves! A free 'Choose Your Own Adventure' game. In this adventure, you will be faced with many decisions, some of which could potentially lead to your death. If you are willing to put your life on the line, and leap forward into a new world and explore the unexplored, press OK to begin.")
var myAge = prompt("How old are you, adventurer?")
if (myAge < 18)
{
alert("Oh! They start younger and younger every year! You'll be careful out there, wont you?")
}
else
{
alert("I see you have had some experience with adventures! I wish you the best of luck, not that you will need it!")
}
}
</script>
<body onload='javascript:begin()'>
</body>
Im not sure what I have done wrong here, but I think the function tag isn't working properly. Just the way it looks in Notepad++, that might just be me. Could anyone give me assistance?
I apologise if I have formatted this wrong.
The browser thinks your JavaScript is not JavaScript (but some other, unknown kind of script):
<script type="text/javascript>
You omitted the second " from the type attribute.
As of HTML 5, the type attribute may be omited if you are using JavaScript, so just write:
<script>
Additionally, you have two <body> start tags. Only one of them has an onload attribute. Browsers may parse the first one and then ignore the second one.
These (among some other errors) would have been picked up by a validator.
You forgot " at:
<script type="text/javascript>
Make sure you put the " in front of >:
<script type="text/javascript">
And as Quentin notes, you have two body tags.
type="text/javascript" //add a " at the end
Correction
<script type="text/javascript">
Try this:
<html>
<head>
<title>Dungeons and Dwarves</title>
<script>
function begin()
{
alert("Welcome to Dungeons and Dwarves! A free 'Choose Your Own Adventure' game. In this adventure, you will be faced with many decisions, some of which could potentially lead to your death. If you are willing to put your life on the line, and leap forward into a new world and explore the unexplored, press OK to begin.")
var myAge = prompt("How old are you, adventurer?")
if (myAge < 18)
{
alert("Oh! They start younger and younger every year! You'll be careful out there, wont you?")
}
else
{
alert("I see you have had some experience with adventures! I wish you the best of luck, not that you will need it!")
}
}
</script>
</head>
<body onload='javascript:begin()'></body>
</html>
You are missing " at:
<script type="text/javascript>
You have misplaces the <body> tag at line number 2: remove body tag from there.
You need to include your <title> tag in <head> tag.
<script type="text/javascript>
would be
<script type="text/javascript">
and <body onload='javascript:begin()'></body>
would be
<body onload='javascript:begin();'></body>
all your alerts need to end like
var myAge = prompt("How old are you, adventurer?");

Jscript not printing to element

I have no idea why this isn't working. I mean as far as I know It should print my array in alphabetical order to the div "output"
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title> Lexicographic ordering </title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
var words = [];
var input = prompt("Please enter a word or type end to stop prompts");
while (input != 'end') {
words.push(input);
input = prompt("Please enter a word or type end to stop prompts");
}
words.sort();
getElementById('#output').innerHTML= words.join();
</script>
</head>
<body>
<header>Lexicographic Ordering </header>
<hr>
<div class ="page-wrapper">
h1> Lexicographic Ordering </h1>
<div id="output"></div>
</div>
</body>
</html>
There are two small bugs in your code, and they're both in this line:
getElementById('#output').innerHTML= words.join();
getElementById is not a part of the window, it's a part of the document object, so you must reference it properly. Also, that method takes an ID, not a selector, so you don't need the # in front of it.
document.getElementById('output').innerHTML= words.join();
That should do what you want! Alternatively, since I notice you have jQuery included, you could do $('#output').innerHTML = ... to achieve the same effects.
You may also try to move the <script> block at the end, just before closing of the </body>. Anywhere after the <div id="output"></div>.
JavaScript on some browsers fails when they have to reference some elements which has not been parsed by their HTML parser when the script is executing or trying to reference them.
Also, you don't use # with getElementById(...);. # is used with Jquery. This is pure JavaScript. Make it getElementById('output').whatever...;
Edit:
Another option suggested by Patrick Evans is to move the JavaScript Code in an onload() event handler method to execute the code. This ensures that the HTML is fully loaded in the DOM before we try to manipulate it.

Javascript Error in Chrome: Me, something I'm missing or a bug in Chrome?

I doubt the last option, but probably one of the first two. Can anybody tell me which?
I'm getting the error in the screen shot.
<html>
<head>
<script type="text/javascript">
var html = "<script></script>";
</script>
</head>
<body>
</body>
</html>
This is a problem in every browser, the script block is terminated at the first string </script>, so if that string appears in your code anywhere it will cause a premature termination of the script block.
If you want to have this as a variable in JS, use:
var html = unescape("%3Cscript%3E%3C/script%3E");
You can also use \ to render that character correctly:
var html = "<script><\/script>";
That's no bug. It's the correct behaviour for a script tag, what you're doing is the equivalent of not escaping a quote in a string.
var string = 'My mother's awesome.';
An easy way to fix your issue is to break apart the </script> tag, like so:
var html = "<script></"+"script>";

how do I automatically execute javascript?

how do I automatically execute javascript?
I know of <body onLoad="">, but I just thought maybe there is another way to do it?
html:
<html><head></head><body><div id="test"></div></body></html>
javascript:
<script>(function(){var text = document.getElementById('test').innerHTML;var newtext = text.replace('', '');return newtext;})();</script>
I wanna get the text within "test", replace certain parts, and then output it to the browser.
Any ideas on how to do it? I'd appreciate any help. Thanks.
If you don't want to use <body onload> which is good choice in terms of obtrusive javascript, you can separate that and put you code like this:
window.onload = function(){
// your code here
};
Alternative:
Place your javascript code at the bottom of the page.
Place the script at the bottom of the page, outside the closing body tag..
It's REALLY easy! If you have a script in your "head" block, with no function id, it will run automatically as soon as the web page loads. For example:
<head>
<meta charset="UTF-8">
<title>Redirection to www.mywebsite.org</title>
<!-- This script initiates an automatic web page redirection, as the page is loaded -->
<script type="text/javascript">
window.location = "http://www.mywebsite.com/"
</script>
</head>
If you don't want to use jQuery, use native window.onload method:
<script type="text/javascript">
function ReplaceText() {
document.getElementById('test').innerHTML = document.getElementById('test').innerHTML.replace(/abc/g, "def");
}
window.onload = ReplaceText;
</script>
Used on the code:
<div id="test">abc abc</div>
Will give this output:
def def
A quick way, if you just want to debug, would be move what you want to execute outside of a function.
<script type="text/javascript">
var text = document.getElementById('test').innerHTML;
var newtext = text.replace('', '');
alert(newtext);
</script>
NB. I'm not sure what you hope to achieve with text.replace('', '') ?

Categories