How to display JavaScript variables in a HTML page without document.write - javascript

I am trying to display some JavaScript variable on my HTML page.
I was first using document.write() but it use to overwrite the current page when the function was called.
After searching around, the general consensus was that document.write() isn't liked very much. What are the other options?
I found a page suggesting using .innerHTML but that was written in 2005.
A jsFiddle illustrating my problem http://jsfiddle.net/xHk5g/

Element.innerHTML is pretty much the way to go. Here are a few ways to use it:
HTML
<div class="results"></div>
JavaScript
// 'Modern' browsers (IE8+, use CSS-style selectors)
document.querySelector('.results').innerHTML = 'Hello World!';
// Using the jQuery library
$('.results').html('Hello World!');
If you just want to update a portion of a <div> I usually just add an empty element with a class like value or one I want to replace the contents of to the main <div>. e.g.
<div class="content">Hello <span class='value'></span></div>
Then I'd use some code like this:
// 'Modern' browsers (IE8+, use CSS-style selectors)
document.querySelector('.content .value').innerHTML = 'World!';
// Using the jQuery library
$(".content .value").html("World!");
Then the HTML/DOM would now contain:
<div class="content">Hello <span class='value'>World!</span></div>
Full example. Click run snippet to try it out.
// Plain Javascript Example
var $jsName = document.querySelector('.name');
var $jsValue = document.querySelector('.jsValue');
$jsName.addEventListener('input', function(event){
$jsValue.innerHTML = $jsName.value;
}, false);
// JQuery example
var $jqName = $('.name');
var $jqValue = $('.jqValue');
$jqName.on('input', function(event){
$jqValue.html($jqName.val());
});
html {
font-family: sans-serif;
font-size: 16px;
}
h1 {
margin: 1em 0 0.25em 0;
}
input[type=text] {
padding: 0.5em;
}
.jsValue, .jqValue {
color: red;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Setting HTML content example</title>
</head>
<body>
<!-- This <input> field is where I'm getting the name from -->
<label>Enter your name: <input class="name" type="text" value="World"/></label>
<!-- Plain Javascript Example -->
<h1>Plain Javascript Example</h1>Hello <span class="jsValue">World</span>
<!-- jQuery Example -->
<h1>jQuery Example</h1>Hello <span class="jqValue">World</span>
</body>
</html>

You can use javascript to access elements on the page and modify their contents. So for example you might have a page with some HTML markup like so:
<div id="MyEdit">
This text will change
</div>
You can use javascript to change the content like so...
document.getElementById("MyEdit").innerHTML = "My new text!";​
Here is a working example
You can also look at using the JQuery javascript library for DOM manipulation, it has some great features to make things like this very easy.
For example, with JQuery, you could do this to acheive the same result...
$("#MyEdit").html("My new text!");
Here is a working example of the JQuery version
Based on this example you provided in your post. The following JQuery would work for you:
var x = "hello wolrd";
$("p").html(x);
Here is the working version
Using a P tag like this however is not recommended. You would ideally want to use an element with a unique ID so you can ensure you are selecting the correct one with JQuery.

there are different ways of doing this.
one way would be to write a script retrieving a command.
like so:
var name="kieran";
document.write=(name);
or we could use the default JavaScript way to print it.
var name="kieran";
document.getElementById("output").innerHTML=name;
and the html code would be:
<p id="output"></p>
i hope this helped :)

You could use jquery to get hold of the html element that you want to load the value with.
Say for instance if your page looks something like this,
<div id="FirstDiv">
<div id="SecondDiv">
...
</div>
</div>
And if your javascript (I hope) looks something as simple as this,
function somefunction(){
var somevalue = "Data to be inserted";
$("#SecondDiv").text(somevalue);
}
I hope this is what you were looking for.

If you want to avoid innerHTML you can use the DOM methods to construct elements and append them to the page.
​var element = document.createElement('div');
var text = document.createTextNode('This is some text');
element.appendChild(text);
document.body.appendChild(element);​​​​​​

