jQuery: creating HTML pages

Creating new HTML pages with jQuery is easy if we use some of the old techniques provided by core JavaScript objects and methods. For example, we can combine together window.open() and the open(), write() and close() methods of the document object to create brand new HTML pages on the fly. Remember that there's nothing wrong with these methods, except for the fact that the write() method doesn't work with XHTML documents served as application/xhtml+xml. Beside that, you can use them without worrying too much because they work reliably on all browsers. Let's see how:

$(document).ready(function() {

  var content = '<style>html {background: gray} body {
                  margin: 2em auto; padding: 
                 2em 1em; width: 40em; background: white;}</style>' +
                 '<h1>New Content</h1>' +
                 '<p>Test</p>';
  
  $('#open').click(function(e) {
  
    var win = window.open('');
    win.document.open();
    win.document.write(content);
    win.document.close();
    
    e.preventDefault();
  
  });

});

First, we've created the new content to be inserted in our page. Then we've created a blank new window by calling the window.open() method without parameters. Using this window as a reference, we've called the open(), write() and close() methods of the document object which now refers to the newly created window. You can see a demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.