I'm currently trying to copy a div to another browser tab with the events still working.
I found ways to do this on the same tab, but not for a different one, for example:
https://api.jquery.com/clone/
jQuery: clone elements AND events
Here's my approach:
var newWindow;
if (navigator.userAgent.match(/msie|trident/i))
{
newWindow = window.open("", "_blank");
}
else
{
newWindow = window.open("about:blank", "_blank");
}
var currentDate = moment().format(L11n.get(".dateTimeFormat"));
var printDate = L11n.get(".printDate") + " " + currentDate;
var cssUrl = $app.appRoot + "rt/main.css";
var jsUrl = $app.appRoot + "app/main.js";
var d3Url = $app.appRoot + "pub/d3.js";
var title = L11n.get(".contractDetail");
var start = "<!DOCTYPE html> \
<html xmlns=\"http://www.w3.org/1999/xhtml\" style=\"height: 100%;\"> \
<head id=\"Head1\"> \
<title>" + title + "<\/title> \
<link href=\"" + cssUrl + "\" rel=\"stylesheet\" type=\"text/css\" /> \
<script src=\"" + jsUrl + "\" language=\"javascript\" type=\"text/javascript\"></script> \
<script src=\"" + d3Url + "\" language=\"javascript\" type=\"text/javascript\"></script> \
<script src=\"pub/jquery.js\" language=\"javascript\" type=\"text/javascript\" /></script> \
<body class=\"detailTabsView limitWidthPrint\" style=\"margin-bottom: 0; margin-top: 0; height: auto;\"> \
<div class =\"detailPrintHeader\">" + printDate + "</div>\
<div class =\"detailContainer\">";
var end = "<\/div><\/body><\/html>";
newWindow.document.write(start + detailHtmlString + end);
newWindow.document.close();
//newWindow.document.$("#dashboardFrame").replaceWith($(".ALL #dashboardFrame").clone(true));
var dash = $(".ALL #dashboardFrame").clone(true, true);
$(newWindow).load(function ()
{
console.log("loaded");
$(newWindow.document.body).find("#dashboardFrame").replaceWith(dash);
});
$(newWindow.document).ready(function ()
{
console.log("ready");
});
newWindow.focus();
The interesting part is this:
var dash = $(".ALL #dashboardFrame").clone(true, true);
$(newWindow).load(function ()
{
console.log("loaded");
$(newWindow.document.body).find("#dashboardFrame").replaceWith(dash);
});
Further explanation:
I have a webapp that, for example, shows a diagram made with D3 (Data-driven-documents). It also shows other information, split up into a tab pane. That diagram has some datapoints that show a tooltip when the user hovers over them.
The app also has a button that opens the current tab in a new window. The tooltips don't work on that new window, but it would be nice if they would.
Edit:
Simple example:
Tab A = source tab, with a button in it that has a click-event bound to it. The event reads, let's say the current time and writes it to an alert box.
Then I open a new tab with javascript, let's call it Tab B. When Tab B is loaded, I want to append the button from Tab A to the body of Tab B. The event on the button still has to work in Tab B.
TL:DR:
You can only solve this by re-binding the events on the new tab in the
ready event
I tried that with this piece of code. You have to pass the event-handler within that piece of code (sry for the long-line-example). Just copy that snipped into your dev-console, paste and run it. You will get an alert();
var newWindow = window.open('about:blank', '_blank');
newWindow.document.write('<!doctype html><html><head><title>Test</title><script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script><script type="text/javascript">$(document).ready(function() { $(window).load(function(e) { alert(\'onload\'); }); });</script><script type="text/javascript">function onload() {alert("load");}</script></head><body><div>Test</div></body></html>');
newWindow.document.close();
You can't get the event from another tab. That's browser restriction. You can use an iFrame for that.
Edit:
As I said you can use an iFrame to retrieve the loaded message. But it also should be possible within a new tab. There is a window.postMessage method in HTML5. You can see which browsers are supportet on caniuse.com. You may also have a very brief look at David Walsh's site. He explains how to use it.
I do not have ressources right now. But you can simple "google" it. Or test it otherwise within your developer console to access a variable declared in windowA on windowB. The result will be undefined
Edit part 2: I don't think it is possible without having a script-ressource or a inline JavaScript in the DOM.
See example:
<!doctype html>
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#test_button').bind('click', function (e) {
alert('Button was clicked!');
e.preventDefault();
});
$(window).load(function (e) {
var body = '<!doctype html><html><head><title>Test2</title><scr' + 'ipt type=\'text/javascript\' src=\'https://code.jquery.com/jquery-2.1.4.min.js\'></scr' + 'ipt></head><body id="body">' + $('#test_button').clone(true, true).attr({'id': 'test2_button', 'data-time': new Date()}).wrap("<div />").parent().html() + '</body></html>';
console.log(body);
var newWindow = window.open('about:blank', '_blank');
newWindow.document.write(body);
//newWindow.document.write('<!doctype html><html><head><title>Test2</title><scr' + 'ipt type=\'text/javascript\' src=\'https://code.jquery.com/jquery-2.1.4.min.js\'></scr' + 'ipt></head><body>' + + '</body></html>');
newWindow.document.close();
});
});
</script>
<body>
<div id="test">
<button id="test_button">Test-Button</button>
</div>
</body>
</html>
I just copy the #test_button into the new window. As a new window is opened a new DOM is generated without the JavaScript event (bind) of the #test_button.
If you append the JavaScript for event-handling you can of course copy your hole content into a new tab/window. Just move your event-bindings into a JavaScript file and append it like I did with the jQuery-file.
Furthermore you just can open the new tab programmatically within your existing tab as you can't access the other tabs ressource (DOM).
You can pass a parameter as well if you like. Just add a param to the open. See other SO-question.
If it helped to clearify your question please feel free to mark this one as answer.
Edit 3
I hope I got it right this time! Try this one:
JavaScript-file (e. g. test.js)
$(document).ready(function () {
console.log('ready');
$('#test_button').bind('click', function (e) {
alert('Button was clicked!');
e.preventDefault();
});
})
HTML-file
<!doctype html>
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="test.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(window).load(function (e) {
var body = '<!doctype html><html><head><title>Test2</title><scr' + 'ipt type=\'text/javascript\' src=\'https://code.jquery.com/jquery-2.1.4.min.js\'></scr' + 'ipt><scr' + 'ipt type=\'text/javascript\' src=\'test.js\'></scr' + 'ipt></head><body id="body">' + $('#test_button').clone(true, true).attr({'data-time': new Date()}).wrap("<div />").parent().html() + '</body></html>';
console.log(body);
var newWindow = window.open('about:blank', '_blank');
newWindow.document.write(body);
//newWindow.document.write('<!doctype html><html><head><title>Test2</title><scr' + 'ipt type=\'text/javascript\' src=\'https://code.jquery.com/jquery-2.1.4.min.js\'></scr' + 'ipt></head><body>' + + '</body></html>');
newWindow.document.close();
});
});
</script>
<body>
<div id="test">
<button id="test_button">Test-Button</button>
</div>
</body>
</html>
Related
I know this has been asked a lot on here, but all the answers work only with jQuery and I need a solution without it.
So after I do something, my Servlet leads me to a JSP page. My JS function should populate a drop down list when the page is loaded. It only works properly when the page is refreshed tho.
As I understand this is happening because I want to populate, using innerHTML and the JS function gets called faster then my HTML page.
I also get this error in my Browser:
Uncaught TypeError: Cannot read property 'innerHTML' of null
at XMLHttpRequest.xmlHttpRequest.onreadystatechange
I had a soulution for debugging but I can't leave it in there. What I did was, every time I opened that page I automatically refreshed the whole page. But my browser asked me every time if I wanted to do this. So that is not a solution that's pretty to say the least.
Is there something I could do to prevent this?
Edit:
document.addEventListener("DOMContentLoaded", pupulateDropDown);
function pupulateDropDown() {
var servletURL = "./KategorienHolen"
let xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.onreadystatechange = function () {
if (xmlHttpRequest.readyState === 4 && xmlHttpRequest.status === 200) {
console.log(xmlHttpRequest.responseText);
let katGetter = JSON.parse(xmlHttpRequest.responseText);
JSON.stringify(katGetter);
var i;
for(i = 0; i <= katGetter.length -1; i++){
console.log(katGetter[i].id);
console.log(katGetter[i].kategorie);
console.log(katGetter[i].oberkategorie);
if (katGetter[i].oberkategorie === "B") {
document.getElementById("BKat").innerHTML += "" + katGetter[i].kategorie + "</br>";
} else if (katGetter[i].oberkategorie === "S") {
document.getElementById("SKat").innerHTML += "" + katGetter[i].kategorie + "</br>";
} else if (katGetter[i].oberkategorie ==="A") {
document.getElementById("ACat").innerHTML += "" + katGetter[i].kategorie + "</br>";
}
// document.getElementsByClassName("innerDiv").innerHTML = "" + katGetter.kategorie + "";
// document.getElementById("test123").innerHTML = "" + katGetter.kategorie + "";
}
}
};
xmlHttpRequest.open("GET", servletURL, true);
xmlHttpRequest.send();
}
It can depend on how + when you're executing the code.
<html>
<head>
<title>In Head Not Working</title>
<!-- WILL NOT WORK -->
<!--<script>
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
</script>-->
</head>
<body>
<p>Replace This</p>
<!-- Will work because the page has finished loading and this is the last thing to load on the page so it can find other elements -->
<script>
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
</script>
</body>
</html>
Additionally you could add an Event handler so when the window is fully loaded, you can then find the DOM element.
<html>
<head>
<title>In Head Working</title>
<script>
window.addEventListener('load', function () {
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
});
</script>
</head>
<body>
<p>Replace This</p>
</body>
</html>
Define your function and add an onload event to body:
<body onload="pupulateDropDown()">
<!-- ... -->
</body>
Script needs to be loaded again, I tried many options but <iframe/> works better in my case. You may try to npm import for library related to your script or you can use the following code.
<iframe
srcDoc={`
<!doctype html>
<html>
<head>
<style>[Style (If you want to)]</style>
</head>
<body>
<div>
[Your data]
<script type="text/javascript" src="[Script source]"></script>
</div>
</body>
</html>
`}
/>
Inside srcDoc, it's similar to normal HTML code.
You can load data by using ${[Your Data]} inside srcDoc.
It should work :
document.addEventListener("DOMContentLoaded", function(){
//....
});
You should be using the DOMContentLoaded event to run your code only when the document has been completely loaded and all elements have been parsed.
window.addEventListener("DOMContentLoaded", function(){
//your code here
});
Alternatively, place your script tag right before the ending body tag.
<body>
<!--body content...-->
<script>
//your code here
</script>
</body>
Am trying to create a facebook share code in just html and javascript
I would want the link to be exactly like this:
share
But the problem now is, how can I get the page title through the help of ONLY javascript and then add it to the link at t=PAGETITLE.
I think you just want to append a "?t=" parameter to the query string passed into the FB share link with the document.title. If that is correct, you can do
var shareURL = fbShareURL + encodeURIComponent(linkURL + "?t=" + document.title));
which will make a URL like
https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Flmn.9nty.com%2F%3Ft%3DTITLE
which will include the page title as a query string parameter in url-encoded form. It's up to you what you do with that query string parameter, though. Using jQuery, you can update the share link dynamically:
var fbShareURL = "http://www.facebook.com/sharer/sharer.php?u=";
var title = document.title; // The current page
var linkURL = "http://lmn.9nty.com/";
$link = $("<a>");
$link.attr("href", fbShareURL + encodeURIComponent(linkURL + "?t=" + title));
$link.text("Share");
// Add the link to your page
$("body").append($link);
Demo: http://jsfiddle.net/7wst45gq/1/
Here is full, working HTML code as requested:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>How to get current page title and add it to link directly as variable in JavaScript</title>
<script type='text/javascript' src='//code.jquery.com/jquery-1.9.1.js'></script>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
// Begin demo code
var fbShareURL = "http://www.facebook.com/sharer/sharer.php?u=";
var title = document.title; // The current page
var linkURL = "http://lmn.9nty.com/";
$link = $("<a>");
$link.attr("href", fbShareURL + encodeURIComponent(linkURL + "?t=" + title));
$link.text("Share");
// Add the link to your page
$("body").append($link);
// End demo code
});//]]>
</script>
</head>
<body></body>
</html>
sharer.php only takes the URL as parameter, the rest of the data will come from the Open Graph tags:
a href="http://www.facebook.com/sharer/sharer.php?u=http://lmn.9nty.com/">Share</a>
Btw, you should urlencode the shared URL.
I have a js rendered in HTML which would give a preview of the form. The code is functioning correctly but it gives me the output on the same page rather i want to open it in a pop-up window. I have tried using window.open () with no luck. Could you please help me out in how i can use window.open() for the below. The button ID is preview. When the button is clicked it executes a function similar to below
$("#preview").click(function() {
$("#formpreview").delete();
var fieldSet = ...................});
You can populate the html in the child window using the below example:
HTML
<!DOCTYPE Html />
<html>
<head>
<title></title>
</head>
<body>
<input type="button" id="launch" value="Launch Child Window"/>
<script type="text/javascript" src="theJS.js"></script>
</body>
</html>
JavaScript
var btnLaunch = document.getElementById("launch");
btnLaunch.onclick = function () {
var childWindow = window.open("", "", "height=500, width=500");
var html = "";
var theVariable = "Conent in Child Window";
html += "<p>" + theVariable + "</p>";
childWindow.document.body.innerHTML = html;
}
Store the popup as a variable, then set the popup's HTML to whatever you need.
$("#preview").click(function() {
var myWindow = window.open("", "Popup", "width=300, height=500");
myWindow.document.write("<html>This is where your content goes</html>");
});
I want to inject iframe head by yui3.The sample code works in FF but IE9 shows the error "YUI is not define". I don't know what happens in IE9.
<head>
<script src="http://yui.yahooapis.com/3.5.0/build/yui/yui-min.js"></script>
<script src="./test-yui.js"></script>
</head>
<body>
<iframe src="#" id="frame"></iframe>
</body>
var SC = 'script';
YUI().use('node', function (Y) {
var frame = Y.Node.getDOMNode(Y.one('#frame'));
o = frame.contentWindow.document;
o.open().write(
'<head><' + SC + ' type="text/javascript" src="http://yui.yahooapis.com/3.5.0/build``/yui/yui-min.js"></' + SC + '>'+
'<' + SC + '>YUI().use(\'tabview\', \'node\', function(Y) {});</' + SC + '>'+
'</head>'+
'<body><div class="unit_title" >HELLO WORLD</div></body>');
o.close();
});
Trying to write to iframes can be tricky I would suggest looking at the Frame module in YUI some details on using it can be found here http://www.andrewwooldridge.com/blog/2011/04/14/hidden-yui-gem-frame/
Problem
We have page with form.
User fill the form and submit it.
I need to print page with data from form and some other content.
Code #1
$(document).ready(function($){
$('input[name=sumb_but]').bind('click', function(e){
e.preventDefault();
var print_text = "<p>Test " + $('#form').serialize() + "</p>";
var newWin = window.open('','printWindow','Toolbar=0,Location=0,Directories=0,Status=0,Menubar=0,Scrollbars=0,Resizable=0');
newWin.document.body.innerHTML = print_text;
newWin.print();
});
});
Cool, but:
I need specific css
Print window appear before content was loaded... ooops
Ok!
Code #2
$(document).ready(function($){
$('input[name=sumb_but]').bind('click', function(e){
e.preventDefault();
var print_text = "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'> <html xmlns='http://www.w3.org/1999/xhtml'> <head> <meta http-equiv='Content-Type' content='text/html; charset=windows-1251' /> <title>Оформление доверенности (простая письменная форма)</title> <link rel='stylesheet' type='text/css' href='/css/print_forms/warrant.css'> </head> <body> <p>Test " + $('#form').serialize() + "</p></body><script type='text/javascript'>window.print();</script></html>";
var newWin = window.open('','printWindow','Toolbar=0,Location=0,Directories=0,Status=0,Menubar=0,Scrollbars=0,Resizable=0');
newWin.document.write(print_text);
});
});
document.write - in other case css not loading
At the and of content added "window.print()"
That works fine in all browsers, but not in IE - windows with content loading successfully without printing dialog.
I need help!
p.s.
CSS with media="print" - not good solution for this case for some reason.
$(document).ready(function($){
$('input[name=sumb_but]').bind('click', function(e){
e.preventDefault();
var print_text = "<p>Test " + $('#form').serialize() + "</p>";
var newWin = window.open('','printWindow','Toolbar=0,Location=0,Directories=0,Status=0,Menubar=0,Scrollbars=0,Resizable=0');
newWin.document.body.innerHTML = print_text;
newWin.document.body.onload = function() { newWin.print(); }
});
});
this could help