Using Javascript to add HTML? - javascript

I was wondering if it was possible to get Javascript to write some HTML onto the page in a certain DIV.
This is due to the fact, there are certain areas of the site where i don't have access to the markup. But i would like to add a small section there.
For example the container i want to add some html to is
<div id="topics"></div>
Is it possible to get Javascript to do this
<*div id="topics"> <div id="mysection"> </div> <*/div>
Many thanks!

This is fairly simple to do, even using plain JavaScript.
var topicsDiv = document.getElementById("topics");
topicsDiv.innerHTML = '<div id="mysection"> </div>';
If you're going to be doing some serious DOM (Document Object Model, i.e. HTML structure) manipulation, however, then I would recommend you look into using the JQuery library. Yet if the task is limited to your question, then normal JavaScript should be fine, as shown above.

With simple Javascript (without JQuery or something you could do):
HTML:
<div id="topics"></div>
JS:
document.getElementById('topics').innerHTML = '<div id="mysection"></div>';
Using JQuery you would simply do:
$('#topics').append('<div id="mysection"></div>');

Of course. For example, you can do this using Prototype:
$('topics').update('<div id="mysection"></div>');
The syntax is quite similar for jQuery or another frameworks, and as Noldorin noted, you can do also this without any framework.

You are probably looking for the innerHTML property
document.getElementById('topics').innerHTML = 'whatever';

I agree with both Noldorin and Can Berk Güder and others, and I'd like to quote that this is DOM (Document Object Model) and one of the main components of AJAX.
AJAX send a request to a server, and uses techniques such as this to "put it" in the page.
Know that you can do almost anything with javascript; you could just have "<html><body></body></html>" and have javascript do ALL the rest. This is what GWT does, and if you need to HEAVILY modify you page dynamically, you may be interested in it.

Related

JavaScript HTML injection efficiency/best practice

I'm looking to inject HTML via JavaScript into a page at work.
What I'd like to know is if injecting a re-write of the page is more or less efficient than injecting snippets throughout the page with methods like getElementById().
For example:
document.getElementById("Example").innerHTML = '<h2 id="Example" name="Example">Text</H2>'
document.getElementsByClassName("Example").innerHTML = '<H1>Test</H1>'
...etc. Is this more efficient/effective than simply injecting my own version of the entire page's HTML start to finish?
Edit: Per Lix's comment, I should clarify that I likely will be injecting a large amount of content into the page, but it will affect no more than a dozen elements at any time.
If your project can manage it, it could be better to create DOM Elements and append them to the tree.
The big problem with efficiency would be that setting .innerHTML property would first remove all the nodes and only then parse the html and append it to the DOM.
It's obvious that you should avoid removing and the re-appending identical elements, so if you're sure the "Example" elements would always remain on the page, your way of setting them seems to be a nice optimazation.
If you want to optimize it even further, you could parse the html you want to append to nodes and have a function that checks which ones should be appended and which one shouldn't. But be aware that accessing the DOM is costly. Read more about the ECMA-DOM bridge.
Edit: In some cases it might be better to let the browser do the html parsing and injecting through innerHTML. It depends on the amount of HTML you're inserting and the amount you're deleting. See #Nelson Menezes's comments about innerHTML vs. append.
Depends on the context. If it was only decoration of existing content, then your proposal would suffice. I'd use jQuery anyway, but that's only my preference.
But when injecting the actual content you have two concerns:
maintainability - Make the structure of your code readable and subject to easy change when you need (and you will need).
accessibility - When javascript is disabled, then no content will be visible at all. You should provide a link to desired content in <noscript/> tag or ensure accessibility to everyone any other way you prefer. That's a minority of internet users at the moment, but for professional webmasters they make it count.
To address both of above concerns I prefer to use ajax to load a whole page, some part or even plaintext into existing element. It makes it readable, 'cause the content is sitting in another file completely separated from the script. And since it's a file, you may redirect to it directly when javascript is disabled. It makes the content accessible to anyone.
For plain javascript you'd have to use XMLHttpRequest object, like here.
With jQuery it's even simpler. Depending on what you need you may use .load, .get or .ajax.
Best practice today is using JQuery Manipulation functions.
Most time you'd use one of this 3 functions :
Replace existing HTML node:
$("div").html("New content");
Append a sibling node:
$("div").append("New content");
Remove a node:
$("div").remove();

Advantages Of Putting HTML in Javascript

