Closing a JavaScript window with an onclick event - javascript

We have to make a JavaScript that opens a new Window, and then you need to be able to close it again with a click inside the window.
But my code does not work, could someone please provide me an answer to how this is done best?
function swipe() {
var largeImage = document.getElementById('largeImage');
var url = largeImage.getAttribute('src');
var w = largeImage.naturalWidth;
var h = largeImage.naturalHeight;
window.open(url,"Image", "height="+ h +", width="+ w +", resizable=yes");
var myWindow = window.self;
myWindow.addEventListener("click", clickHandler);
var elementIsClicked = false;
function clickHandler(){
elementIsClicked = true
}
function isElementClicked (){
if(elementIsClicked){
newWindow.close();
}
}
setInterval(isElementClicked, 500);
}

A comment says that newWindow is not defined anywhere. I think you meant to use the myWindow object. myWindow.close() will work, since it closes the window.
If you want to execute this when this first loads, you should put this in a window.onload function or a self-invoking function. Also, for full compatibility within all browsers, you should omit the resizable=yes part, because that is supported in only IE.
Also, if you want to use jQuery, you can execute this method within an $(window).load() function.

You can utilize document.write()
window.onload = function() {
var largeImage = document.getElementById("largeImage");
// var url = largeImage.getAttribute('src');
var w = largeImage.naturalWidth;
var h = largeImage.naturalHeight;
// open blank `window`
var popup = window.open("", "Image"
, "height="+ h
+", width="+ w
+", resizable=yes");
// write `img` `outerHTML` to `popup` `window`
popup.document.write(largeImage.outerHTML);
window.onclick = function() {
// close `popup`
popup.document.write("<script>this.close()<\/script>");
// remove `onclick` handler
this.onclick = null;
}
}
plnkr http://plnkr.co/edit/0KUPw3UlEF0ONO1vDoOU?p=preview

var newWindow;
function windowOpener() {
var url = "http://stackoverflow.com/questions/36387144/closing-a-javascript-window-with-an-onclick-event";
newWindow = window.open(url, "Popup", "width=700,height=500");
var timer = setInterval(function() {
if (newWindow.closed) {
alert("window closed");
clearInterval(timer);
}
}, 250)
}
<button onclick="windowOpener();">Open a window</button>
Here is the code for opening and detecting whenever it closes.
Here is the sample code on codepen.io http://codepen.io/sujeetkrjaiswal/pen/vGebqy
The code is not runnig in the stackoverflow for some reason, try it on codepen.

Thank you all for your answers.
Here is the solution to my problem:
function swipe() {
var largeImage = document.getElementById('largeImage');
var url = largeImage.getAttribute('src');
var w = largeImage.naturalWidth;
var h = largeImage.naturalHeight;
var popup = window.open(url,"Image", "height="+ h +", width="+ w +", resizable=yes");
popup.document.write('<img src="women_running_small.jpg" id="largeImage" style="width:95% ;height:95%; object-fit:contain"/>');
popup.onclick = function() {
// close `popup`
popup.document.write("<script>this.close()<\/script>");
// remove `onclick` handler
this.onclick = null;
}
}

Related

javascript code is not opening in new tab

I've come across many forum posts regarding opening window as a new tab instead of new window but no use. When I click on a link/something.. at present it is opening in a new window but i want a tab instead of window.
Here is my sample code:
$(document).on('click', '#myTabs li', function (event) {
if ($(event.target).attr('class') != 'closeIcon') {
var temp_id = $(this).attr('id');
selectedId = temp_id.substring(0, temp_id.length - 6);
$('input:radio[id=all]').prop('checked', true);
loadAll();
}
});
function loadAll() {
var clientForm = document.createElement("form");
var target = "Map" + (windowCount++);
clientForm.target = target;
clientForm.method = "POST"; // or "post" if appropriate
clientForm.action = "../Test.jsp";
var idInput = document.createElement("input");
idInput.type = "hidden";
idInput.name = "id";
idInput.value = id;
clientForm.appendChild(idInput);
document.body.appendChild(clientForm);
var nameDisplay = document.createElement("input");
nameDisplay.type = "hidden";
nameDisplay.name = "idText";
nameDisplay.value = idText;
clientForm.appendChild(nameDisplay);
document.body.appendChild(clientForm);
var dateDisplay = document.createElement("input");
dateDisplay.type = "hidden";
dateDisplay.name = "dateText";
dateDisplay.value = dateText;
clientForm.appendChild(dateDisplay);
document.body.appendChild(clientForm);
map = window.open('', target, '_blank');
map = window.open("", target, "status=0,title=0,height=600,width=800,scrollbars=1");
if (map) {
clientForm.submit();
} else {
alert('You must allow popups for this map to work.');
}
}
I see this line in your code, which specifies width and height of the new window:
map = window.open("", target, "status=0, title=0,height=600,width=800,scrollbars=1");
When you specify a width and a height the browser will always open in a new window instead of a new tab.
If you specify three parameters, your statement will always open a new window, not a new tab.
Your statement should probably read:
window.open(<URL>, '_blank');
You can find more details here.

