I'm trying to swap two HTML paragraphs with a JavaScript button. The code seems to all check out, so I can't seem to figure out why it's not working!
HTML:
<p id="p1"> Donald Drumpf paced and loomed behind Hillary Clinton at times during Sunday night's second presidential debate -- a decision possibly driven by stress during the intensely bitter event, according to body language expert Janine Driver. </p>
<p id="p2"> "He's decreasing stress by doing all that movement," Driver said of Drumpf's behavior on CNN's "New Day" on Monday. </p>
<button onclick="swapT()"> Swap </button>
JS:
function swapT()
{
var obj1 = document.getElementById('p1');
var obj2 = document.getElementById('p2');
var temp = obj1.innerHTML;
obj1.innerHTML = obj2.innerHTML;
obj2.innerHTML = temp;
}
I get the error:
Uncaught ReferenceError: swapT is not defined
What's going wrong?
From the error message you got, it seems that your swapT() function is bound to an inline handler before it's defined. If you're going to call the function from an inline handler, first define the function within the <head> of your document:
<html>
<head>
<script>
function swapT() {
var obj1 = document.getElementById('p1');
var obj2 = document.getElementById('p2');
var temp = obj1.innerHTML;
obj1.innerHTML = obj2.innerHTML;
obj2.innerHTML = temp;
}
</script>
</head>
<body>
<p id="p1">Donald Drumpf paced and loomed behind Hillary Clinton at times during Sunday night's second presidential debate -- a decision possibly driven by stress during the intensely bitter event, according to body language expert Janine Driver.</p>
<p id="p2">"He's decreasing stress by doing all that movement," Driver said of Drumpf's behavior on CNN's "New Day" on Monday.</p>
<button onclick="swapT()">Swap</button>
</body>
</html>
My suggestion is to bind the listener when you define your function, instead:
<html>
<body>
<p id="p1">Donald Drumpf paced and loomed behind Hillary Clinton at times during Sunday night's second presidential debate -- a decision possibly driven by stress during the intensely bitter event, according to body language expert Janine Driver.</p>
<p id="p2">"He's decreasing stress by doing all that movement," Driver said of Drumpf's behavior on CNN's "New Day" on Monday.</p>
<button id="swap">Swap</button>
<script>
function swapT() {
var obj1 = document.getElementById('p1');
var obj2 = document.getElementById('p2');
var temp = obj1.innerHTML;
obj1.innerHTML = obj2.innerHTML;
obj2.innerHTML = temp;
}
document.getElementById('swap').addEventListener('click', swapT);
</script>
</body>
</html>
Here are some relevant links for further reference:
Why put JavaScript in the footer of a page?
Where to place Javascript in a HTML file?
Should I write script in the body or the head of the html?
Does javascript have to be in the head tags?
Related
I have this pesky problem with my code that I think is a runtime error because it shows up when I run the program and actually stops it. I used an error console to show me where the error is, but I can't make sense of it. If anybody can point me in the right directions without giving me the answer I'd appreciate it. Here is the code:
<script type="text/javascript">
<!-- HIDE FROM INCOMPATIBLE BROWSERS
function changeQuote() {
quotes = new Array;
quotes[0] = "Laughter is the best medicine.";
quotes[1] = "Never look a gift horse in the mouth.";
quotes[2] = "One good turn deserves another.";
quotes[3] = "The early bird catches the worm.";
quotes[4] = "Two is company, three is a crowd.";
var newQuote = quotes[Math.round(Math.random()+quotes.length)];
document.quoteform.quote.value = newQuote;
}
var tick = setInterval("changeQuote()");
// STOP HIDING FROM INCOMPATIBLE BROWSERS -->
</script>
</head>
<body>
<form action=""name="">
<input type="text" size="50" name="quote" /><br />
</form>
</body>
</html>
I also have two image of the error console message:
I want to display a quote depending on what day it is. Example: Quote of the day is Tuesday March 10 : "Quote here". I have the alert displaying the date, day and time but I want it to display on the page in the h2 header. So after it loads the alert I want the quote, depending on which day it is, to be written on the page.
Thank you.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Class 6 array assignment starter file</title>
<script>
var venomArray = new Array();
venomArray[0] = " Ability is nothing without opportunity - Napoleon Bonaparte";
venomArray[1] = " Nothing happens unless first we dream - Carl Sandburg";
venomArray[2] = "quote3";
var today = new Date();
//var text = document.getElementById('expression').firstChild.nodeValue = venomArray[i];
// if I uncomment this, It displays the index 1 for tuesday. How do I get it to write to the page? Would I use firstChildnodeValue?
alert("The quote of the day for: "+today+ venomArray[today.getDay()-1]);
</script>
</head>
<body>
<section>
<h2 style = "color:red" id='expression'> Quote of the Day : </h2>
<h3> All of the Quotes are listed below:</h3>
<p>
Nothing happens unless first we dream - Carl Sandburg<br>
Believe you can and you're halfway there - Theodore Roosevelt<br>
A place for everything, everything in its place - Benjamin Franklin<br>
Don't let the fear of striking out hold you back - Babe Ruth<br>
We can't help everyone, but everyone can help someone - Ronald Reagan<br>
With self-discipline most anything is possible - Theodore Roosevelt
</p>
</section>
</body>
</html>
You need to set the innerHTML property of the element
document.getElementById("expression").innerHTML = ' Quote of the Day : ' +
today+venomArray[today.getDay()-1];
Check this.. This may help your question
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Class 6 array assignment starter file</title>
</head>
<body>
<section>
<h2 style = "color:red" id='expression'> Quote of the Day : <span id="quote"></span> </h2>
<h3> All of the Quotes are listed below:</h3>
<p>
Nothing happens unless first we dream - Carl Sandburg<br>
Believe you can and you're halfway there - Theodore Roosevelt<br>
A place for everything, everything in its place - Benjamin Franklin<br>
Don't let the fear of striking out hold you back - Babe Ruth<br>
We can't help everyone, but everyone can help someone - Ronald Reagan<br>
With self-discipline most anything is possible - Theodore Roosevelt
</p>
</section>
<script type="text/javascript">
var venomArray = new Array();
venomArray[0] = " Ability is nothing without opportunity - Napoleon Bonaparte";
venomArray[1] = " Nothing happens unless first we dream - Carl Sandburg";
venomArray[2] = "quote2";
venomArray[3] = "quote3";
venomArray[4] = "quote4";
var t = new Date();
//alert(t.getDay());
//var text = document.getElementById('expression').firstChild.nodeValue = venomArray[i];
// if I uncomment this, It displays the index 1 for tuesday. How do I get it to write to the page? Would I use firstChildnodeValue?
// alert("The quote of the day for: "+today+ venomArray[today.getDay()-1]);
document.getElementById("quote").innerHTML = venomArray[t.getDay()-1];
</script>
</body>
</html>
You can use innerHtml property of an element to update the content, something like:
document.getElementById('expression').innerHTML = "Quote";
This is an implementation in pure JavaScript. You usually use some kind of templating now a days to display variable text in a web page.
Use This :-
<script>
var venomArray = new Array();
venomArray[0] = " Ability is nothing without opportunity - Napoleon Bonaparte";
venomArray[1] = " Nothing happens unless first we dream - Carl Sandburg";
venomArray[2] = "quote3";
var today = new Date();
//var text = document.getElementById('expression').firstChild.nodeValue = venomArray[i];
// if I uncomment this, It displays the index 1 for tuesday. How do I get it to write to the page? Would I use firstChildnodeValue?
//alert("The quote of the day for: "+today+ venomArray[today.getDay()-1]);
/*Add this Code*/
var display_date = "today"+ venomArray[today.getDay()-1];
$('h2').html(display_date );
</script>
I'm new to the forum and new to html. I've tried may of the answers in the forums but nothing is seaming to work. While like I said i'm new I've tried looking through w3shools and having a hard time figuring this out.
what I want is to when I click the button, I would like is for it to look at the <h1><h1> and are you = x, if you are = to x then please change to work. if you are = to work please change to x.
<!DOCTYPE html>
<html>
<Head>
<title>Heather I Love You!</title>
</head>
<body style= background-color:#A8A8A8>
<!========This is the header===========>
<div id="header" style= "background-color:#00FF33;" >
<h1><p id="hheader">Heather this is a series of Pitures, Videos, and Poems to
show you the love that I have for you!"</p></h1></div>
<!=============The side bar that will allow a list of where she Wants to
go==========>
<div id="Menu" Style="background-
color:#660033;height:300px;width:125px;float:left;">
<Talbe>
<b><h3{color:white}>Categories</h3></b><br>
<button type="button" onclick="ChangeHead()">click here!</button><br>
<!--Functions-->
<Script>
function ChangeHead()
{
var g=document.getElementById("hheader")
x="Heather this is a series of Pitures, Videos, and Poems to show you the
love that I have for you!"
work="Here are some pictures of us and the boys"
if (document.getElementById("hheader").innertext == x)
{
document.getElementById("hheader").innerHTML= =work;
}
else
{
document.getElementById("hheader").innerHTML== x
}
}
</Script>
</body>
</Html>
Assuming that you have an element with the id 'hheader':
<div id='hheader'>Heather this is a series of Pitures, Videos, and Poems to show you the love that I have for you!</div>
The following script should work:
<script>
function ChangeHead() {
var g = document.getElementById("hheader");
var x = "Heather this is a series of Pitures, Videos, and Poems to show you the love that I have for you!";
var work = "Here are some pictures of us and the boys";
if (document.getElementById("hheader").innerText == x) {
document.getElementById("hheader").innerHTML = work;
} else {
document.getElementById("hheader").innerHTML = x;
}
};
ChangeHead();
</script>
So that the script will change the text of the 'hheader' div to the value of the work variable
I've found a few syntax errors in your code and I corrected them accordingly.
Here you can see a working demo:
http://jsfiddle.net/robertp/LvcCe/
1- You have an unterminated string literal at line 34 :
x="Heather this is a series of Pitures, Videos, and Poems to show you the
love that I have for you!"
For your script to work, you have to replace the line breaks in your string with "\n" in between "to " and "show". Also, take out the line breaks.
2- innerText does not work with Firefox, just use innerHTML all the time instead at line 38 :
if (document.getElementById("hheader").innertext == x)
3- = = makes no sense if you want to assign a value. Use only 1 equal sign when you assign a value to a variable.
Use two only when you are making an if statement!
Watch it at :
line 40 :
document.getElementById("hheader").innerHTML= =work;
and at line 44 :
document.getElementById("hheader").innerHTML== x
4- Line 13 has an extra quote at the end that you want to take out :
show you the love that I have for you!"
If you replace all these mistakes, your script works.
Please look at a modified version of your script that works here:
http://lespointscom.com/a/misc/stackoverflow/2014_01_29/new.html
Or just copy paste this html as is:
<!DOCTYPE html>
<html>
<Head>
<title>Heather I Love You!</title>
</head>
<body style= background-color:#A8A8A8>
<!========This is the header===========>
<div id="header" style= "background-color:#00FF33;" >
<h1><p id="hheader">Heather this is a series of Pitures, Videos, and Poems to
show you the love that I have for you!</p></h1></div>
<!=============The side bar that will allow a list of where she Wants to
go==========>
<div id="Menu" Style="background-
color:#660033;height:300px;width:125px;float:left;">
<Talbe>
<b><h3{color:white}>Categories</h3></b><br>
<button type="button" onclick="ChangeHead()">click here!</button><br>
<!--Functions-->
<Script>
function ChangeHead()
{
var g=document.getElementById("hheader")
x="Heather this is a series of Pitures, Videos, and Poems to \n\nshow you the love that I have for you!"
work="Here are some pictures of us and the boys"
if (document.getElementById("hheader").innerHTML == x)
{
document.getElementById("hheader").innerHTML=work;
}
else
{
document.getElementById("hheader").innerHTML= x
}
}
</Script>
</body>
</Html>
I'm learning a bit HMTL5 to prepare to the 70-480 exam. I'm trying to do some javascript code. It looks something like this:
function inchestometers(inches) {
if (inches < 0)
return -1;
else {
var meters = inches / 39.37;
return meters;
}
}
var inches = 12;
var meters = inchestometers(inches);
document.write("the value in meters is " + meters);
var hello = document.getElementById("hello");
hello.firstChild.nodeValue = "Hello World";
and I have such html code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Htnl 5 test</title>
<script src="script/test.js"></script>
</head>
<body>
<p id="hello">Hello</p>
</body>
</html>
In my VS 2012 i have used the Asp.net Empty Web application project and added the Js file and also the html file. The problem is that The function runs properly without any exeptions. This function is taken from here: http://msdn.microsoft.com/en-us/library/cte3c772(v=vs.94).aspx
But whem I'm trying to run the code where I'm getting the document element it' crashint with the error like in the subject. What I've investigated is that the hello gets the null value. I've also tried the code thaken from here:
http://msdn.microsoft.com/en-us/library/yfc4b32c(v=vs.94).aspx - the example with the div. I have the same effect.
What is wrong? I know that there were simmilar subjects but I can't seem to find one matching to mine. Thank you kindly for your help.
Regards
Rafal
you are getting a problem because your javascript code is running before the element
<p id="hello">
is defined.
the simplest solution is to include your script at the end of the body section instead of in the head section but this would cause the document.write call to occur after the rest of the content.
another solution would be to place the code inside two functions like this
function do_conversion() {
var inches = 12;
var meters = inchestometers(inches);
document.write("the value in meters is " + meters);
}
function say_hello() {
var hello = document.getElementById("hello");
hello.firstChild.nodeValue = "Hello World";
}
then change the body section like this
<body onload='say_hello()'>
<script>
do_conversion();
</script>
<p id="hello">Hello</p>
</body>
I am somewhat new to programming and have been working through the Head First HTML5 Programming book. On page 65, they have an exercise that helps you insert a javascript function into the HTML head that will change the text located at bullet points in the body of the page. When I open the HTML file in the browser, the page loads, but the content from the Javascript function isn't added to the bullet points. I have determined it's because the script is running before the DOM is complete because when I change the book's code to <body onload="addSongs()">, the page loads correctly.
Here's the code from the book (that doesn't seem to work):
<!doctype html>
<html>
<head>
<title>My Playlist</title>
<meta charset="utf-8">
<script>
function addSongs() {
var song1 = document.getElementById("song1");
var song2 = document.getElementById("song2");
var song3 = document.getElementById("song3");
song1.innerHTML = "Blue Suede Strings, by Elvis Pagely";
song2.innerHTML = "Great Objects on Fire, by Jerry JSON Lewis";
song3.innerHTML = "I Code the Line, by Johnny Javascript";
window.onload = addSongs;
}
</script>
</head>
<body>
<h1> My Awesome Playlist! </h1>
<ul id="playlist">
<li id="song1"></li>
<li id="song2"></li>
<li id="song3"></li>
</ul>
</body>
</html>
I have read through different posts and many people suggested using JQuery (which I'm hoping to learn in the next few months), but I'm just curious as to whether the window.onload = function; has been deprecated since this book was published or if I am making a mistake somewhere. A lot of the exercises in this book use this principle and I can't move forward until I figure this out. Any suggestions or different approaches are appreciated.
Thanks!
You need to move the line:
window.onload = addSongs;
To outside the function.
"I have determined it's because the script is running before the DOM is complete"
The script is running, but all it does is declare a function, it doesn't ever call it (because the aforementioned line is in the wrong place).
it's just a typo.
you put window.onload = addSong; in the definition of the function addSong. so window.onload will never be set, as addSong will never be called.
function addSongs() {
var song1 = document.getElementById("song1");
var song2 = document.getElementById("song2");
var song3 = document.getElementById("song3");
song1.innerHTML = "Blue Suede Strings, by Elvis Pagely";
song2.innerHTML = "Great Objects on Fire, by Jerry JSON Lewis";
song3.innerHTML = "I Code the Line, by Johnny Javascript";
}
window.onload = addSongs; //move this line out of function definition.
You need to move window.onload = addSongs; after define the function, not before it.
like this:
<!doctype html>
<html>
<head>
<title>My Playlist</title>
<meta charset="utf-8">
<script>
function addSongs() {
var song1 = document.getElementById("song1");
var song2 = document.getElementById("song2");
var song3 = document.getElementById("song3");
song1.innerHTML = "Blue Suede Strings, by Elvis Pagely";
song2.innerHTML = "Great Objects on Fire, by Jerry JSON Lewis";
song3.innerHTML = "I Code the Line, by Johnny Javascript";
}
window.onload = addSongs;
</script>
</head>
<body>
<h1> My Awesome Playlist! </h1>
<ul id="playlist">
<li id="song1"></li>
<li id="song2"></li>
<li id="song3"></li>
</ul>
</body>
</html>