6 javascript tasks assigned to me by my lecturer - javascript

I am a complete beginner to javascript. I am also new to this website. I am asking for help to complete an assignment. I have been trying for more than 4 hours by looking at lecture material and online for a solution. It is causing me a lot of unnecessary stress. Before javascript we only used CSS and Html. I was given 6 javascript tasks to manipulate the html file (taskc.html) already given to me.
The tasks are as follows
Make a statement to change contents of h1 from "Welcome" to "Text"
2nd statement should make an new alert window when the page loads that delivers a message explaining what the page is about
3rd statement should change the title to "text"
4th statement should log the contents (innerHTML) of the first paragraph element in the console.
5th statement should hide the contents of the second paragraph when the page loads
6th statement should change the contents of the header to have a new colour of your choice
Here is that html.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Task C - The Document Object Mode</title>
</head>
<body>
<h1 id="header">Welcome</h1>
<p id="first">This site uses JavaScript</p>
<p id="second">Javascript is very useful</p>
</body>
</html>
Because the actual coding im meant to add is meant to be in the .js file I was given. so I figured I had to link the js file in the html file so I added
<script type="text/javascript" src="taskc.js"></script>
With that out of the way I went to the lecture notes and I thought I would simply need to modify some of the code given to me there like
document.getElementById('demo').innerHTML = 'Hello World!';
When I put this code in brackets I got the error (document is not defined)
I modified it to match the requirements for task 1
here it is
document.getElementById('header').innerHTML = 'text';
I was confused because I didn't know what this error meant and of course Errors and how to fix them are never explained so I had to lookup how to resolve the error.
I found that to fix it I have to declare it as a variable so I ended up doing this.
var document = 'taskc.html';
When I did this for document, alert and console all the errors went away, but when I did a live preview only statement 1 was working
If anyone could help me fix this I would really appreciate because I don't understand enough javascript to be able to complete this in a reasonable amount of time.

So first: Please use Javascript functions to keep your code tidy and clean.
Example:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Task C - The Document Object Mode</title>
</head>
<body>
<h1 id="header">Welcome</h1>
<p id="first">This site uses JavaScript</p>
<p id="second">Javascript is very useful</p>
<script type="text/javascript" src="taskc.js">test();</script>
</body>
</html>
function test(){
alert("This is a test!");
}
Always implement scripts that are document referenced at the bottom of your html.
If you use JQuery you can use following code to check document is loaded:
$(document).ready(function(){
//foo bar
});

Related

Wordpress: how to use javascript variables into html body

I'm really new in Wordpress, Javascript and HTML so I know this question is really basic, but I wasn't able to find it solved anywhere.
I want to create some variables in javascript and then display them in my page which is created in Wordpress.
Reading other posts I've found I need to insert a javascript code that at the end stores my variable this way (dummy version):
<script type="javascript">
document.getElementById('test').innerHTML = 'hello';
</script>
And then on the text block I want to display my variable to be displayed I should add this code:
<body>
<p id="test"></p>
</body>
However I've tried adding the javascript in the header (Tatsu header) and also tried adding it in the text block (HTML version) in different combinations and it never worked. Tried adding the script block before and after the body block, and also tried having it inside, before and after the display line.
If I try the following it works:
<body>
<p>hello</p>
</body>
So I guess my problem is that I'm not setting the variable properly.
Can anyone help? Apologies if this is already solved somewhere, spent some hours and wasn't able to find it.
Thank you in advance.
Your problem is the type of which you're using here:
<script type="javascript">
I noticed this whilst constructing an example of this problem.
javascript is not a correct mime type.
It should be text/javascript as per https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
Please note this is not a complete list. Such as application/javascript also being valid. Please also see https://www.iana.org/assignments/media-types/media-types.xhtml
Working example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<p id="test">
This shouldn't show up
</p>
<script type="text/javascript">
console.log("####### JAVASCRIPT IS RUNNING ######")
document.getElementById('test').innerHTML = 'hello';
</script>
</body>
</html>

what does "JavaScript sanitization doesn't save you from innerHTML" mean?

