javascript array length not accessible in web page - javascript

I have a javascript array in an external file:
<script src="assets/players.js"></script>
contents of above array:
window.players = [
"Addison, Jackson",
"Agron, Dmitry",
"Zuccarino, John"
]
I have tried to return the number of records to no avail:
<h3>Sample data file with <script>window.players.length;</script> names:</h3>
What am I doing wrong..?

If you want to write out the length, than you would need to use document.write
<h3>Sample data file with <script>document.write(window.players.length)</script> names:</h3>
Or you could use DOM methods.
<h3>Sample data file with <span id="count"></span> names:</h3>
<script>
document.querySelector("#count").innerHTML = window.players.length;
</script>

Javascript is not a "pre-processed" language, like PHP. Change your code to:
<h3>Sample data file with <span id="output"></span> names:</h3>
<script>document.getElementById("output").innerHTML = window.players.length;</script>

You cannot use template-style coding on the client side. Instead, you need to create any element that you can reference from the script and then manipulate its contents, e.g.
<h3 id="num"></h3>
<script>
document.getElementById("num").innerHTML = "Sample data file with " + window.players.length +" names"
</script>

Related

Access DOM of an imported local HTML file

I'm working on a project in which I would like to import a locally stored HTML template using JavaScript.
This template will be dynamically filled with datas that I get by accessing a website REST API.
This is an example of what I want to do :
index.html :
<!DOCTYPE html>
<html>
<head>
<title>My Site</title>
</head>
<body>
<div id="loaded-content">
<!-- Here will be displayed the template -->
</div>
</body>
<script type="text/javascript" src="script.js"></script>
</html>
template.html:
<div id="data">
<h1 id="data-name">value</h1>
<p id="first-attribute">value</p>
<p id="first-attribute">value</p>
<p id="first-attribute">value</p>
</div>
datas.json:
{
"datas":
[
{
"name": "value",
"first-attribute": "value",
"second-attribute": "value",
"third-attribute": "value"
},
{
"name": "value",
"first-attribute": "value",
"second-attribute": "value",
"third-attribute": "value"
}
]
}
For each object contained in datas, I want to display the template again.
Currently, I load the template using XMLHttpRequest object. I can display the content of my template but I can't access to the template's DOM to change the value of its elements.
Which method should I use to correctly load my HTML file ?
I'm looking for something in pure Javascript (no jQuery or something).
Thank you for your help =)
Your immediate problem is that your template as it currently stands will result in multiple elements with the same ID, which isn't allowed.
If you have control of the template, change it to be a more traditional template style where vars are bracketed off rather than relying on HTML IDs. So I'd change your template to be:
<div>
<h1>{{name}}</h1>
<p>{{first-attribute}}</p>
<p>{{second-attribute}}</p>
<p>{{third-attribute}}</p>
</div>
This way we can run string replacements via REGEX rather than outputting then interrogating the items by IDs.
Let's say #content is the container element for the templates, data stores your parsed JSON data and template stores the unparsed template string:
var
cntr = document.querySelector('#content'),
html;
//iterate over data items
data.datas.forEach(function(obj) {
//grab all var references i.e. {{foo}} and replace them with actual values, if exist
html = template.replace(/\{\{[^\}]+\}\}/g, function(match) {
var var_name = match.replace(/^\{\{|\}\}$/g, '');
return obj[var_name] || '??';
});
//append the readied HTML to the content container
cntr.innerHTML += html;
});
This is an example. You can use a JSON parser to get the data in the format you need. So here is what you do: create a dummy <div> DOM element to push later, use replace function to replace val with the value of the data variable. Then finally append this to the HTML's div element. If you got the data using an XMLHttpRequest, pass on the data to template. Then replace the placeholders value with the data from parsing JSON. And use replace method to do so. It should work fine.
var template = document.createElement("div");
var data = "Hello world";
template.innerHTML = "<h1>val</h1>";
template.innerHTML = template.innerHTML.replace("val", data);
document.getElementById("myDiv").appendChild(template);
<div id="myDiv">
</div>

Embed same web widget multiple times with different data attribute values

