Proper way to center pop window with Javascript and pass html - javascript

Goal: quick and dirty app (client side only) to grab some arguments from one page and put results onto a new page, which can be printed and then closed. Arguments on the original page then can be changed and new page popped.
Used this as a starting point:
https://developer.mozilla.org/en/DOM/window.open
http://www.yourhtmlsource.com/javascript/popupwindows.html
Proof of concept(final version will have about 10 inputs/args)
HTML fragment
<input type="text" id="x">
<form>
<input type=button value="Calculate" onClick="javascript:genResults()">
</form>
JS
function dirtypop(arg)
{
var popwin=window.open('','name','height=300,width=400,status=1,center=1');
popwin.document.write('<html><head><title>Square</title>');
popwin.document.write('</head><body>');
popwin.document.write('<h1>Squared plus one is: '+arg+'</h1>');
popwin.document.write('<p>Close this window</p>');
popwin.document.write('</body></html>');
popwin.document.close();
};
function genResults()
{
x = document.getElementById('x').value;
if (x == parseFloat(x))
{
dirtypop(x*x+1);
}
};
This works(tested on FF3.5 and Chrome), except new window does not pop into center. How to center it? Mozzila says needs chrome=yes and talks about UniversalPrivilege scripts, what kind of beasts are those?
Anything else that can be improved?

Here's one of my custom cross-browser scripts that can be reused dynamically to center any popped window of any size on the screen:
// here's the script
function popWindow(url,winName,w,h) {
if (window.open) {
if (poppedWindow) { poppedWindow = ''; }
//GET SIZE OF WINDOW/SCREEN
windowW = w;
windowH = h;
var windowX = (screen.width/2)-(windowW/2);
var windowY = (screen.height/2)-(windowH/2);
var myExtra = "status=no,menubar=no,resizable=yes,toolbar=no,scrollbars=yes,addressbar=no";
var poppedWindow = window.open(url,winName,'width='+w+',height='+h+',top='+windowY+',left=' + windowX + ',' + myExtra + '');
setTimeout(refreshThis,3000);
}
else {
alert('Your security settings are not allowing our popup windows to function. Please make sure your security software allows popup windows to be opened by this web application.');
}
}
// and you would call it like this:
popWindow('http://www.myurl.com/','myPoppedWindowName','500','400');
// With this example call you would pop a window with a url of http://www.myurl.com/
// which is given the name of myPoppedWindowName
// and a width of 500px along with height of 400px
// which gets centered on the screen according to these size parameters
This will do the trick considering it truly is a cross-browser implementation, including reverse compatibility to browsers in place back in 2001. It also contains a check to make sure the end-user has popup windows enabled.

You'll need to set the top and left properties instead of center=1.
var left = (screen.width - windowWidth) / 2;
var top = (screen.height - windowHeight) / 2;

Related

'Media-queries' for javascript - different code for different viewport height/widths