I'm learning xss prevention through this ppt:http://stash.github.io/empirejs-2014/#/2/23, and I have a question on this page.
It says "JavaScript sanitization doesn't save you from innerHTML", and I tried a simple test like this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
<div id="test"></div>
<script>
var userName = "Jeremy\x3Cscript\x3Ealert('boom')\x3C/script\x3E";
document.getElementById('test').innerHTML = "<span>"+userName+"</span>";
</script>
</body>
</html>
when I opened this html on my browser(chrome), I only saw the name "Jeremy",by using F12, I saw
<div id="test"><span>Jeremy<script>alert('boom')</script></span></div>
Although the script had been added to html, the alert box didn't come out.
"JavaScript sanitization doesn't save you from innerHTML" I think this means that the word "boom" should be alerted. Am I right?
According to MDN, innerHTML prevents <script> elements from executing directly1, which means your test should not alert anything. However, it does not prevent event handlers from firing later on, which makes the following possible:
var name = "\x3Cimg src=x onerror=alert(1)\x3E";
document.getElementById('test').innerHTML = name; // shows the alert
<div id="test"></div>
(script adapted from the example in the article, with escape sequences although I'm not sure those are relevant outside of <script> elements)
Since <script> elements never execute when inserted via innerHTML, it's not clear to me what that slide is trying to convey with that example.
1 This is actually specified in HTML5. MDN links to a 2008 draft; in the current W3C Recommendation, it's located near the end of section 4.11.1, just before section 4.11.1.1 begins:
Note: When inserted using the document.write() method, script elements execute (typically synchronously), but when inserted using innerHTML and outerHTML attributes, they do not execute at all.

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.

where to embed javascript section in a html page [duplicate]

This question already has answers here:
when and where to put javascript in html
(7 answers)
Closed 9 years ago.
the thing is i'm unable to figure out where to embed javascript in html page whether in head section or body section.
example 1:
<html>
<head>
<title>events</title>
<script>
document.getElementById("b").onclick=function(){displayDate()};
function displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script>
</head>
<body>
<p id="demo"></p>
<button id="b">new</button>
</body>
</html>
in the above example I placed script tags in head section but it is not working.
example: 2
<html>
<head>
<title>events</title>
<script>
function upper()
{
var x=document.getElementById("t");
x.value=x.value.toUpperCase();
}
</script>
</head>
<body >
enter some text:<input type="text" id="t" onChange="upper()"/>
</body>
</html>
in the second example I placed the javascript in head section it is working properly.first example demonstrates that on clicking a button date will be displayed in the second example in a text box when data is entered and if we come out of the box the letters in the box will we converted to uppercase.
To have it more readable I prefer to always place JavaScript in the head section. If you need to access elements from there, use the window.onload event:
<head>
<title>events</title>
<script type="text/javascript">
window.onload = function() {
document.getElementById("b").onclick = function() {
displayDate();
};
};
function displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script>
</head>
This would work just fine.
Your second example worked because you just defined a function, you didn't try to access any element.
You can put it in the head. The problem is that your examples are not the same. The first one doesn't work because the current date is retrieved by calling Date(), when it should be new Data().getDate(). The second example works because the code is valid.
The problem you're running into is that you're trying to reference an element before it is loaded into the DOM.
When you're putting the script in the HEAD tag, the dom hasn't been loaded yet and the document.getElementById won't find what you're looking for.
You have a few different options to deal with this. You can put the script at the end of the page, which will work for your small example here.
Probably a better option is to take a look at learning/using jquery or another js utility. Jquery makes it easy to solve this issue by giving you a "ready" event. This ready event will be triggered when the DOM is fully loaded. So:
$(document).ready(
function()
{
$("#demo").html((new Date()).toString());
});
Is all you really need. With this approach, it doesn't matter where the script it on the page.

Stylesheet ignored when using body onload and document.write

I am messing around with JavaScript experimenting to get a feel for it and have already hit a problem. Here is my html code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script type="text/javascript" src="testing.js"></script>
</head>
<body onload="writeLine()">
</body>
</html>
Here is the JavaScript testing.js:
function writeLine()
{
document.write("Hello World!")
}
Here is the style sheet styles.css:
html, body {
background-color: red;
}
So a very simple example, but I may have chose an awkward example, using on-load in a body tag. So the code above loads and runs the function, but the style sheet does nothing, unless I remove the script tags in the head. I have tried putting the script tags everywhere else, but nothing works. I have researched on-line how to properly link to JavaScript files, and have no found no clear solution, can anyone point out my error?
I have used JavaScript before, but I want a clear understanding from the beginning before I use it any longer
You cannot use document.write after the document is closed (which it will be when onload fires) without destroying the existing document (including links to stylesheets).
Instead, use DOM manipulation, which is covered by chapters 8 and 9 of the W3C JavaScript Core Skills.
Your problem is with the document.write() called in a wrong moment*. This method prints given text at current place in the page as was intended to work while the page still loads. Because you are calling it when the whole page was loaded, the results are unexpected (undefined?)
Instead you should manipulate the dom tree directly:
function writeLine() {
var text = document.createTextNode("Hello World!");
document.body.appendChild(text);
}
Actually in Opera browser I see red background for few milliseconds and then it goes back to white. Try commenting out document.write() - the background is as expected. Moreover you should include <script> tag at the end of body, but this won't solve your problem.
* to be honest, there is no good moment for calling document.write(), avoid it
In your particular example it doesn't matter where the script tag is added as the document.write command executes after the content is rendered, overwriting the existing content.
If you add an alert before overwriting the content you can see your page is red before it gets overwritten with Hello World.

Categories