JavaScript : Output now shown as expected - javascript

How to to show "New Way" in h1, and "To do that way" in h2? My Output: "To do that way" in h1 and "The Good Way" in h2 is not expected.
function init() {
var planet = document.getElementById("greenplanet");
planet.innerHTML="New Way";
document.getElementById("hard");
planet.innerHTML="To do that way"
}
window.onload=init;
<h1 id="greenplanet">The Great Planet</h1>
<h2 id="hard">The Good way</h2>

you are adding 'New Way' in #greenplanet and then replacing it with 'To do that way', you need to add it to #hard. you can do something like this:
function init() {
var planet = document.getElementById("greenplanet");
planet.innerHTML="New Way";;
document.getElementById("hard").innerHTML="To do that way"
}
window.onload=init;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<h1 id="greenplanet">The Great Planet</h1>
<h2 id="hard">The Good way</h2>
</body>
</html>

You didn't reassign planet var in 3rd line of your function.
BTW you don't inject HTML so change element.innerHTML to element.innerText or element.textContent

// correct your init() as below :
function init() {
var planet = document.getElementById("greenplanet");
planet.innerHTML="New Way";
var planet1 = document.getElementById("hard");
planet1.innerHTML="To do that way"
}

You should reassign new div with "hard" id to planet variable in order to make your code work
function init() {
var planet = document.getElementById("greenplanet");
planet.innerHTML="New Way";
planet = document.getElementById("hard");
planet.innerHTML="To do that way"
}
window.onload=init;
<h1 id="greenplanet">The Great Planet</h1>
<h2 id="hard">The Good way</h2>

Related

How to create a Javascript function that uses parameters and arguments to change the font size and color of an HTML tag?

I created a button that uses function fontColor to activate the id= "main header". I'm trying to get the parameters of function to accept arguments to adjust the font size and color in the id="Main Header". Can I get some help with this? Thanks.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="script.js"></script>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<button type="button" onClick="fontColor(30,"blue");" id="push">Change.</button>
<h1 id="Main Header"> HI</h1>
<p id="this one">Hello World</p>
</body>
</html>
function fontColor(s, c) {
var size = element.style.fontsize(s);
var color = element.style.color(c);
var result = [size, color];
document.getElementById("Main Header").innerHTML = result;
}
Just set the id to a variable, and change it from there. Also, as the other user said, fontSize should be suffixed with px
function fontColor(s, c) {
var changing = document.getElementById("Main Header");
changing.style.fontSize = s;
changing.style.color = c;
}
Camel-case element.style.fontSize
I could be wrong but also I believe element.style.fontSize needs a string so fontColor("30px","blue")
EDIT: element is undefined and there's more errors than I previously thought. I couldn't just tell you how to fix the errors so I just rewrote your function.
A better solution would be:
function fontColor(s, c) {
var element = document.getElementById("MainHeader"); <- should be one word
element.style.fontSize = s;
element.style.color = c;
}

Selecting specific part of an HTML text

I have a function that returns some HTML fragment that I store in a variable called data, with its whole structure. What I want is to extract from it some of those parts.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script id="hello">
</script>
</head>
<body>
</body>
</html>
For example, I want to get the body and save it in a new variable:
var body = data.split("<body")[1].split(">").slice(1).join(">").split("</body>")[0];
Where data is the HTML text as a string that the original function is returning.
Is there any way I could save an specific script, from its ID (in this case with id = hello), and save it in another variable??
Thank you very much
var newVar = $("#hello").html();
Let's suppose you have an HTML string in a variable, for example
var foo = '<body><span>bar</span></body>';
Now, let's initialize a parser, to convert this into HTML:
var parser = new DOMParser();
var doc = parser.parseFromString(foo, "text/html");
Now, you can read anything from foo, as it is converted into HTML:
document.getElementsByTagName("body")[0].innerHTML = doc.querySelectorAll("body")[0].innerHTML;
$html = document.querySelector("body").innerHTML;
$hello = document.getElementById("hello").innerHTML;
console.log($html);
console.log($hello);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script id="hello">
// script data
</script>
</head>
<body>
</body>
</html>