Why does closing a window in Indesign doesn't work?

I have a question concerning Indesign script.
Why does it work, when you close a window like:
submitButton.onClick = function(){
close();
}
But when I try to execute a function afterwards like:
submitButton.onClick = function(){
close();
tagElements();
}
(note I am using the "with" tag, so no window.close() is needed)
The window does not close? Am I forgetting about something here? Shouldn't the window close, and then execute the function?
The window is initialized like:
var de = new Window('dialog', 'Descriptions');
Replacing close() with de.close() should do the trick. This works for me;
var de = new Window('dialog', 'Descriptions');
btn = de.add('button', undefined, 'close');
btn.onClick = function() {
de.close();
alert('foo');
}
de.show();
You may have to add a delay after closing (not tried):
function pause(msec) {
var done = null;
var date = new Date();
var curDate = null;
do curDate = new Date();
while(curDate-date < msec);
var done = 1;
return done;
}
submitButton.onClick = function(){
close();
pause(500);
tagElements();
}
You need the reference to the Opened window in the code.
submitButton.onClick = function(){
de.close();
tagElements();
}
should work
The following has done the trick:
with(de)
submitButton.onClick = function(){
close(1);
}
}
if(de.show){
tagElements();
}
de.show will be true, when you pass '1' in the close function( 1 == true). On you close button you would just add 'close()' and the if statement will be false.

Copy/Paste element with jQuery

I have a div that I'm appending to another div when a button is clicked. I'm also calling a bunch of functions on the div that gets created.
HTML
<a onClick="drawRect();">Rect</a>
JS
function drawRect(){
var elemRect = document.createElement('div');
elemRect.className = 'elem elemRect';
elemRect.style.position = "absolute";
elemRect.style.background = "#ecf0f1";
elemRect.style.width = "100%";
elemRect.style.height = "100%";
elemRect.style.opacity = "100";
renderUIObject(elemRect);
$('.elemContainer').draggableParent();
$('.elemContainer').resizableParent();
makeDeselectable();
handleDblClick();
}
var createDefaultElement = function() {
..
..
};
var handleDblClick = function() {
..
..
};
var renderUIObject = function(object) {
..
..
};
var makeDeselectable = function() {
..
..
};
I could clone the element when the browser detects a keydown event
$(window).keydown(function(e) {
if (e.keyCode == 77) {
$('.ui-selected').clone();
return false;
}
});
then append it to #canvas. But the problem is, none of the functions I mentioned above get called with this method.
How can I copy/paste an element (by pressing CMD+C then CMD+V) and call those above functions on the cloned element?
The jQuery.clone method returns the cloned node. So you could adjust your code to do something like this:
var myNodes = $('.ui-selected').clone();
myNodes.each(function () {
createDefaultElement(this);
appendResizeHandles(this);
appendOutline(this);
});

Set title in the window popup

