I have several templates for faceboxes (lightbox) that I need at different points of the application. These are stored in different partials and files.
I will initialize different javascript functions in accordance to which ones I need. The question is, what is the best way to append the external HTML page into my body using javascript?
Since you tagged the question with it, here's a jQuery solution.
$("body").append("text");
Remember that the parameter can also be a DOM element. So you can do this :
var p = $("<p/>").text("a paragraph");
$("body").append(p);
the easy way with jQuery is:
$('#result').load('test.html');
<div id="result"><!--/ Hold My Data! /--></div>
obviously you can change #result with body
Also you can try some templates library..
Like handlebar and underscore..
and append in the el provided by backbone.js
Suppose you want to append this html in your template, then you can use the below code according to your application
Consider the code
Example 1:
rowData += '<div style="width: 130px;">'+param1+'</div>';
rowData += '<div style="width: 130px;">'+param2+'</div>';
$('#ID').html(rowData);
and please make sure that the js should be include in that file.
Here is the information of variable used above:
row data - the html that you want to append,
param- if you want to show the value of java script variable on browser dynamically,
#ID- ID of the div in which you want to append this html
example 2:
Consider the following HTML:
<h2>Hello World</h2>
<div class="user">
<div class="inner">Hi</div>
<div class="inner">Bye</div>
</div>
You can create content and insert it into several elements at once:
$( ".inner" ).append( "<p>Lorem Ipsum</p>" );
Related
That title might be a little confusing but I don't know how to put it otherwise. I have some JSON encoded data in a .json-file:
{"foo":"bar", "bar":"foo", "far":"boo"}
and some HTML content in a .html-file:
<h1>I'm a Title</h1>
<p>Lorem Ipsum</p>
<br>
<img src="./media/foo.png">
There is a jQuery script that takes the data from both files ($.getJSON() and $(#div).load()) and creates a page with some predefined head, uses the html as content and the json data to create some buttons (key=destination & value=name) on there.
Because the project has many of these pages I would love to have only one file that holds both my HTML content AND the JSON data so I had all I needed for one page would be a single file access. So the question really is: How can I store both JSON and HTML data in one file so jQuery can access, distinguish and process it?
This is part of an electron application but I'm not sure if that even matters for that question.
The content of the json file assuming it is a json object can be assigned to a javascript variable in the html document in a script tag.
Then to refer to, for example foo, you use theJsonObject.foo;
With the following javascript snipet you can see inthe browser's console the name of each property an the value.
How you mix this in your current code depends on how you are writting it. But make sure the variable is declared before you use it.
for (let prop in theJsonObject) {
console.log( prop + ": " + theJsonObject[prop] );
};
<html>
<head>
....
<script>
var theJsonObject = {"foo":"bar", "bar":"foo", "far":"boo"};
</script>
</head>
<body>
....
</body>
</html>
I'm trying to achieve something similar to what JSRender does, but I'm not sure how to go about it. Consider the HTML "template" below:
<!DOCTYPE html>
<body>
<div class="content">
<div class="notifications">{{:notifications}} notifications</div>
<div class="something else">this is {{:something_else}} to show</div>
</div>
</body>
</html>
Supposed I have JSON data like so:
{"notifications": "3", "something_else": "some arbitrary data"}
How do I populated this data into the HTML page? The way JSRender does it seems to involve creating a separate template in a <script> tag, then populating the data into the template and finally copying the template into an empty container. Is there a way to avoid this template redefinition? I believe my HTML page can already act like a template as demonstrated above.
The Question: is it possible to display JSON data into a ready HTML page (such as above) with defined "data positions"? As part of the challenge, using $('.notifications').html()-related methods should be avoided since this would be cumbersome when handling large extensive data.
You can do that using top-level JsViews top-level data-linking - with an element such as a <span> for each insertion point.
<div class="content">
<div >this is <span data-link="something_else></span> to show</div>
...
Code:
$.link(true, ".content", data);
In addition, the data is data-bound to the HTML.
Here is a sample which shows the data-binding by letting you actually change a data property dynamically:
It also shows data-linking to the src and title attributes of an <img> tag. See here for more information about different data-link targets.
var data = {notifications: "3", something_else: "some arbitrary data",
imgData: {img1: {src: "http://www.jsviews.com//icons/android-chrome-36x36.png",
desc: "some image"}}};
$.link(true, ".content", data, {replace: true});
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsviews/0.9.90/jsviews.js"></script>
<div class="content">
<div ><span data-link="notifications"></span> notifications</div>
<div >this is <span data-link="something_else"></span> to show</div>
<img data-link="src{:imgData.img1.src} title{:imgData.img1.desc}"/>
<br/>Edit: <input data-link="something_else"/>
</div>
While BorisMoore's answer addresses the question adequately, I crafted a "hack" that also appears to work with the ability to support attributes on almost all elements, though I don't know to what extent it is reliable.
However, this requires one to change the data structure to also indicate the type of element and even the part of it (attribute) where the data is to be inserted. The data would need to look like so:
{"notifications": "span:|3", "something_else": "span:|some arbitrary data", "avatar":"img.alt:|A"}
Then in JQuery, one could do something like so:
$.each(data, function(key, value) {
value = value.split(":|");
var element = value[0];
value = value[1];
if(element.indexOf('.') == -1){
var content = $(element + ':contains("{{:'+key+'}}")').last().html().replace("{{:"+key+"}}", value);
$(element + ':contains("{{:'+key+'}}")').html(content);
}else{
element = element.split('.');
var attribute = element[1];
element = element[0];
$(element + '['+attribute+'="{{:'+key+'}}"]').last().attr(attribute, value);
}
});
EDIT: The main drawback of this method is that it unbinds all attached events when an elements property is modifed this way.
I'm trying to make a javascript function that displays different string every 7 days for example. And I want to display that string in a footer of an html.
The part that bugs me is how to insert that string in a paragraph in html (or anything that will display the text).
I have 2 dimensional array in .js, let's say:
array = [[first1,first2],[second1,second2],[third1,third2],[fourth1,fourth2],[fifth1,fifth2]];
And I want do display, let's say
array[2][0] in one paragraph and
array[2][1] in another paragraph.
let's say
<div>
<p>In here i want array[2][0]</p>
<p>In here i want array[2][1]</p>
</div>
Please help.
HTML:
<div>
<p>In here i want <span id="placeholder-1"></span></p>
<p>In here i want <span id="placeholder-2"></span></p>
</div>
JS:
document.getElementById('placeholder-1').innerHTML = array[2][0];
document.getElementById('placeholder-2').innerHTML = array[2][1];
Fiddle: http://jsfiddle.net/8N95j/
select the html element by document.getElementById/getElementsByClassName and attach the js value like
var ele = document.getElementById('footerid');
ele.innerHTML += array[2][0];
note: getElementsByClassName would give u an array
update
here is a working fiddle using the same markup u shared.
One different approach would be to use a framework like Ember or AngularJS. These are quite easy to put in place nowadays, and leads to much easier to maintain code. For instance, your HTML would look like
<div ng-controller='MyController'>
<p>In here i want {{ array[2][0] }}</p>
<p>In here i want {{ array[2][1] }}</p>
</div>
where MyController references an AngularJS controller (basically a simple javascript object which defines a $scope in which the array is defined.
At that point, you no longer need to update the HTML, ever. Whenever your javascript does something like array[2][0] = 'foo' the HTML is automatically updated in real-time.
Use the below code to dynamically create a p tag and append it in a container div
HTML :
<div id="container">
<p>In here i want Test1</p>
</div>
JS :
var array = [['first1','first2'],['second1','second2'],['third1','third2'],['fourth1','fourth2'],['fifth1','fifth2']];
//If needed for loop can start here
var para = document.createElement("p");
para.innerHTML = 'In here i want ' + array[2][0];
document.getElementById('container').appendChild(para);
DEMO
I have seen html templates created using any of the following tags
<textarea>
<script>
<div>
Which one is better and why?
Which of the following way of creating html templates is better and y?
CSS:
.template {
display: none;
}
textarea :
<textarea class="template" id="tmpl1">
<div>adfsdfsdfs</div>
</textarea>
script :
<script type="text/html" id="tmpl1">
<div>adfsdfsdfs</div>
</script>
div :
<div class="template" id="tmpl1">
<div>adfsdfsdfs</div>
</div>
I had faced problem with script tag here
i would suggest none of the above options take a look at Mustache it was created by one of the founders of git hub
http://mustache.github.com/
definitely my favorite way to do html templating
They are all poor choices.
textarea is designed to accept user input
div elements are designed to present content to the user
script elements are designed to hold programs
If you want to embed a template into an HTML document, then I'd write a JavaScript program to store it in a variable (and use a json serializer to generate the JavaScript literal that gets assigned to that variable). That program can then go in a script element.
Alternatively, store the template in a data-* attribute on an appropriate element.
With jQuery templates, I'm trying to use the {{wrap}} template tag to wrap the results of another template. This second template renders plain text, not HTML. I currently get an empty string where I expect to get the plain text rendered by the wrapped template.
If I surround the plain text with some HTML elements, like a <div> tag, then everything works fine, but I get the <div> rendered into the results. I would be fine creating a dummy tag around my contents in order to get the {{html}} tag to work, but I wouldn't want it in the rendered results.
I will also want to use this same wrapper, if possible to wrap templates that actually do produce HTML as well, so it would be good if the same wrapper template can work for both cases.
Here is my code:
$("#x").html($("#myTmpl").tmpl());
<div id="x" />
<script id="myTmpl" type="text/x-jquery-tmpl">
The following wraps some non-HTML content: {{wrap "#wrapper"}} help {{/wrap}}
</script>
<script id="wrapper" type="text/x-jquery-tmpl">
<table>
<tbody>
<tr>
<td>
Wrapped content: {{html $item.html}}
</td>
</tr>
</tbody>
</table>
</script>
This code can be found at this jsFiddle: http://jsfiddle.net/bernardchen1/BYdeg/
I eventually found a solution. I created use a dummy tag to wrap the plain text (or even the html that is produced by other templates), and then I created a function that I pass into the template invocation that can strip out the dummy tag. I invoke it like this: {{html $data.clean($item)}}. The "clean" function needs access to the content being returned by the inner template, which I found to be $item.wrapped[0]. Once I had that content, I could get its inner html to return from the clean function.
I'm concerned about whether I'm supposed to be accessing $item.wrapped though.
Ultimately, I may just try refactoring my code to not require this dummy tag and the cleaning function.
This solution can be found here: http://jsfiddle.net/bernardchen1/nmzWt/
Edit: there is another solution to call appendTo to attach the template html to another DOM element, and then grab the data back out.