Why getElementbyId not working in this case?

Okay So this is the code. When I run it. It just has the h1 tag and 3 subparts. It doesn't take value from getElementByID function and assigns it to respective id.
<!Doctype html>
<html>
<head>
<title>My Playlsit</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 Javascripts"
}
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>
You have missed the > symbol of starting li element.
Also function cannot be assigned as string value. Remove the quotes.
window.onload = addsongs;

What can't I get this random quote generator to work?

I've been trying to make a "Random Quote Machine" that randomly selects a quote from an array of 5 quotes and inserts the text into a paragraph on a webpage. The Machine uses HTML and JavaScript(jQuery). I suspect my error is pretty simple given how simple the project is.
Here's the HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Random Quote Machine</title>
<script src="jquery.min.js"></script>
<script src="quotes.js"></script>
</head>
<body>
<h1>Mason Cooley Quotes</h1>
<div>
<p id="quote"></p>
</div>
<button id="quoteGen">Generate A Random Quote</button>
</body>
</html>
Here's the JavaScript:
var quotes = ["Innocence is thought charming because it offers delightful possibilities for exploitation.",
"Every day begins with an act of courage and hope: getting out of bed.",
"Hatred observes with more care than love does.",
"To understand someone, find out how he spends his money.",
"The educated do not share a common body of information, but a common state of mind."
];
function getQuote() {
return Math.floor(Math.random() * quotes.length);
}
$('#quoteGen').click(function() {
$('#quote').text(quotes[getQuote()]);
});
Because your scripts are included in the head element, the quoteGen button doesn't exist in the DOM at the time that you try to bind an event handler to it. You need to either include the scripts just before the end of your body tag, or wrap your code in a DOM-ready event handler to ensure that the DOM exists as you expect it to when your code runs.
So, you could either go with this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Random Quote Machine</title>
</head>
<body>
<h1>Mason Cooley Quotes</h1>
<div>
<p id="quote"></p>
</div>
<button id="quoteGen">Generate A Random Quote</button>
<script src="jquery.min.js"></script>
<script src="quotes.js"></script>
</body>
</html>
... or, use a DOM-ready handler, such as this:
$(function () {
$('#quoteGen').click(function() {
$('#quote').text(quotes[getQuote()]);
});
});
Works just fine?
http://jsfiddle.net/tj3dvz1m/.
make sure to run your code in a
$( document ).ready(function() {
Your code here.
});
The handler is being set before the #quoteGen dom node exists.
You need to move the inclusion of quotes.js to the end of your file, right before the closing of /BODY.
Or register the handler to be installed once the document is ready:
$(document).ready(function(){
$('#quoteGen').click(function() {
$('#quote').text(quotes[getQuote()]);
});
});
This code works fine. Credit to owner.
// Random Quotes
var Quotation=new Array()
Quotation[0] = "Time is of the essence! Comb your hair.";
Quotation[1] = "Sanity is a golden apple with no shoelaces.";
Quotation[2] = "Repent! The end is coming, $9.95 at Amazon.";
Quotation[3] = "Honesty blurts where deception sneezes.";
Quotation[4] = "Pastry satisfies where art is unavailable.";
Quotation[5] = "Delete not, lest you, too, be deleted.";
Quotation[6] = "O! Youth! What a pain in the backside.";
Quotation[7] = "Wishes are like goldfish with propellors.";
Quotation[8] = "Love the river's \"beauty\", but live on a hill.";
Quotation[9] = "Invention is the mother of too many useless toys.";
var Q = Quotation.length;
var whichQuotation=Math.round(Math.random()*(Q-1));
function showQuotation()
{document.write(Quotation[whichQuotation]);}
showQuotation();

Javascript window.onload Not Waiting for DOM to Load

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>

Categories

Resources