I am wondering if it is better to put your html in javascript or in your html files.
For example having my js file have this
$('<div>').addClass('test').append(
$('<p>').text('test1'),
$('<span>').text('test2'),
$('<span>').text('test3')
).insertAfter( $('#test1') );
VS
My html file looking like this
<div id="#test1"></div>
<div class="test">
<p>test1</p>
<span>test2</span>
<span>test3</span>
</div>
and the js file have:
$('.test').show();
Highly subjective and depends on contexts of course.
In a web page, most of the content is already known. No reason not to just put the content in the HTML and use CSS (and maybe Javascript when really needed) to style in.
In a web application, however, things are not so well known. The document is much more dynamic and using Javascript to add/remove elements is required.
BTW, your two pieces of code do two different things. In the first example you give it a class of test and in the second you are giving it an ID of #test1. This is an invalid ID and should be test1. The selector for that ID would be #test1 which may be causing some of the confusion.
This is probably okay for just straight-up webpages, but for web applications you should really look into a templating system such as mustache.js(https://github.com/janl/mustache.js) or Handlebars.js(http://handlebarsjs.com/).
That way, you can keep your HTML in external template files and use Javascript objects and arrays to fill them with data. For example, a mustache template might look like:
<div id="{{id}}"></div>
<div class="{{class}}">
<p>{{name}}</p>
<span>{{prop1}}</span>
<span>{{prop2}}</span>
</div>
And you would have an object that looks like this to fill it:
var obj = {
id: "myID",
class: "some classes",
name: "Martin Brennan",
prop1: "whatever",
prop2: 22
}
And you would use the template with the object like this (after loading the template into a variable):
Mustache.render(template, obj)
Like Jeremy J Starcher said though, this is highly subjective, and I would suggested that you give templating systems a try to see if you can see the value in using them in your project(s).
Of course the second option is much better and faster.
If you use
$('<div>').addClass('test').append(
$('<p>').text('test1'),
$('<span>').text('test2'),
$('<span>').text('test3')
).insertAfter( $('#test1') );
browser must parse JavaScript. And each time you use $() you are creating an object which has a lot of properties and methods which you don't use (useless!). And of course the browser must parse the HTML too.
But if you use
<div id="#test1"></div>
<div class="test">
<p>test1</p>
<span>test2</span>
<span>test3</span>
</div>
browser only has to parse HTML and it's much faster.
One of the largest benefits of using the 2nd, hard-coded HTML method is that it'll still show up for people with JavaScript disabled. It's hard to verify exactly how many users don't have JS enabled (because most trackers use JS..) but last guesstimate I heard was somewhere around 5% of internet users.
Moral of the story - make your site work without JavaScript. Then and only then add JavaScript to make it look prettier/ add additional (non essential) features.
The simple answer is that static content should be created using normal markup, while Javascript should be used for dynamic content.
Also, in many cases you can use both. You can have static HTML markup with style="display:none", and then use Javascript to change the style to make it appear and disappear as needed.

Trying to implement a countdowntimer in DOM

I want to implement a timer in DOM but I don't want to use any Javascript. Is this actually possible?
I already have the code in Javascript but I would like to change it to DOM so that I don't have to activate JS.
Thanks for any help :D
The only way to reliably modify the Document Object Model is with JavaScript. DOM is just a structure for accessing parts of a webpage, nothing more.
So unless you have a vendetta against JavaScript and would rather using something like client side VBscript (IE only) you have to use JavaScript.
If you just want to get a similar effect you could try playing with CSS pseudo-elements which I doubt will cover your needs. Also CSS pseudo-elements aren't really part of the page so there are quirks; pseudo-element text cannot be selected for example.
In short, you must use JavaScript to "use" DOM, its a structure, not a language.

Do I need somehow "prepare" my HTML before moving on to making my page more sexy with jQuery?

Do I need somehow "prepare" my HTML before moving on to making my page more sexy with jQuery?
What I mean is there some rule that says that HTML modification with jQuery is easier when HTML has "this" and "that" and "that too"? Some "HTML design patterns" like we have in C++ for example?
My HTML is generated by PHP application from templates and data retrieved from mySql database, and it is styled with CSS so I have ids and classes and almost all "components" on pages are inside divs (with id or class or both) so I presume that it is "jQuery ready" but maybe I should add something more to HTML or think about something?
I mostly have a complete vision what I want to accomplish with jQuery and how page should look like and behave when I finish so it is "only" matter of implementing it but I don't want to get too deep and suddenly discover that if I done something at the beginning my work would be easier and faster.
One advice: generate valid HTML according to whatever DOCTYPE you are using and have fun with jquery. Also avoid mixing markup and javascript: keep them separate and progressively enhance your markup with javascript features.
What you need to do is create a bare HTML page that is usable as-is, meaning, no Javascript required to operate it – that's the ideal anyway, building a web app usually means there's a dependency on Javascript, but you should only use JS when necessary.
Adding Javascript should only enhance your UI while CSS should add the presentation on top of the existing HTML structure. In other words, an HTML page without CSS and Javascript should look and read well.

Is there a way to create your own HTML element?

Is there a way to create your own HTML element? I want to make a specially designed check box.
I imagine such a thing would be done in JavaScript. Something akin to document.createHTMLElement but the ability to design your own element (and tag).
No, there isn't.
The HTML elements are limited to what the browser will handle. That is to say, if you created a custom firefox plugin, and then had it handle your special tag, then you "could" do it, for varying interpretations of "doing it". A list of all elements for a particular version of HTML may be found here: http://www.w3.org/TR/html4/index/elements.html
Probably, however, you don't actually want to. If you want to "combine" several existing elements in such a way as they operate together, then you can do that very JavaScript. For example, if you'd like a checkbox to, when clicked, show a dropdown list somewhere, populated with various things, you may do that.
Perhaps you may like to elaborate on what you actually want to achieve, and we can help further.
Yes, you can create your own tags. You have to create a Schema and import it on your page, and write a JavaScript layer to convert your new tags into existing HTML tags.
An example is fbml (Facebook Markup Language), which includes a schema and a JavaScript layer that Facebook wrote. See this: Open Graph protocol.
Using it you can make a like button really easily:
<fb:like href="http://developers.facebook.com/" width="450" height="80"/>
The easiest way would be probably to write a plugin say in Jquery (or Dojo, MooTools, pick one).
In case of jQuery you can find some plugins here http://plugins.jquery.com/ and use them as a sample.
You need to write own doctype or/and use own namespace to do this.
http://msdn.microsoft.com/en-us/magazine/cc301515.aspx
No, there is not. Moreover it is not allowed in HTML5.
Take a look at Ample SDK JavaScript GUI library that enables any custom elements or event namespaces client-side (this way XUL for example was implemented there) without interferring with the rules of HTML5.
Take a look into for example how XUL scale element implemented: http://github.com/clientside/amplesdk/blob/master/ample/languages/xul/elements/scale.js and its default stylesheet: http://github.com/clientside/amplesdk/blob/master/ample/languages/xul/themes/default/input.css
It's a valid question, but I think the name of the game from the UI side is progressive markup. Build out valid w3 compliant tags and then style them appropriately with javascript (in my case Jquery or Dojo) and CSS. A well-written block of CSS can be reused over and over (my favorite case is Jquery UI with themeroller) and style nearly any element on the page with just a one or two-word addition to the class declaration.
Here's some good Jquery/Javascript/CSS solutions that are relatively simple:
http://www.filamentgroup.com/examples/customInput/
http://aaronweyenberg.com/90/pretty-checkboxes-with-jquery
http://www.protofunc.com/scripts/jquery/checkbox-radiobutton/
Here's the spec for the upcoming (and promising) JqueryUI update for form elements:http://wiki.jqueryui.com/Checkbox
If you needed to validate input, this is an easy way to get inline validation with a single class or id tag: http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/
Ok, so my solution isn't a 10 character, one line solution. However, Jquery Code aside, each individual tag wouldn't be much more than:
<input type="checkbox" id="theid">
So, while there would be a medium chunk of Jquery code, the individual elements would be very small, which is important if you're repeating it 250 times (programmatically) as my last project required. It's easy to code, degrades well, validates well, and because progressive markup would be on the user's end, have virtually no cost on the server end.
My current project is in Symfony--not my choice--which uses complex, bulky server-side tags to render form elements, validate, do javascript onclick, style, etc. This seems like what you were asking for at first....and let me tell you, it's CLUNKY. One tag to call a link can be 10 lines of code long! After being forced to do it, I'm not a fan.
Hm. The first thought is that you could create your own element and do a transformation with XSLT to the valid HTML then.
With the emergence of the emerging W3 Web Components standard, specifically the Custom Elements spec, you can now create your own custom HTML elements and register them with the parser with the document.register() DOM method.
X-Tag is a helpful sugar library, developed by Mozilla, that makes it even easier to work with Web Components, have a look: X-Tags.org

Categories