Prepending constructed variable to HTML in JS - javascript

I started learning web developing for fun a couple weeks ago and I'm creating a rock-paper-scissors game using HTML, CSS and JS. I'm trying to add something to a block of HTML, but failing to do so with my current code. After a lot of googling I decided to try posting my question.
I added the function I'm trying to add the lines from and the place I'm trying to add them to. As I said, my code is not working and I don't quite understand why.
function displayPlayedRounds(winner) {
"use strict";
// <p class="roundCountPrev">
// <img src="/images/whiteRock.png" class="player1PrevRound"/>
// ← Round 4
// <img src="/images/blackPaper.png" class="player2PrevRound"/>
// </p>
var middlePart, toAppend;
if (winner === -1) {
middlePart = "Round " + movesMade + " →";
} else if (winner === 1) {
middlePart = "← Round " + movesMade;
} else {
middlePart = "Round " + movesMade;
}
toAppend = "<p class='roundCountPrev'><img src=" + userImages[userChoice] + " class='player1PrevRound'/>" + middlePart + "<img src=" + compImages[compMove] + "class='player2PrevRound'/></p>";
document.getElementById('displayPrevRounds').prepend('toAppend');
}
<span id='displayPrevRounds' class="player1">Previous rounds
<p class="roundCountPrev">
<img src="/images/whiteRock.png" class="player1PrevRound"/>← Round 4
<img src="/images/blackPaper.png" class="player2PrevRound"/>
</p>
</span>

firstly, as #madalin ivascu says, prepend is a jQuery function, not comes from DOM methods.
if you want use jQuery, it does a convenient way, you need "import/require/include" jQuery first. like:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
then, you can use this:
$('#displayPrevRounds').prepend(toAppend);
note that, no '', it's a var not chr.
if you want use DOM methods anyway, you can...
actually, i found you question via Google:"document html prepend",
use DOM Method:
parentNode.insertBefore(newChild, refChild);
How can I implement prepend and append with regular JavaScript?
and, here:
Append and Prepend without JQuery?

prepend is a jquery function, create a jquery object
$('#displayPrevRounds').prepend(toAppend);

Related

TypeError: Functionname is not a function at HTMLButtonElement.onClick

I'm pretty new to Javascript and playing around with it at the moment. However, I can't actually test my code because I get the following error:
Uncaught TypeError: namecaller is not a function
at HTMLButtonElement.onclick (Tools.html:101)
Here is my code:
div id="content">
<script>
function namecaller(){
var a = "scurvy";
var b = "dog";
document.getElementById("namecaller").innerHTML = "You are a " + a + " " + b;
}
</script>
Namecaller</p>
<button type="button" onclick="namecaller()">
You are a...</button>
I have no clue why it doesn't work, looked at other StackOverflow questions and also at the W3 tutorials.
function namecaller() {
var a = "scurvy";
var b = "dog";
document.getElementById("content").innerHTML = "You are a " + a + " " + b;
}
<div id="content"></div>
<button type="button" onclick="namecaller()">
You are a...</button>
The code seems to have a lot of problems like your tags were not in properly written. The tags need to open closed properly. And your script should be in right place so that it gets compiled. Then you have not given an id to any of the elements and try calling them. So here is the working example of how the code should be properly written for bug-free compilation.
Sometimes, it is because your function name override some other functions, especially the system defined ones. For example, I once made a function named as "translate." Later, it reports the exactly same error like yours. The solution is quite simple: just change the function name. For me, I make it "function tranlateIt()" and hence the problem is gone forever.
This is not the solution to your particular problem (the accepted answer answers it neatly), but the following might be the useful reference to the future readers (it happened very often to me).
The same error you provided happened to me, when I first declared a variable and then the function with the same name. For example:
var example = 5;
function example() {
console.log("The function just got executed!");
}
<button onclick="example()">Click me!</button>
You have not defined the id of paragraph for which you are changing the value. Just define the Id of paragraph as namecaller and it will work.
See the code below:
<div id="content">
<script>
function namecaller(){
var a = "scurvy";
var b = "dog";
document.getElementById("namecaller").innerHTML = "You are a " + a + " " + b;
}
</script>
<p id = "namecaller">Namecaller</p>
<button type="button" onclick="namecaller()">
You are a...</button
// Write this function code in inside <script> tag or in index.js file
function namecaller() {
var a = "scurvy";
var b = "dog";
document.getElementById("content").innerHTML = "You are a " + a + " " + b;
}
.content{
background-color: bisque;
}
.button{
color: white;
background-color: blue;
}
<!-- Write this code in inside the <body> tag in your index.html file -->
<!-- I added little CSS -->
<div class="content" id="content"></div>
<button class="button" type="button" onclick="namecaller()">You are a...</button>
Your div tag is not properly written. all tags need to open and close properly. You have to give the proper id to any HTML element and then call the function. Run the code snippet.