innerHTML is fine and still valid. Use it all the time on projects big and small. I just flipped to an open tab in my IDE and there was one right there.
document.getElementById("data-progress").innerHTML = "<img src='../images/loading.gif'/>";
Not much has changed in js + dom manipulation since 2005, other than the addition of more libraries. You can easily set other properties such as
uploadElement.style.width = "100%";

hi here is a simple example: <div id="test">content</div> and
var test = 5;
document.getElementById('test').innerHTML = test;
and you can test it here : http://jsfiddle.net/SLbKX/

Add an element to your page (such as a div) and write to that div.
HTML:
<html>
<header>
<title>Page Title</title>
</header>
<body>
<div id="myDiv"></div>
</body>
</html>
jQuery:
$('#myDiv').text('hello world!');
javascript:
document.getElementById('myDiv').innerHTML = 'hello world!';

Similar to above, but I used (this was in CSHTML):
JavaScript:
var value = "Hello World!"<br>
$('.output').html(value);
CSHTML:
<div class="output"></div>

Related

Directly adding text into innerHTML without using innerText

Is it possible to add string inside innerHTML without having to use innerText?
like this:
var sentence="<b>hello there</b>";
document.querySelector(".container").innerHTML='<span class="thing"></span>';
document.querySelector(".thing").innerText=sentence;
<!DOCTYPE html>
<html>
<head></head>
<body>
<div class="container"></div>
</body>
</html>
but without having to use innerText,
Maybe the code would look something like this:
var sentence="<b>hello there</b>";
document.querySelector(".container").innerHTML='<span class="thing">'+raw(sentence)+'</span>';
I don't see anything seriously wrong with your current approach. If you want to avoid the repetition of creating an element with a particular class and then have to select it again right after you append it, you can consider creating an element instead of an HTML string:
var sentence="<b>hello there</b>";
document.querySelector(".container")
.appendChild(document.createElement('span'))
.textContent = sentence;
<div class="container"></div>

how to convert an html script into a .js file script

would like to place the script into a .js file that opens already with
$(document).ready(function() {
});
I have tried but it feel slike because im putting the onMouse over command into the html I don't think it will be possible?
<head>
<style>
div > p {
cursor: pointer;
}
</style>
<script>
var monkeySrc = "http://icons.iconarchive.com/icons/martin-berube/animal/256/monkey-icon.png";
var lionSrc = "http://icons.iconarchive.com/icons/martin-berube/animal/256/lion-icon.png";
var treeSrc = "http://totaltreeworks.co.nz/wp-content/uploads/2011/02/Tree-256x256.png";
var falconSrc = "http://icons.iconarchive.com/icons/jonathan-rey/star-wars-vehicles/256/Millenium-Falcon-01-icon.png";
function changeImage(src){
document.getElementById("myImage").src = src;
}
</script>
</head>
<body>
<div class="images">
<img id="myImage" width="256" height="256">
</div>
<div>
<p onmouseover="changeImage(monkeySrc)">Monkey are funny!</p>
</div>
<div>
<p onmouseover="changeImage(lionSrc)">Lions are cool!</p>
</div>
<div>
<p onmouseover="changeImage(treeSrc)">Trees are green!</p>
</div>
<div>
<p onmouseover="changeImage(falconSrc)">Falcons are fast!<p>
</div>
</body>
</html>
If you were to take your existing JavaScript and place it in an external file, it would work just fine. It would work because all of your variables and your function would be in the global scope.
Going one step further you'll want to move those onmouseover event handlers into the JavaScript itself.
Given a small change to your current HTML and assuming jQuery you could do something like the following:
<p data-kind="monkey">Monkey are funny!</p>
then
var urlMap = {
monkey : 'http://icons.iconarchive.com/icons/martin-berube/animal/256/monkey-icon.png'
...
};
$('p').on('mouseover', function () {
var kind = $(this).data('kind');
var url = urlMap[kind];
changeImage(url);
});
which you would then be able to wrap in the $(document).ready, the shorthand for which is just $(function () { /* The code from above here */ });
You would need to bind the event handlers programmatically from within the .js file. jQuery would make this very simple and allow you to use arbitrary CSS selectors, but you can do the same in pure JS using e.g. document.getElementById and document.addEventListener.
You can bind the function to the event using Javascript addEventListner
1- Add id attribute to each of your paragraphs tags
<p id="p1"> .....</p>
2- Grab a variable that points to each of those
var p1 = document.getElementById('p1');
3- add event listner
p1.addEventListener("mouseover", changeImage(monkeySrc));
If you put your javascript code in another file and replace <script>...</script> with <script src="javascriptcodefilename.js"></script> in your HTML file, it still works as intended.
Example: http://codepen.io/anon/pen/waLqxz
It might be cleaner to add all of your urls to an array where the key is the name of the link, so you would have something like urls['lionSrc'] = "www.xyz.com";...
then in your changeImage function you would do document.getElementById("myImage").src = url[src];
this way you could even check to see if the image exists already, and if not, show an "image not found" icon.

