javascript - Open a new page with div contents -


i have hidden divs in html page specific ids:

<div id='log1' style='visibility: hidden;display: none;'>content</div> <div id='log2' style='visibility: hidden;display: none;'>content</div> 

and links:

<a href='?' target='_blank'>log 1</a> <a href='?' target='_blank'>log 2</a> 

i want browser open new page / tab (or popup might bad if user has popup blockers) contents of corresponding div.

i know javascript create floating div , show data in same page, i'd avoid that. moreover, if there way of doing ask without js (which doubt) better.

you can't popup based on hidden divs in html without using javascript, no. there's css trick if put divs far off page , give them id, link anchor, browser scroll view.

on javascript side, it's straightforward. first, add data-log attribute them tell log should show, then:

var links = document.queryselectorall("...some selectors links..."); array.prototype.foreach.call(links, function(link) {     link.onclick = function() {         var log = document.getelementbyid(this.getattribute("data-log"));         var wnd = window.open("", "_blank");         wnd.document.write(             "<!doctype html>" +             "<html><head>" +             "<meta charset='appropriate charset here'>" +             "<title>title here</title>" +             "</head><body>" +             "<div>" + log.innerhtml + "</div>" +             "</body></html>"         );         wnd.document.close();         return false; // prevents default action of following link     }; }); 

note window.open must done within click handler; popup blockers allow popup if it's in direct response user action.

window.open returns reference window, , can write document.


(i don't use onclick handlers, didn't mention using library , there's still lot of ie8 out there. using onclick lets use return false prevent default; details in small article on anemic little blog.)


Comments