The problem
I'm using javascript to calculate widths of elements to achieve the layout I'm after. The problem is, I don't want to load the code on smaller screen sizes (when the screen width is less than 480px for example). I'd like this to work on load and on browser/viewport resize.
I'd consider small screen devices 'the default' and working up from there. So, none of the following script is called by default, then if the browser width is greater than 480px (for example), the following script would be called:
The code
$(document).ready(function() {
//Get the figures width
var figure_width = $(".project-index figure").css("width").replace("px", "");
//Get num figures
var num_figures = $(".project-index figure").length;
//Work out how manay figures per row
var num_row_figures = Math.ceil(num_figures / 2);
//Get the total width
var row_width = figure_width * num_row_figures;
//Set container width to half the total
$(".project-index").width(row_width);
x = null;
y = null;
$(".project-index div").mousedown(function(e) {
x = e.clientX;
y = e.clientY;
});
$(".project-index div").mouseup(function(e) {
if (x == e.clientX && y == e.clientY) {
//alert($(this).next().attr("href"));
window.location.assign($(this).next().attr("href"));
}
x = y = null;
});
});
// Drag-on content
jQuery(document).ready(function() {
jQuery('#main').dragOn();
});
The extra bit
The slight difference on larger screens is to do with the browser/viewport height. This is in regards to the line:
var num_row_figures = Math.ceil(num_figures / 2);
You can see once the calculation has a value, it divides it by 2. I only want this to happen when the browser/viewport height is above a certain amount - say 600px.
I'd be happy with this being the 1st state and then the value is divided by 2 if the height is greater than 600px if it's easier.
Can anyone help me/shed some light on how to manage my script this way. I know there's media queries for managing CSS but I can't seem to find any resources for how to manage javascript this way - hope someone can help.
Cheers,
Steve
You can use window.matchMedia, which is the javascript equivalent of media queries. The matchMedia call creates a mediaQueryList object. We can query the mediaQueryList object matches property to get the state, and attach an event handler using mediaQueryList.addListener to track changes.
I've added an example on fiddle of using matchMedia on load and on resize. Change the bottom left pane height and width (using the borders), and see the states of the two queries.
This is the code I've used:
<div>Min width 400: <span id="minWidth400"></span></div>
<div>Min height 600: <span id="minHeight600"></span></div>
var matchMinWidth400 = window.matchMedia("(min-width: 400px)"); // create a MediaQueryList
var matchMinHeight600 = window.matchMedia("(min-height: 600px)"); // create a MediaQueryList
var minWidth400Status = document.getElementById('minWidth400');
var minHeight600Status = document.getElementById('minHeight600');
function updateMinWidth400(state) {
minWidth400Status.innerText = state;
}
function updateMinHeight600(state) {
minHeight600Status.innerText = state;
}
updateMinWidth400(matchMinWidth400.matches); // check match on load
updateMinHeight600(matchMinHeight600.matches); // check match on load
matchMinWidth400.addListener(function(MediaQueryListEvent) { // check match on resize
updateMinWidth400(MediaQueryListEvent.matches);
});
matchMinHeight600.addListener(function(MediaQueryListEvent) { // check match on resize
updateMinHeight600(MediaQueryListEvent.matches);
});
#media screen and (max-width: 300px) {
body {
background-color: lightblue;
}
}
So i searched a bit and came up with this example from w3 schools .http://www.w3schools.com/cssref/tryit.asp?filename=trycss3_media_example1
i think this is something you are trying to achieve.
For pure js , you can get the screen width by screen.width

trouble with window.resize event

I have a page that contains a jquery tab element with three tabs. Within that element, there is a map (tab 1 - PolyMap), chart (tab 2 - Devexpress), and data grid (tab 3 - Devexpress). The site itself is built on Foundation 4 to provide responsive design. Using foundation, the width and height of the page will change when the screen size changes, but the actual map and graph elements were not changing. I implemented the following code to cause the map and graph to automatically resize when the screen size changes (i.e portrait-landscape), or when the page is initially loaded.
I am fairly new to javascript programming, so I am still trying to learn the intricacies of the differences between browsers. I typically use Chrome to develop, and so I developed the code based on what works in Chrome. The issue that I am running into is that when I now test in IE or Firfox (both current releases), I am getting differing results. In IE, both elements are loaded with 0px height. In Firefox, the map is loaded correctly (the tab that is shown by default), but the chart is loaded with a 0px height (the chart tab is initially not shown). If the screen size changes, the script fires and the size is immediately corrected, so I am guessing that it is either an issue with using $(window).load, or the code is firing before the page is loaded completely in IE or Firefox (although I have a hard time understanding how it would work correctly in Chrome).
Are there any suggestions - and remember, i am new, so if the entire code block should be reworked, I am completely open to that- I want to learn...
Code (appears immediately before closing html tag):
function ResizeMap() {
var mPadding = $('#MapContent').css("padding");
mPadding = mPadding.substring(0, mPadding.length - 2);
mPadding = mPadding * 2;
if (MapContent.offsetWidth > 970) {
var nWidth = 970-mPadding;
var nHeight = 650;
} else {
var nWidth = MapContent.offsetWidth-mPadding;
var nHeight = nWidth * (650/(970-mPadding));
}
$('#map').width(nWidth);
$('#map').height(nHeight);
}
function ResizeChart() {
var cPadding = $('#ChartContent').css("padding");
cPadding = cPadding.substring(0, cPadding.length - 2);
cPadding = cPadding * 2;
if (ChartContent.offsetWidth > 970) {
var nWidth = 970-cPadding;
var nHeight = 650;
} else {
var nWidth = ChartContent.offsetWidth-cPadding;
var nHeight = nWidth * (650/(970-cPadding));
}
chart.SetWidth(nWidth);
chart.SetHeight(nHeight);
}
$(window).resize(function() {
ResizeMap();
ResizeChart();
});
$(window).load(function() {
ResizeMap();
ResizeChart();
});