Easy way to set font color in javascript onClick?

Question: So let's say I have some basic code
<a name = "sec">this is a test</a>
I want a javascript function to on click of a link to change that to
So user clicks:
link!
And the JS kicks in to change the 1st html to:
<font color = "green"><a name = "sec">this is a test</a></font>
Is it possible to do this in JS?
You can set the element's color with JS as a simple solution. You should also give the element a valid href attribute that nullifies the default click behavior.
<a name="sec" href="javascript:void(0);" onclick="this.style.color='green';">
this is a test
</a>
Try something along the lines of
link
And you should not use <font> tag for setting text attributes, this is considered bad practice in today’s HTML (be it XHTML or HTML5).
Something like this should work: (Psudeo Code)
<a id="sec" onClick="makeGreen()">this is a test</a>
<script type="text/javascript" charset="utf-8">
function makeGreen() {
document.getElementById('sec').style.color('green');
};
</script>
Realistically, you should keep your semantics and your style separate. As other users have suggested, use a css class instead of modifying styles directly. This is fairly easy to do, as shown by this jsFiddle
This is a test
<script type="text/javascript">
var el = document.getElementById('my-link');
el.addEventListener('click', function() {
this.className = 'clicked-class';
});
</script>
And of course in your CSS you would define some sort of rule:
.clicked-class {
color: green;
}
This could be made even simpler with a javascript library of your choice, but hopefully should be enough to get you started.
$(element).on("click",function() {$(this).css({'color', 'blue'});

Updating the content of a div with javascript

Rather than trying to create tons of different pages on my website, I'm trying to update the content of a single div when different items in the navbar are click to update the maint div content. I tried to find a simple example using Javascript:
<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>
<div id="example1div" style="border-style:solid; padding:10px; text-align:center;">
I will be replaced when you click.
</div>
<a href="javascript:ReplaceContentInContainer('example1div', '<img src='2.jpg'>' )">
Click me to replace the content in the container.
</a>
This works just fine when I only try and update text, but when I put an img tag in there, as you can see, it stops working.
Either
1) what is the problem with how I am trying to do it?
or 2) What is a better/easier way to do it?
I'm not stuck on Javascript. jQuery would work too, as long as it is just as simple or easy. I want to create a function that will just let me pass in whatever HTML I want to update and insert it into the div tag and take out the 'old' HTML.
You just have some escaping issues:
ReplaceContentInContainer('example1div', '<img src='2.jpg'>')
^ ^
The inner ' need to be escaped, otherwise the JS engine will see ReplaceContentInContainer('example1div', '<img src=' plus some syntax errors resulting from the subsequent 2.jpg'>'). Change the call to (tip of the hat to cHao' answer concerning escaping the < and > in the HTML):
ReplaceContentInContainer('example1div', '<img src=\'2.jpg\'>')
A simple way to do this with jQuery would be to add an ID to your link (say, "idOfA"), then use the html() function (this is more cross-platform than using innerHTML):
<script type="text/javascript">
$('#idOfA').click(function() {
$('#example1div').html('<img src="2.jpg">');
});
</script>
First of all, don't put complex JavaScript code in href attributes. It's hard to read or to maintain. Use the <script> tag or put your JavaScript code in a separate file altogether.
Second, use jQuery. JavaScript is a strange beast: the principles underlying its patterns were not designed with modern-day web development in mind. jQuery gives you lots of power without miring you in JavaScript's oddities.
Third, if your goal is to avoid having to endlessly duplicate the same basic structure for all (or many) of your pages, consider using a templating system. Templating systems allow you to plug in specific content into scaffolds containing the common elements of your site. If it sounds complicated, it's because I haven't explained it well. Google it and you'll find lots of great resources.
Relying on JavaScript for navigation means your site won't be indexed properly by search engines and will be completely unusable to someone with JavaScript turned off. It is increasingly common--and acceptable--to rely on JavaScript for basic functionality. But your site should, at minimum, provide discrete pages with sensible and durable URLs.
Now, all that said, let's get to your question. Here's one way of implementing it in jQuery. It's not the snazziest, tightest implementation, but I tried to make something very readable:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery Example</title>
<style type="text/css" media="all">
/* all content divs should be hidden initially */
.content {
display: none;
}
/* make the navigation bar stand out a little */
#nav {
background: yellow;
padding: 10px;
}
</style>
</head>
<body>
<!-- navigation bar -->
<span id="nav">
about me |
copyright notice |
a story
</span>
<!-- content divs -->
<div class="content" id="about_me">
<p>I'm a <strong>web developer</strong>!</p>
</div>
<div class="content" id="copyright">
<p>This site is in the public domain.</p>
<p>You can do whatever you want with it!</p>
</div>
<div class="content" id="my_story">
<p>Once upon a time...</p>
</div>
<!-- jquery code -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
// Wait for the document to load
$(document).ready(function() {
// When one of our nav links is clicked on,
$('#nav a').click(function(e) {
div_to_activate = $(this).attr('href'); // Store its target
$('.content:visible').hide(); // Hide any visible div with the class "content"
$(div_to_activate).show(); // Show the target div
});
});
</script>
</body>
</html>
Ok, hope this helps! If jQuery looks attractive, consider starting with this tutorial.
Your main problem with your example (besides that innerHTML is not always supported) is that < and > can easily break HTML if they're not escaped. Use < and > instead. (Don't worry, they'll be decoded before the JS sees them.) You can use the same trick with quotes (use " instead of " to get around quote issues).