Javascript function call from html

I'm doing javascript homework(total newb) and the study guide says...
Add document.write() statements around each line of HTML code (p. 53 gives an example)
Be sure to keep the code organized and easy to read.
Keep in mind that single (') and double (") quotes must be nested to avoid errors.
I've done that here.
function displayHeader() {
document.write("<h1>
<img src="images/PeteBanner.jpg" alt="Pistol Pete" />
Jason Lemon's Javascript Website!
<img src="images/PeteBanner.jpg" alt="Pistol Pete" /></h1>;
};
When I go to the header section of the html file...I'm supposed to call the function. I referenced the javascript file in the head section. Here is what I'm putting in the header section. It's not working. I know my code is way off.
It should look more like this ...
function displayHeader() {
document.write(
'<h1>' +
'<img src="images/PeteBanner.jpg" alt="Pistol Pete" />' +
'Jason Lemon\'s Javascript Website!' +
'<img src="images/PeteBanner.jpg" alt="Pistol Pete" />' +
'</h1>';
)
}
... but using document.write is generally bad practice, but if that's what the assigment says, I guess it's okay, just know that you shouldn't be using it.
To call the function after you've included the script in your HTML, you can do
<script type="text/javascript">
displayHeader()
</script>
Use one line.
function displayHeader() {
document.write('<h1><img src="images/PeteBanner.jpg" alt="Pistol Pete" />Jason Lemon\'s Javascript Website! <img src="images/PeteBanner.jpg" alt="Pistol Pete" /></h1>')
};
You need to concat the strings or write all in one line. Like this it would look like if you concatenate the strings.
function displayHeader() {
document.write(
"<h1> "
+ "<img src = 'images/PeteBanner.jpg' alt = 'Pistol Pete' / >"
+ "Jason Lemon 's Javascript Website!"
+ "<img src = 'images/PeteBanner.jpg' alt = 'Pistol Pete' / > </h1>"
);
};

Javascript getElementsByTagName - include embedded elements

I am using a fragment of javascript from the internet to collect all the <small></small> elements within a div id 'footnotes' and append them as an ordered list at the end of my document, with links and back links (i.e Easy HTML Footnotes), Footnotes.js:
var DOMsupport = document.getElementsByTagName && document.createElement;
window.onload = function() {
if (!DOMsupport) return;
var footNoteHolder = document.getElementById('footnotes');
var allNotes = footNoteHolder.getElementsByTagName('small');
var notesList = document.createElement('ol');
notesList.className = 'notesList';
for (var i = 0; i < allNotes.length; i++) {
var newA = document.createElement('a');
newA.id = 'text-' + (i + 1);
newA.setAttribute('href', '#footnote-' + (i + 1));
newA.setAttribute('title', 'Jump to footnote');
newA.appendChild(document.createTextNode((i + 1)));
newBackLink = document.createElement('a');
newBackLink.id = 'footnote-' + (i + 1);
newBackLink.setAttribute('href', '#text-' + (i + 1));
newBackLink.setAttribute('title', 'Back to text');
newBackLink.appendChild(document.createTextNode('[back]'));
newNote = document.createElement('li');
newNote.appendChild(document.createTextNode(allNotes[i].firstChild.nodeValue + ' '));
newNote.appendChild(newBackLink);
notesList.appendChild(newNote);
allNotes[i].replaceChild(newA, allNotes[i].firstChild);
}
footNoteHolder.appendChild(document.createElement('hr'));
footNoteHolder.appendChild(notesList);
}
I like the simplicity, no Jquery in sight, but I would like to be able to include line breaks <br> and/or links Click for PubMed inside some of the footnotes.
When I try to include any other elements within the <small></small> tags the text is placed within the body - not collected and placed at the end. e.g.
<!DOCTYPE HTML>
<html>
<head>
<title>MDT Home</title>
</style>
<script type='text/javascript'
src='..\..\js\footnotes.js'>
</script>
</head>
<body>
<span id='footnotes' ><br>
<h2>Welcome to the MDT site<br></h2><br>
I have designed the site in a minimalist style using <a href='https://www.lua.org/' title='Lua'>Lua</a> it should run on all trust machines.<br>
<br>
To use the menu click the icon at the top left. If you have a modern browser you can use keyboard shortcuts [<small>
Alt-M: Menu.<br>
Alt-H: MDT Home.<br>
Alt-K: Hip and Knee.<br>
Alt-A: Foot and Ankle.<br>
Alt-W: Wrist and Hand.<br>
Alt-S: Shoulder and Elbow.<br>
Alt-I: Spine.<br>
Alt-C: Children.<br>
</small>] e.g move to menu by entering Alt-M.
Please read the terms of use before proceeding to review patient data. <br>
<br></span>
</body>
</html>
I'm not sure if the problem lies with the selection of allNotes using getElementsByTagName('small') producing a NodeList object, or is the problem the building of the newNote using allNotes[i].firstChild.nodeValue + ' ' .
Sorry I don't have the original source of this fragment any longer - normally I would credit the author - and ask them directly. In an ideal world I would learn javascript properly instead of culling fragments and pasting then into my pages.
Any help gratefully received.
Gavin
Spurred on by the criticism I have examined each line of this code to find why I can't have elements in my footnotes.
It appears you can't have elements within TextNodes. A post which Mr Thomas is well aware of, having contributed in the comments.
I will not be learning Javascript to find an alternative mechanism of collating fragments which may or may not contain elements. I know there are good bits of Javascript, but DOM coding does not seem to be one of them.

Refresh div with button click using random javascript string element

There are several similar questions, so I hope this is a unique problem. None of the proposed solutions on those similar questions have solved my issue. Humble apologies from this beginner if I messed up somehow.
I have an empty div on my page with I am loading using javascript with strings from an array. Currently, I have a script running on a button which reloads the entire page. I would like for that button to just reload the div with items from my javascript array.
Here is my code:
<html>
<head>
<link rel="stylesheet" href="obliqueStyle.css">
<style></style>
</head>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<body>
<div id="wrapper">
<div id="strategyBox"></div>
<div id="button">
<a class="againbutton" onclick="buttonReload()">Again</a>
<script>
var buttonReload = function() {
document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
}
</script>
</div>
</div>
<script src="os.js"></script>
</body>
Here is a snippet of my array and the JS (coming from the os.js file referenced in index.html) I am using to load the div initially/on refresh:
var obliqueStrategy = ["Abandon normal instruments",
"Accept advice",
"Accretion",
"A line has two sides"];
var randomStrategy = obliqueStrategy[Math.floor(Math.random() * obliqueStrategy.length)];
document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
I've tried calling the same javascript as a function in script in the html like this:
<div id="button">
<a class="againbutton" onclick="buttonReload()">Again</a>
<script>
var buttonReload = function() {
document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
}
</script>
</div>
I've tried using the jQuery AJAX load function like this:
<script>
$(function() {
$("#againbutton").on("click", function() {
$("#strategyBox").load("index.html")
return false;
})
})
</script>
I've played around with variations of the above and tried a couple other things that I'm forgetting exactly how and what I did, so I can't include them. I've really hit a wall on this even though it seems profoundly simple.
Thanks in advance for any help.
Here's one method: http://jsfiddle.net/kxqcws07/
HTML
<div id="wrapper">
<div id="strategyBox"><p id="strategyText"></p></div>
<div>
<input type="button" class="againbutton" value="Again">
</div>
</div>
Javascript
//wrapping your logic in a namespace helps reduce the chances of naming collisions of functions and variables between different imported js files
var localNameSpace = function() {
//private array containing our strings to randomly select
var obliqueStrategy = [
"Abandon normal instruments"
, "Accept advice"
, "Accretion"
, "A line has two sides"
];
var api = {
//bindButtonAction binds the generateRandomStrategy function to the click event of the againbutton
bindButtonAction: function() {
$('#wrapper .againbutton').click(api.generateRandomStrategy);
}
, generateRandomStrategy: function() {
//get the position of one of the string randomly
//Math.random() returns a float value < 1 so multiplying it by 100 gets us a range of (0.* - 99.*)
//then we Math.floor() that to get rid of the float value and keep just the integer part
//finally we modulus it with the length of the string array
//if you are unfamiliar with modulus, what it does is gives you the remainder of a division. for instance 10 / 3 gives you 3 with a remainder of 1, so 10 % 3 would be just 1.
//what this does for us is keeps the random offset of our within the bounds of the array length (0 to length -1)
var randomOffset = Math.floor(Math.random() * 100) % obliqueStrategy.length;
//finally once we have the offset, we set the html to the string at the position in the array
$('#wrapper #strategyBox #strategyText').html( obliqueStrategy[randomOffset] );
}
};
return api;
}();
$(document).ready(function() {
//here we call the bind action so the button will work, but we also explicitly call the generateRandomStrategy function so the page will preload with a random string at the start
localNameSpace.bindButtonAction();
localNameSpace.generateRandomStrategy();
});

How to reload JSON with AJAX every 10 Seconds

I'm trying to reload a JSON file every 10 seconds with JQUERY.
The page is here: http://moemonty.com/chirp/chirp.html
The Code is here:
<html>
<head>
<title>the title</title>
<!-- included Jquery Library -->
<script type="text/javascript" src="./js/jquery-1.4.2.js"></script>
<!-- jquery library -->
</head>
<body>
<script>
$.ajaxSetup({ cache: false }); //disallows cachinge, so information should be new
function loadChirp(){ //start function
var url = "http://www.chirpradio.org/json";
$.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22"+url+"%22&format=json&callback=?",
function(data){
console.log(data.query.results.json);
document.write('The artist is: ' + data.query.results.json.artist + '<br/><br/>');
document.write('The artist is: ' + data.query.results.json["record-label"] + '<br/><br/>' );
document.write('The album is: ' + data.query.results.json.album + '<br/><br/>');
document.write('The record label is: ' + data.query.results.json["record-label"] + '<br/><br/>');
document.write('The feedback link is: ' + data.query.results.json["feedback-link"] + '<br/><br/>');
document.write('The database id is: ' + data.query.results.json["database-id"] + '<br/><br/>');
document.write('The time is: ' + data.query.results.json.timestamp.time + ' ');
document.write(data.query.results.json.timestamp["am-pm"] + '<br/><br/>');
document.write('The current dj is: ' + data.query.results.json["current-dj"] + '<br/><br/>');
setTimeout("loadChirp()",5000);
alert('The timeout was triggered.');
});
} //end function
$(document).ready(function(){
//DOCUMENT READY FUNCTION
loadChirp();
});
//DOCUMENT READY FUNCTION
</script>
</body>
</html>
It doesn't seem to be working.
You probably want the previous set of returned data replaced by the new set, instead of appending it. In that case, using jQuery you can do:
<div id='content'></div>
<script>
function loadChirp(){
$.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22"+url+"%22&format=json&callback=?",
function(data) {
$('#content').html('The artist is: ' + data.query.results.json.artist + '<br/><br/>');
});
setTimeout("loadChirp()",5000);
}
</script>
etc...
I would expect the loop to work as quoted, but there could be a subtlety around the fact you're using JSONP. I would change the setTimeout call to:
setTimeout(loadChirp, 5000);
...for a couple of reasons. First off, using the function reference rather than a code string is a better idea generally, and second off, you're quite certain that you're getting the right function reference (whereas with the string, what reference you get depends on the context in which the code is executed).
But as Pointy pointed out in a comment, there's a separate issue: document.write will not do what you probably want it to do there. You can only use document.write to write to the HTML stream that's being parsed as part of the original page load. After the page load, you can't use it anymore. Consider using jQuery's append or appendTo and similar functions to add to the DOM after page load.
You have an error in console.log(data.query.results.json); - console is not defined.
Also, you can use setInterval( "function()", 5000 );.
You should definitely use:
setInterval("loadChirp", 10000):
Don't write loadCrirp() inside setInterval as we're only passing a refrence

Categories

Resources