Javascript dialog is programmed to move when the page scrolls, but it flickers. Can this be fixed?

I've written some jQuery code to display a box with data in the corner of the users' web browser. I'm using the .scroll event to make the box stay in the corner as the user scrolls up and down the page. Let me emphasize that I am not using jquery-ui dialog.
The only problem is that the box flickers as the page scrolls. I'm afraid that there will be no cross-browser solution to this problem as the different browsers seem to behave differently with scrolling. Barring a cross-browser solution, an IE solution would be nice (My web application is designed to be used by a specific group of about 100 users in my organization.)
Here are snippets of the relative code:
ExternalScroll: function () {
LittleBlackBook.setPosition();
}
setPosition: function () {
var scrollPosition = $(self).scrollTop();
var cssTop = LittleBlackBookStatic.determineCssTop(this.height, this.isTop, this.vOffset, scrollPosition);
var cssHeight = LittleBlackBookStatic.determineCssHeight(this.height);
var cssLeft = LittleBlackBookStatic.determineCssLeft(this.width, this.isLeft, this.hOffset);
var cssWidth = LittleBlackBookStatic.determineCssWidth(this.width);
this.jQueryObj.css('top', cssTop);
this.jQueryObj.css('height', cssHeight);
this.jQueryObj.css('left', cssLeft);
this.jQueryObj.css('width', cssWidth);
}
var LittleBlackBookStatic = {
determineCssTop: function (height, isTop, vOffset, vScroll) {
var windowHeight = $(self).height();
var scrollPosition = $(self).scrollTop();
var newModalTop = isTop ? vOffset + vScroll : windowHeight - height + vScroll - vOffset;
return newModalTop + 'px';
},
determineCssHeight: function (height) {
return height + 'px';
},
determineCssLeft: function (width, isLeft, hOffset) {
var windowWidth = $(self).width();
var newModalLeft = isLeft ? hOffset : windowWidth - width - hOffset;
return newModalLeft + 'px';
},
determineCssWidth: function (width) {
return width + 'px';
}
} // end LittleBlackBookStatic
I'm using jQuery to look up the scroll position as the page scrolls and change the CSS.
Is there a better way; a way that will make it scroll without flickering? If no, then why not?
You should use fixed positioning for that box instead instead of animating it to keep it in the corner.
You'll use less javascript and avoid flickering that comes with animation.

How can I implement a FPS view with WebGL inside a browser?