Is it possible to set a title in the window popup?
I have this in javascript:
var popup = window.open('......');
popup.document.title = "my title";
but this does not work..still can't see any title
EDIT: the page popup is displaying is .aspx and it HAS a title tag, but still can't see that on the popup window..
Since popup.onload does not seem to work, here is a workaround: http://jsfiddle.net/WJdbk/.
var win = window.open('', 'foo', ''); // open popup
function check() {
if(win.document) { // if loaded
win.document.title = "test"; // set title
} else { // if not loaded yet
setTimeout(check, 10); // check in another 10ms
}
}
check(); // start checking
I was having problems with the accepted answer until I realized that if you open an existing, slow page that already has a <title> the browser will 1) set your title, then 2) once the document fully loads it will (re)set the popup title with the "normal" value.
So, introducing a reasonable delay (function openPopupWithTitle):
var overridePopupTitle = function(popup, title, delayFinal, delayRepeat) {
// https://stackoverflow.com/a/7501545/1037948
// delay writing the title until after it's fully loaded,
// because the webpage's actual title may take some time to appear
if(popup.document) setTimeout(function() { popup.document.title = title; }, delayFinal || 1000);
else setTimeout(function() { overridePopupTitle(popup, title); }, delayRepeat || 100);
}
var openPopupWithTitle = function(url, title, settings, delay) {
var win = window.open(url, title, settings);
overridePopupTitle(win, title, delay);
return win;
}
None of these answers worked for me. I was trying to open a popup with a PDF inside and kept getting permission denied trying to set the title using the above methods. I finally found another post that pointed me in the correct direction. Below is the code I ended up using.
Source: How to Set the Title in Window Popup When Url Points to a PDF File
var winLookup;
var showToolbar = false;
function openReportWindow(m_title, m_url, m_width, m_height)
{
var strURL;
var intLeft, intTop;
strURL = m_url;
// Check if we've got an open window.
if ((winLookup) && (!winLookup.closed))
winLookup.close();
// Set up the window so that it's centered.
intLeft = (screen.width) ? ((screen.width - m_width) / 2) : 0;
intTop = (screen.height) ? ((screen.height - m_height) / 2) : 0;
// Open the window.
winLookup = window.open('', 'winLookup','scrollbars=no,resizable=yes,toolbar='+(showToolbar?'yes':'no')+',height=' + m_height + ',width=' + m_width + ',top=' + intTop + ',left=' + intLeft);
checkPopup(m_url, m_title);
// Set the window opener.
if ((document.window != null) && (!winLookup.opener))
winLookup.opener = document.window;
// Set the focus.
if (winLookup.focus)
winLookup.focus();
}
function checkPopup(m_url, m_title) {
if(winLookup.document) {
winLookup.document.write('<html><head><title>' + m_title + '</title></head><body height="100%" width="100%"><embed src="' +m_url + '" type="application/pdf" height="100%" width="100%" /></body></html>');
} else {
// if not loaded yet
setTimeout(checkPopup(m_url, m_title), 10); // check in another 10ms
}
}
You can use also
var popup = window.open('......');
popup.onload = function () {
popup.document.title = "my title";
}
Not sure if this will help,
function GetInput() {
var userInput;
var stringOutput;
userInput = prompt('What should the title be?', "");
stringOutput = userInput;
document.title = stringOutput;
}
<button type="button" onclick="GetInput()">Change Title</button>
var win= window.open('......');
win.document.writeln("<title>"+yourtitle+"</title>");
This works for me, tested in chromium browsers.
I ended up creating a setTitle method in my popup window and calling it from my parent page.
//popup page:
function setTitle(t) {
document.title = t;
}
//parent page
popupWindow.setTitle('my title');
Try this, it will work.
var timerObj, newWindow;
function openDetailsPopUpWindow(url) {
newWindow = window.open(url, '', 'height=500,width=700,menubar=no,resizable=yes,scrollbars=yes');
timerObj = window.setInterval("fun_To_ReTitle('~~newTitle~~ ')", 10);
}
function fun_To_ReTitle(newTitle){
if (newWindow.document.readyState == 'complete') {
newWindow.document.title=newTitle;
window.clearInterval(timerObj);
}
}

Help converting JavaScript click function to onLoad