best way to inject html using javascript

I'm hoping that this isn't too subjective. I feel there is a definitive answer so here goes.
I want to create this html on the fly using JS (no libraries):
Play
Mute
<div id="progressBarOuter">
<div id="bytesLoaded"></div>
<div id="progressBar"></div>
</div>
<div id="currentTime">0:00</div>
<div id="totalTime">0:00</div>
using javascript. I know I can do this using createElement etc but it seems extremely long winded to do this for each element. Can anyone suggest a way to do this with more brevity.
I do not have access to a library in this project....so no jquery etc.
Keep your markup separate from your code:
You can embed the HTML snippets that you'll be using as hidden templates inside your HTML page and clone them on demand:
<style type="text/css">
#templates { display: none }
</style>
...
<script type="text/javascript">
var node = document.getElementById("tmp_audio").cloneNode(true);
node.id = ""; // Don't forget :)
// modify node contents with DOM manipulation
container.appendChild(node);
</script>
...
<div id="templates">
<div id="tmp_audio">
Play
Mute
<div class="progressBarOuter">
<div class="bytesLoaded"></div>
<div class="progressBar"></div>
</div>
<div class="currentTime">0:00</div>
<div class="totalTime">0:00</div>
</div>
</div>
Update: Note that I've converted the id attributes in the template to class attributes. This is to avoid having multiple elements on your page with the same ids. You probably don't even need the classes. You can access elements with:
node.getElementsByTagName("div")[4].innerHTML =
format(data.currentTime);
Alternatively, you can act on the HTML of the template:
<script type="text/javascript">
var tmp = document.getElementById("tmp_audio").innerHTML;
// modify template HTML with token replacement
container.innerHTML += tmp;
</script>
Shove the entire thing into a JS variable:
var html = 'Play';
html += 'Mute';
html += '<div id="progressBarOuter"><div id="bytesLoaded"></div><div id="progressBar"></div></div>';
html += '<div id="currentTime">0:00</div>';
html += '<div id="totalTime">0:00</div>';
Then:
document.getElementById("parentElement").innerHTML = html;
if you want theN:
document.getElementById("totalTime").innerHTML = "5:00";
You can use
<script type="text/javascript">
function appendHTML() {
var wrapper = document.createElement("div");
wrapper.innerHTML = '\
Play\
Mute\
<div id="progressBarOuter"> \
<div id="bytesLoaded"></div>\
<div id="progressBar"></div>\
</div>\
<div id="currentTime">0:00</div>\
<div id="totalTime">0:00</div>\
';
document.body.appendChild(wrapper);
}
</script>
If you live in 2019 and beyond read here.
With JavaScript es6 you can use string literals to create templates.
create a function that returns a string/template literal
function videoPlayerTemplate(data) {
return `
<h1>${data.header}</h1>
<p>${data.subheader}</p>
Play
Mute
<div id="progressBarOuter">
<div id="bytesLoaded"></div>
<div id="progressBar"></div>
</div>
<time id="currentTime">0:00</time>
<time id="totalTime">0:00</time>
`
}
Create a JSON object containing the data you want to display
var data = {
header: 'My video player',
subheader: 'Version 2 coming soon'
}
add that to whatever element you like
const videoplayer = videoPlayerTemplate(data);
document.getElementById('myRandomElement').insertAdjacentHTML("afterbegin", videoplayer);
You can read more about string literals here
edit: HTML import is now deprecated.
Now with Web Components you can inject HTML using an HTML import.
The syntax looks like this:
<link rel="import" href="component.html" >
This will just load the content of the html file in the href attribute inline in the order it appears. You can any valid html in the loaded file, so you can even load other scripts if you want.
To inject that from JavaScript you could do something of the likes of:
var importTag = document.createElement('link');
importTag.setAttribute('rel', 'import');
importTag.setAttribute('href', 'component.html');
document.body.appendChild(importTag);
At the time I am writing this, Chrome and Opera support HTML imports. You can see an up to date compatibility table here http://caniuse.com/#feat=imports
But don't worry about browsers not supporting it, you can use it in them anyway with the webcomponentsjs polyfill.
For more info about HTML imports check http://webcomponents.org/articles/introduction-to-html-imports/
If you don't need any validation for your syntax (which is what makes createElement() so nice) then you could always default to simply setting the innerHTML property of the element you want to insert your markup inside of.
Personally, I would stick with using createElement(). It is more verbose but there are far less things to worry about that way.
If performance is a concern, stay away from innerHTML. You should create the whole object tree using document.createElement() as many times as needed, including for nested elements.
Finally, append it to the document with one statement, not many statements.
In my informal testing over the years, this will give you the best performance (some browsers may differ).
If HTML is ever declared in a variable, it should be simple and for a very specific purpose. Usually, this is not the right approach.
here's 2 possible cases :
Your HTML is static
Your HTML is dynamic
solution 1
In this case, wrap your HTML in double quotes, make it a string and save it in a variable. then push it inside HTML, here's a demo 👇
HTML
<div id="test"></div>
JavaScript
let selector = document.querySelector("#test");
let demo_1 = "<div id='child'> hello and welcome</div>"
selector.innerHTML = demo_1;
solution 2
In this case, wrap your HTML in back ticks, make it a template literal and save it in a variable. then push it inside HTML,
here, you can use variables to change your content. here's a demo 👇
HTML
<div id="test"></div>
JavaScript
let selector = document.querySelector("#test");
let changes = 'hello and welcome'
let demo_1 = `<div id='child'>${changes}</div>`
selector.innerHTML = demo_1;
You can concatenate raw HTML strings (being careful to escape text and prevent XSS holes), or you can rewrite jQuery (or something similar)
I have a situation where I pass text into a third party library, but if my model isPrivate, I'd like to add an element to the text.
return { id: item.id, text: (item.isPrivate == true) ? "<i class=\"icon-lock\" title=\"Private group.\"></i> " + item.label : item.label };
This creates issues with the way the third party library builds up its markup.
This is never a good idea, but third party libraries are there so that we don't have to write everything ourselves. In a situation like this, you have to rely on passing markup though javascript.
When i find a proper solution to this, I will give you an update

Categories

Resources