Javascript getElementsByTagName - include embedded elements - javascript

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.

Related

Trying to add styles/change fonts in a random text and image script

I'm trying to get a webpage to open up a random image and text to go along with it. I will be using this to have different events posted on our library's front page. Pulling from different examples on the web I've gotten the basics to work fine with this.
var total_images = 2;
var random_number = Math.floor((Math.random()*total_images));
var random_img = new Array();
var random_text = [];
random_img[0] = "<a href = 'www.webpage.com'><img src='image_1.jpg' alt='Image'></a>";
random_text[0] = "<p>Here is some text</p>";
random_img[1] = "<a href = 'www.webpage2.com'><img src='image_2.jpg' alt='Image2'></a>";
random_text[1] = "<p>Here is some text2</p>";
document.write(random_img[random_number] + ' <br/><p id="myP">' + random_text[random_number] + 'dfsadf</p>');
function myFunction() {
document.getElementById("myP").style.font = "italic bold 20px arial,serif";
}
It works as hoped and on a refresh will display a new event picture and text. What I am having trouble with is I cannot get it to match the styles from the rest of our webpage. I've tried using functions to create a new id, regular html tags and just about anything I can pull from the web. Any time I add anything more to the random_text[] = "<p>codehere</p>"; than the usual <b> or <i> it breaks the page.
If I can change the fonts to match it would be perfect.
It will probably break the page because a <p> tag should not be put inside of another <p> tag. Try this for the document write:
document.write('<div id="myP">' + random_img[random_number] + ' <br/>' + random_text[random_number] + 'dfsadf</div>');
And the fonts could be modified using CSS in your HTML page:
<style type="text/css">
#myP p { font:20px arial,sans-serif; }
</style>

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 write to page in javascript using date method

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>

'document.Form1.imgLoading' is null or not an object

Could someone help please, i'm stuck on the following error:
'document.Form1.imgLoading' is null or not an object control.js, line 55 character 2
Which is:
Line 55: document.Form1.imgLoading.style.width=370
From:
function setLoading(){
var strPath = "../images/"
var strFName = "searchingText.gif"
var strSearchPath = ""
//15/2if (!document.Form1.TextBoxLangID.value == "") { //SO LANG USED
// strSearchPath = strPath + document.Form1.TextBoxLangID.value + "/brand/" + strFName
//}
//else{
// strSearchPath = strPath + "brand/" + strFName
//15/2}
//document.Form1.imgSearchingText.src = strSearchPath
document.Form1.imgLoading.style.width=370
document.Form1.imgLoading.style.height=328
document.Form1.imgLoading.style.left = 327
document.Form1.imgLoading.style.top = 220
document.Form1.imgLoading.style.zIndex=2000'
The problem with your code is you are referring like form.controlname. In ASP.Net the control names are generated like ctl$imgLoading etc based on Master page/nested control configuration.
Better avoid document.Form1.imgLoading and make use of referring it
based on id using native document.getElementById()
If you have the script code in .aspx page, Please use the below code to refer the element
var imgLoading=document.getElementById('<%= imgLoading.ClientID %>');
imgLoading.style.width=370;
In case if you have the script in JS file
Make sure you set the ClientIDMode=staticSupported from ASP.Net 4.0 only for imgLoading control in .aspx page, then
var imgLoading=document.getElementById('imgLoading');
imgLoading.style.width=370;
I do not have enough reputation to comment, but I just want to say that if your <script> tags are in the <head> section, place your script tags at the back of the body section, or load the script onload of the document.
This is because the image that is in the <body> section of your document has yet to be loaded, so it is null or not an object.
Hope that helps.
If imgLoading is a asp:Image control then you have to find it using next code:
document.getElementById('<%= imgLoading.ClientID %>').style.width = 370

External Javascript File Fetch?

I am currently using this code:
var wordRandomizer = {
run: function (targetElem) {
var markup = this.createMarkup();
targetElem.appendChild(markup);
},
createMarkup: function () {
var that = this;
var frag = document.createDocumentFragment();
this.elem = document.createElement('span');
var button = document.createElement('button');
button.innerText = 'Change Item';
button.addEventListener('click', function () {
that.changeItem();
});
frag.appendChild(this.elem);
frag.appendChild(button);
return frag;
},
changeItem: function () {
var rand = this.getRandInt(1, this.items.length) - 1;
console.log(rand);
this.elem.innerText = this.items[rand];
},
getRandInt: function (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
},
items: ['itemA', 'itemB', 'itemC', 'itemD']
};
wordRandomizer.run(document.body);
I code is a button which when pressed grabs one of the items in the list. However, I don't want the items to show on the same page as the generator as people simply look at the source code. How can I make it so once the button is pressed it grabs the random item from another location where people cannot view them all using the source code.
If it helps, you can see the code in action here - http://jsbin.com/ESOdELU/1/edit
I will give you a solution using PHP since it is a free scripting language and is the most likely to be supported by a host or default web server...
For starters, here is the code to include jquery and the basic AJAX script
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/JavaScript">
$(document).ready(function(){
$("#generate").click(function(){
$("#madlibs p").load("script.php");
});
});
</script>
Here is the code for script.php
<?php
header("Cache-Control: no-cache");
// For testing you can use an inline array like the lines below
// Just remove the comment slashes "//" from the beginning of the line
// and comment out the external declarations
//$actors = array('Denzel Washington','Michael J. Fox','Jim Carey','Boris Kodjoe');
//$roles = array('Mental Patient','Homeless Musician','Drag Queen Detective','Tormented Mathematician');
// In production, you would put these in a text file or a database.
// For $actors, put an entry on each line of a text file and save it as 'leads.txt'
// Do the same with a separate file for $roles (roles.txt).
$actors = file("leads.txt");
$roles = file("roles.txt");
// This selects a random element of each array on the fly
echo $prefixes[rand(0,count($actors)-1)] . " stars as a "
. $suffixes[rand(0,count($roles)-1)] . " in the next blockbuster film.";
// Example output:
// Michael J. Fox stars as a Tormented Mathematician in the next blockbuster film.
?>
Put this in the body of your page and be sure to style everything up for display.
<body>
<div id="madlibs"><p> </p></div>
<button id="generate">Surprise Me!</button>
</body>
A couple of notes:
- You can include your basic layout HTML in the script.php file and then would only need the ID of the DIV in which you will be displaying the result $("#madlibs")
You can use any server side language to achieve the same result, just swap out the external file call to the appropriate name and extension (.asp, .cfm, etc.)
Here is a link to the original tutorial that helped me with a similar project:
http://www.sitepoint.com/ajax-jquery/
I hope this helps. Sorry, but I couldn't come up with a purely Java of JavaScript solution on lunch.

Categories

Resources