I'm trying to convert a JavaScript function that ran off a click event to launch on page load and window resize. As you can see below, I commented out the section governing the click event and added the last line "window.onload," and manually added the class="resizerd" to the element it was working with.
The function isn't running at all. Chrome's Dev tools are showing "Uncaught TypeError: Cannot set property 'prevWidth' of undefined" Did I mess up the syntax somewhere? Any advice for how to launch this on load?
Thank you!
//var clicked = document.getElementById("buttonImportant")
var resizeeContainer = document.getElementById('video_container');
var resizee = resizeeContainer.getElementsByTagName('video')[0];
/*clicked.addEventListener('click',function(){
if( resizeeContainer.className.lastIndexOf("resizerd")>=0 ){
}
else
{
resizeeContainer.className="resizerd";
}*/
myResizerObject.prevWidth = resizee.offsetWidth;
myResizerObject.prevHeight = resizee.offsetHeight;
myResizerObject.Init();
//},false);
myResizerObject.prevWidth = resizee.offsetWidth;
myResizerObject.prevHeight = resizee.offsetHeight;
myResizerObject.Init();
var RESIZER = function(){
this.prevWidth = resizee.offsetWidth;
this.prevHeight = resizee.offsetHeight;
this.resizee = resizeeContainer.getElementsByTagName('video')[0];
this.resizeeContainer = resizee.parentNode;
this.resizeeStyle = this.resizee.style;
var ratio = this.resizee.offsetHeight/this.resizee.offsetWidth;
var that = this;
this.Init = function(){
if( that.resizeeContainer.className.lastIndexOf("resizerd")>=0 )
{
var resizeeContOffsetWidth = that.resizeeContainer.offsetWidth;
var resizeeOffsetWidth = that.resizee.offsetWidth;
var resizeeContOffsetHeight = that.resizeeContainer.offsetHeight;
var resizeeOffsetHeight = that.resizee.offsetHeight;
if(that.prevWidth!= resizeeContOffsetWidth)
{
that.prevWidth = resizeeContOffsetWidth;
var desired = resizeeContainer.offsetHeight/resizeeContainer.offsetWidth;
if(desired>ratio){
that.resizeeStyle.width=resizeeContOffsetWidth*desired+resizeeContOffsetWidth*desired+"px";
that.resizeeStyle.left = -1*(resizeeOffsetWidth-resizeeContOffsetWidth)/2+'px';
}
else{
that.resizeeStyle.cssText="width:100%;height:auto;position:fixed;";
}
}
if(that.prevHeight!=resizeeContOffsetHeight)
{
that.prevHeight = resizeeContOffsetHeight;
var desired = resizeeContOffsetHeight/resizeeContOffsetWidth;
if(desired>ratio){ console.log(ratio);
//that.resizeeStyle.top = '0px';
that.resizeeStyle.left = -1*(resizeeOffsetWidth-resizeeContOffsetWidth)/2+'px';
that.resizeeStyle.width = resizeeContOffsetHeight*desired+resizeeContOffsetHeight/desired+'px';
}
else
{
that.resizeeStyle.top = -1*(resizeeOffsetHeight-resizeeContOffsetHeight)/2+'px';
}
}
}
};
};
var myResizerObject = new RESIZER();
window.onresize = myResizerObject.Init;
window.onload = myResizerObject.Init;
Did you try to execute the function through the <body> tag?
Like:
<body onload="myfunction();">
Try calling the entire resize javascript function in the OnLoad="myfunction();" event of the Body of the page. I have done this to resize the page everytime it loads and it works just fine.
You have this line:
myResizerObject.prevWidth = resizee.offsetWidth;
That is probably giving the error. You've done nothing to declare myResizerObject so it cannot have a property prevWidth.
Somewhere down there you do
var myResizerObject = new RESIZER();
I suspect you want those lines in a more reasonable order :)
Such code should work just fine:
var myResizerObject = new RESIZER();
function UpdateResizerObject() {
var resizeeContainer = document.getElementById('video_container');
var resizee = resizeeContainer.getElementsByTagName('video')[0];
myResizerObject.prevWidth = resizee.offsetWidth;
myResizerObject.prevHeight = resizee.offsetHeight;
myResizerObject.Init();
}
window.onload = function() {
UpdateResizerObject();
};
window.onresize = function() {
UpdateResizerObject();
};
Have it after you define the RESIZER class though.
Your mistake was calling the object instance variable before creating it.
Edit: some basic debug.. add alerts to the function like this:
this.Init = function(){
alert("Init called.. container: " + that.resizeeContainer);
if (that.resizeeContainer)
alert("class: " + hat.resizeeContainer.className);
if( that.resizeeContainer.className.lastIndexOf("resizerd")>=0 )
{
...
}
}
And see what you get.

Categories

Resources