I'm using Copperlicht, and I want to create a usable FPS. The demo controls shows why the browser environment makes this a pain.
In order to implement FPS camera control, you need to track the relative mouse position - in other words, its motion, not its absolute screen coordinates. The mouse can leave the browser at any time (rightfully so) and can't be tracked, unless the user initiates a drag event inside the page. Click events change focus and prevent the application from using mouse data as input.
The mouse position can be tracked during drag, but this requires the user to hold down their left mouse button. This isn't good since left clicking is usually used for other things. Holding the button down is also tiring and cumbersome.
The only thing I can think of is automating the middle mouse button. A middle mouse button press keeps focus in the browser, and keeps left/right click events outside the browser window in the browser's focus. Is it possible to cause middle mouse button to stay pressed using JavaScript?
If not, is there a "pure" solution to this ? I'd rather not go to flash or Java or a plugin as an answer.
This thread is a nice reading on this topic. It seems like prototypes for this functionality are at least suggested for Firefox and Chrome.
How about making the window fullscreen and then pausing the game if the cursor moves out of the window? I know this doesn't really solve the problem, but it's the best I can think of, without using a plugin of some sort.
It's kind of cheating, but going to about:flags in Chrome and enabling "FPS counter" works for me, :) (but it's not doing it for all browsers nor inside your WebGL app).
I found this example code at
http://bitdaddys.com/javascript/example3run.html
<html>
<head>
<title>JavaScript Example of Mouse Position Tracking</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<form name=thisform>
<table border=0>
<tr><td colspan=2>Position Of Cursor</td></tr>
<tr><td>X <input type=text name=x value=""></td>
<td>Y <input type=text name=y value=""></td>
</tr>
</table>
</form>
<script type=text/javascript>
var isIE = document.all?true:false;
if (!isIE) document.captureEvents(Event.MOUSEMOVE);
document.onmousemove = getMousePosition;
function getMousePosition(mp) {
var _x;
var _y;
if (!isIE) {
_x = mp.pageX;
_y = mp.pageY;
}
if (isIE) {
_x = event.clientX + document.body.scrollLeft;
_y = event.clientY + document.body.scrollTop;
}
document.thisform.x.value=_x;
document.thisform.y.value=_y;
return true;
}
</script>
</body>
</html>
We need the window to be able to capture the mouse, as it is seen with some browser plugins, maybe in Java. Flash doesn't have this ability, AFAIK.
As a sidenote, when captured to "get the mouse back" you have to press ESC, and this can be annoying when the app doesn't inform the user properly.
(this is the only solution i've seen so far could work for my game project, doing an FPS too)
Implement a Plugin for each browser you intend to support. AFAIK, this is the way they solved the problem with "Quake Live".
Chrome / Chromium -> PPAPI
Firefox & Opera -> NPAPI
IE -> ActiveX
Safari -> Safari plugin development
Btw, the link Daniel Baulig gave you has a nice pointer and solves this problem (on the long run).
At this point in time (Oct 2011) the only way to get real First Person Shooter-style controls is via a browser plugin. Depending on your needs you might also be able to get away with a simple click-and-drag scheme like I'm currently using in my Quake 3 demo, but if you are building an actual game and not a pretty tech demo this is probably not sufficient.
(Note: That's actually what Google did for their GWT port of Quake 2. You have to use the CTRL key to fire, since clicking is used to move your view.)
In the near future, however, we should be receiving a "MouseLock" API that is basically custom-built for this purpose. You can read up on it's progress at Seth Ladd's Blog. Once that comes out we'll have a lot more options for game controls available to us. (Would also help with things like RTS games)
Right here right now :
I make one with push/pop matrix with glmatrix 0.9 also version 2.0 webgl & glmatrix .
Secret - Must translate to zero , rotate and then translate to map position. You have all parameters for first person controler.
See:opengles 1.1. / webgl 1.0 / glmatrix 0.9
or see this example with full colizion.
WebGl 2 / glmatrix 2 Example's (also First Person controller):
Download from bitBucket
Live example
Out of context :
////////////////////////////////////////////////////////
// Somewhere in draw function ....
////////////////////////////////////////////////////////
mat4.identity(object.mvMatrix);
this.mvPushMatrix(object.mvMatrix,this.mvMatrixStack);
////////////////////////////////////////////////////////
if (App.camera.FirstPersonController==true){camera.setCamera(object)}
////////////////////////////////////////////////////////
mat4.translate(object.mvMatrix, object.mvMatrix, object.position.worldLocation );
mat4.rotate(object.mvMatrix, object.mvMatrix, degToRad(object.rotValue), object.rotDirection.RotationVector );
....
End of Draw function
Content of SetCamera :
var camera = new Object();
/* Set defaults */
camera.pitch = 0;
camera.pitchRate = 0;
camera.yaw = 0;
camera.yawRate = 0;
camera.xPos = 0;
camera.yPos = 0;
camera.zPos = 0;
camera.speed = 0;
camera.yawAmp = 0.05;
camera.pitchAmp = 0.007;
keyboardPress = defineKeyBoardObject();
camera.setCamera = function(object) {
/* Left Key or A */
if (keyboardPress.getKeyStatus(37) || keyboardPress.getKeyStatus(65) || App.camera.leftEdge == true) {
camera.yawRate = 20;
if (App.camera.leftEdge == true) camera.yawRate = 10;
}
/* Right Key or D */
else if (keyboardPress.getKeyStatus(39) || keyboardPress.getKeyStatus(68) || App.camera.rightEdge == true) {
camera.yawRate = -20;
if (App.camera.rightEdge == true) camera.yawRate = -10;
}
else {
// camera.yawRate = 0;
}
/* Up Key or W */
if (keyboardPress.getKeyStatus(38) || keyboardPress.getKeyStatus(87)) {
camera.speed = 0.03;
}
/* Down Key or S */
else if (keyboardPress.getKeyStatus(40) || keyboardPress.getKeyStatus(83)) {
camera.speed = -0.03;
}
else {
camera.speed = 0;
}
/* Page Up
if (keyboardPress.getKeyStatus(33)) {
camera.pitchRate = 100;
}
/* Page Down
else if (keyboardPress.getKeyStatus(34)) {
camera.pitchRate = -100;
}
else {
camera.pitchRate = 0;
}
*/
/* Calculate yaw, pitch and roll(x,y,z) */
if (camera.speed != 0) {
camera.xPos -= Math.sin(degToRad(camera.yaw)) * camera.speed;
camera.yPos = 0;
camera.zPos -= Math.cos(degToRad(camera.yaw)) * camera.speed;
}
camera.yaw += camera.yawRate * camera.yawAmp ;
camera.pitch += camera.pitchRate * camera.pitchAmp ;
mat4.rotate(object.mvMatrix, object.mvMatrix, degToRad(-camera.pitch), [1, 0, 0]);
mat4.rotate(object.mvMatrix, object.mvMatrix, degToRad(-camera.yaw), [0, 1, 0]);
// mat4.translate(object.mvMatrix, object.mvMatrix, [camera.yaw, -camera.pitch, 0]);
mat4.translate(object.mvMatrix, object.mvMatrix, [-camera.xPos , -camera.yPos , -camera.zPos ]);
camera.yawRate = 0;
camera.pitchRate = 0;
};
This code allows you to draw 3D objects and folders easily
and quickly.Under the principle of one object one line.
webgl 3d wourld engine framework zlatnaspirala
First person web site look.
Used lib :
High performance matrix and vector operations for WebGL

Auto-detect a screen resolution and change browser zoom with Javascript?

How do I auto-detect a screen resolution and change browser zoom with Javascript?
I was thinking of something more like this:
I've got the following code:
#warp with width: 3300% and a mask with width: 100%; and then, each .item has width: 3.030303% — with overflow hidden, otherwise it couldn't work as I want.
My point is: I've done this for at least 1280px wide screens.
What I want is if someone can write code that I could use toswitch the CSS file once viewed on a <1280px screen — them, I could do something like:
.item img { width: 80%; } and then, the result would be the same as "browser zoom out".
If you mean change the native browser zoom triggered by CTRL +/- then this isn't possible. You can adjust CSS properties/apply stylesheets but you cannot affect native browser controls. There are in fact CSS only options here depending on your target audience (and their browser choice) through the use of media queries, a couple of examples here and here. If these are not suitable then you can do various things with JavaScript to detect screen width/height and adjust accordingly.
Auto-detect a screen resolution
See this SO question
change browser zoom with javascript
This is not possible. See this SO question.
This will help to detect browser zoom tested on all browser
<script>
window.utility = function(utility){
utility.screen = {
rtime : new Date(1, 1, 2000, 12,00,00),
timeout : false,
delta : 200
};
utility.getBrowser = function(){
var $b = $.browser;
$.extend(utility.screen,$.browser);
utility.screen.isZoomed = false;
var screen = utility.screen;
screen.zoomf = screen.zoom = 1;
screen.width = window.screen.width;
screen.height = window.screen.height;
if($b.mozilla){ //FOR MOZILLA
screen.isZoomed = window.matchMedia('(max--moz-device-pixel-ratio:0.99), (min--moz-device-pixel-ratio:1.01)').matches;
} else {
if($b.chrome){ //FOR CHROME
screen.zoom = (window.outerWidth - 8) / window.innerWidth;
screen.isZoomed = (screen.zoom < .98 || screen.zoom > 1.02)
} else if($b.msie){//FOR IE7,IE8,IE9
var _screen = document.frames.screen;
screen.zoom = ((((_screen.deviceXDPI / _screen.systemXDPI) * 100 + 0.9).toFixed())/100);
screen.isZoomed = (screen.zoom < .98 || screen.zoom > 1.02);
if(screen.isZoomed) screen.zoomf = screen.zoom;
screen.width = window.screen.width*screen.zoomf;
screen.height = window.screen.height*screen.zoomf;
}
}
return utility.screen;
};
window.onresize = function(e){
utility.screen.rtime = new Date();
if (utility.screen.timeout === false) {
utility.screen.timeout = true;
setTimeout(window.resizeend, utility.screen.delta);
}
};
window.resizeend = function() {
if (new Date() - utility.screen.rtime < utility.screen.delta) {
setTimeout(window.resizeend, utility.screen.delta);
} else {
utility.screen.timeout = false;
utility.screen = utility.getBrowser();
if(window.onresizeend) window.onresizeend (utility.screen);
if(utility.onResize) utility.onResize(utility.screen);
}
};
window.onresizeend = function(screen){
if(screen.isZoomed)
$('body').text('zoom is not 100%');
else{
$('body').text('zoom is 100% & browser resolution is'+[screen.width+'X'+screen.height]);
}
};
$(document).ready(function(){
window.onresize();
});
return utility;
}({});
</script>
Demo
RE: Auto-detect a screen resolution and change browser zoom with Javascript?
The question is perfectly possible and is in effect at our website here:
www.noteswithwings.com
JS detects the screen width and zooms out or in a little to fit the content on to the screen.
Further, if the user resizes the window the zoom is triggered.
This actually helps fit content on to tablet sized screens and screens as small as the iphone without adding extra stylesheets or having to detect an OS/ Browser..
var oldZoom = $(window).width();
var windowWidth = $(window).width();
check_window_size(windowWidth,1,bsr,bsr_ver);
$(window).resize(function() {
var windowWidthnow = $(window).width();
check_window_size(windowWidthnow,2,bsr,bsr_ver);
});
function check_window_size(size,init_var,bsr,bsr_ver)
{
/* Develop for resizing page to avoid grey border!
Page layout 1265px wide.
On page resize shift layout to keep central, zoom BG-img to fill screen
Zoom content down for smaller screens by 5% to keep content flow!
*/
//change this var for screen width to work with, in this case our site is built at 1265
var wdth = 1265;
//Change this variable for minimum screen;
var smallest_width=1120;
var varZoom= $(window).width()/wdth;
var s_size = $(window).width();
var scale_smaller;
var center = (s_size-wdth)/2;
var its_ie=false;
if(size<=smallest_width)
{
$("#old_browser").css("width","50%").css({"height":"40px","left": center+"px"});
if(!check_for_object(false,"moved_pages"))
{
if(center<-110)//margin width!
{
if(!its_ie)
$("#scroller").css("zoom",0.95);
$("#footer").css("zoom",0.9).css("left",120+"px");
$(".colmask").css("left",-110+"px");
if(check_for_object(false,"move_menu_loggedin"))
$("#move_menu_loggedin").css("right","110px");
if(check_for_object(false,"login_div"))
$("#login_div").css("left","-80px");
return;
}
$("#move_menu_loggedin").css("left","-"+center+"px");
$("#scroll").css("zoom","normal");
$(".colmask").css("left",center+"px");
}
else
{
/*Only pages that you do not want to move the colmask for!*/
$("#scroller").css("zoom",0.90);//.css("left","-50px");;
$("#footer").css("zoom","normal");
}
}
else
{
if(size>wdth)
$("#background").css("zoom",varZoom);
$("#scroller").css("zoom","normal");
$("#footer").css({"zoom":"normal","left":0});
if(!check_for_object(false,"moved_pages"))
{
$(".colmask").css("left",center+"px");
$(".colmask").css("zoom","normal");
var movelog = -center;
if(check_for_object(false,"move_menu_loggedin"))
$("#move_menu_loggedin").css("right",movelog +"px");
if(check_for_object(false,"login_div"))
$("#login_div").css("left","80px");
}
else
{
$(".colmask").css("zoom","normal");
}
}
}
-- check_window_size(windowWidth,1,bsr,bsr_ver); bsr & bsr_ver are detected using a php class.
-- #old_browser is a div containing information if you have an old web browser.
-- #background is a fixed image 100x100% of the screen.
As you can see we also move a few items which were not in the containing div scope.
Colmask is the containing div for most of the pages content (For us that sits underneath the header which is why we move some items manually)
Hope the code snippet can help someone else achieve this.

Categories