I want to create a web widget that can be embedded multiple times on the same page but with different data attribute values so I can display different data according to the data attribute value.
For example, I want to embed mywidget.js file multiple times as follows:
<body>
<div>
<script src="script/mywidget.js" data-sport="soccer" id="widget-soccer">
</script>
</div>
<div>
<script src="script/mywidget.js" data-sport="tennis" id="widget-tennis">
</script>
</div>
</body>
My question is, inside the code in mywidget.js, how do I determine the correct script tag reference and read it's data attribute so I can use that value to fetch the corresponding data from a web service. I am using only jquery and javascript.
I want the widget to be embeddable on other users sites as well so all they do is embed using only the script tag and passing in the desired data attribute value without adding anything extra anywhere they need on their website.
This is not really a very good approach, as it is very inflexible. But given that <script> tags, when not deferred, halt parsing of the document while they execute, the current script tag will be the last in the DOM; so you can get the current sport inside your script by using this:
var sport = $('script').last().data('sport');
However, it would be much better to define a function in your external JavaScript file, and then invoke it when you need to instantiate your widget (EDIT: like in Lee Taylor's answer).
Why don't you do something like:
<head>
<script src="script/mywidget.js"></script>
</head>
<body>
<div><script>createMyWidget({sport : "soccer"} );</div>
<div><script>createMyWidget({sport : "tennis"} );</div>
</body>
I don't think you can. I know it's not that nice, but I would try:
<div><script>sport = "soccer";</script><script src="script/mywidget.js" id="widget-soccer"></script></div>
<div><script>sport = "tennis";</script><script src="script/mywidget.js" id="widget-tennis"></script></div>
and use sport in mywidget.js
Another approach could be that myscript.js is actually a dynamic "page", let's say with php, then you could use src="script/mywidget.js?sport=swimming", and in the php you would print:
sport = "<?php echo addcslashes($_GET['sport'], '"'); ?>";
But even better would be:
<script src="script/mywidget.js"></script>
<div><script>showWidget("soccer");</script></div>
<div><script>showWidget("basketball");</script></div>
I think you can use jQuery to find all script tags with src="script/mywidget.js" or something
$('script[src="script/mywidget.js"]')
And then you'll have an array of scripts tags that you can loop through and access the data property using jQuery's .data() method.

Filling static HTML page with JSON data

I am looking for a good template library that will allow me to fill in a static HTML page with a few variables that will be in JSON format - using javascript. There will only be a few variables that change and one might be in <title></title>
Ideally I'm looking for something like:
<div>
Name: {name} is currently {age} years old
</div>
and then simply being able to supply the values for name and age via JSON and having it populated with values on the fly.
Does anyone know of a library that would work well?
Thanks in advance.
Handlebars.js is fairly simple to use
<div class="entry">
<h1>{{title}}</h1>
<div class="body">
{{body}}
</div>
</div>
Check out their docs
Why noy just use jQuery?
http://jsfiddle.net/chace/NF496/7/
var someJSONName = "Jimmy"
var someJSONAge = "32"
$("#myContent").click(function () {
$("#myContent").effect("highlight", 1500);
$("#myContent").text("Name: " + someJSONName + " is currently " + someJSONAge + " years old.");
});
Take a look at AngularJS too. Especially optimal if you're working with large datasets that can change over the lifetime of the page.
Docs: http://angularjs.org/

html template in jquery or javascript

This is a very short example, but I was wondering if there is a way of using an xml or html file with html markup instead of including it in the javascript like I do below.
I know there are template libraries out there, but I really just want to do something simple and not involve any libraries other than jQuery.
var description = this.name;
if description == 'full') {
return "<div><textarea cols='50' rows='50'>" + this.value + "</textarea></div>";
} else {
return "<div><textarea cols='50' rows='15'>" + this.value + "</textarea></div>";
};
Thanks
In general, without a template engine you have three options:
a) Adding the template directly into your markup as script tag
<script type="text/template" data-template="stats">
<div id="content">
...
</div>
</script>
The html code inside the script tag could be accessed with the following code:
$("script[data-template=" + templateName + "]").html()
The big benefit of this approach is that you are not making another http request.
b) Putting the template in external file and load it via ajax.
$.ajax({
url: "test.html"
}).done(function(html) {
...
});
c) Doing the things like you already did.
If you use AJAX to call a file, you can use the result of the file, which could be XML or nested HTML, etc etc.
I define a hidden div on my markup - then give it a generic ID, then in javascript I use the jQuery.clone() method to make a clone of that markup, and in the markup I define the template macro values that can then be injected with the real data using .replace..
HTML:
<div id="mytemplate">
Name: {0}
</div>
JS/jQuery:
var clone = $('#mytemplate').clone();
Then perform the replacements on the clone object and simply append to the DOM where desired!

How can i use html tags in javascript

I wrote an ajax program.when i am getting response, at that time i will display
that content in my web page using html tags.
So how can I use html tags in javascript?
A sample data you get from server, and a sample html you want to add would make it easier for people to help you.
The basic steps are
1.Get a reference to the html node you want to put the new data in. There are multiple strategies to get reference to the node. If it has an id, it's most starightforward.
2.set innerHTML property.
eg
var node = document.getElementById("targetNode");
node.innerHTML = "<div>data</div>";
Well... Not much detail so not much of an answer...
Easy way
document.write("<body> <div> this is on my page! </div> </body>
or you can edit the innerhtml of an element to place things inside it
document.getElementById("id").innerHTML = "<div>This is inside my element with id="id" </div>"
Answers the question, no?
Instead of embedding html into javascript, you could make a bunch of predefined javascript functions and then use them outside of the script tags. For example, here's how to display a picture while still using the javascript functions.
<html>
<script type="text/javascript">
function display_message()
{
alert("This is a message.");
};
</script>
<body>
<img src="image.jpg">
<form>
<input type="button" value="Click me!" onclick="display_message()" />
</form>
</body>
</html>
I know this is an old post, but this could be helpful...
Using jquery is great way to combine html elements with script
Note: This would be used in the body, if using it in the be sure to enclose it in
$(document).ready (function(){ YOUR CODE });
// Create an object:
var url = {
link: "https://stackoverflow.com/questions/2834929/how-can-i-use-html-tags-in-javascript"
};
// Display URL object:
$('#panel').html('<a href=' + url.link + '>' + url.link + '</a>');
//Note: the # denotes id, if you want to use a class it would be:
//$('.panel').html('<a href=' + url.link + '>' + url.link + '</a>');
//your html would be: <div id="panel"></div> or whatever you choose ie <p> and so //forth

Categories

Resources