Internet explorer 10 and top.window.pageYOffset - javascript

I use window.pageYOffset to find the position of the scroll bar (works fine in firefox), however it is always undefined in IE10
I have tried using:
window.pageYOffset // undefined
document.body.scrollTop // always 0
document.documentElement.scrolltop // undefined
top.window.scrollY // undefined
is this a known issue with IE10?
this is with compatibility mode enabled. Without it, pageYOffset works as expected. We have to use compatibility mode as it's a requirement for our clients
the code displays a calander, which needs to be displayed against a text box. it's position is altered when the user has scrolled on the page:
UPDATED WITH CODE:
function showCalendar(e, datePicker) {
top.calendarReturnFunc = function(value, controlId) {
getDatePicker(controlId).dateBox.hasDate = "True";
dateChosen(value, controlId, true);
};
top.datePickerActive = function() { return true; };
var itop = top.window.screenTop != undefined ? top.window.screenTop : parseInt(top.window.screenY) + parseInt(130);
var ileft = top.window.screenLeft != undefined ? top.window.screenLeft : parseInt(top.window.screenX);
var x = e.screenX - parseInt(ileft);
var y;
if (typeof top.window.pageYOffset === "undefined") {
y = (e.screenY - parseInt(itop) - datePicker.yOffset) + document.documentElement.scrollTop; //IE10?...
}
else {
y = (e.screenY - parseInt(itop) - datePicker.yOffset) + top.window.pageYOffset; //works fine in firefox
}
if (datePicker.alignLeft) {
x -= 180;
}
if (!datePicker.alignBottom) {
y -= 178;
}
_calendar.style.left = x + "px";
_calendar.style.top = y + "px";
_calendar.style.display = "block";
_calendar.datePicker = datePicker;
_calendar.callingFrame = this;
_calendar.src = datePicker.calendarUrl + "&Date=" + escape(datePicker.dateBox.value);
}

You can use document.documentElement.scrollTop for IE. You didn’t capitalise the T in scrollTop in your sample.

Related

How can I get rangeslider.js to work on mobile devices?

I have the following problem, you will see I have a web page where I implement the rangeslider plugin on PC it works correctly but on mobile I can't explain myself: when on mobile I select the slider I cannot make it go up or down or change the amount it has, it is only modified while The scroll is used but as you know with the scroll the user moves on mobile, therefore it cannot work so check what I mean on the page
this is the link of the page: http://ucreativa.work/linux/nsite2/product.php
As you can see, it works well on PC, but if they try to use it on mobile, the slider does not work.
What do you think that might be? I append the js code that I use I don't append the css because it is a lot of code that is not relevant
my question is can this plugin work on mobile?
var cpu_cur_val = '2';
var ram_cur_val = '4';
var disk_cur_val = '8';
var backup_cur_val = '30';
var ips_cur_val = '0';
function new_range (wrapper) {
// Variables to use later
var rangeWrapper = document.querySelector('.' + wrapper + '__wrapper');
var rangeInput = document.querySelector('.' + wrapper + '__input');
var rangeValues = document.querySelector('.' + wrapper + '__values');
var rangeValueNumberBottom = document.querySelector('.' + wrapper + '__value__number--bottom');
var rangeValueTextBottom = document.querySelector('.' + wrapper + '__value__text--bottom');
var rangeSliderPaths = document.querySelectorAll('.' + wrapper + '__slider__path');
var mouseX = 0;
var mouseY = 0;
var mouseInitialY = 0;
var mouseDy = 0;
var mouseDyLimit = 25;
var mouseDyFactor = 3;
var max = parseInt(rangeInput.max);
var rangeMin = parseInt(rangeInput.min);
var rangeMax = parseInt(rangeInput.max);
var rangeValue = parseInt(rangeInput.value);
var rangeHeight = 320;
var currentY = rangeHeight * rangeValue / max;
var rangeMinY = rangeHeight * rangeMin / max;
var rangeMaxY = rangeHeight * rangeMax / max;
var scaleMax = 0.32;
var scale, newPath, newY, newSliderY, lastMouseDy, rangeWrapperLeft, pageX, pageY;
// Update slider value, initially using the `input` value
updateValue();
// Function to build the slider `path`, using the given `dy` and `ty` values
function buildPath(dy, ty) {
return 'M 0 ' + ty + ' q ' + mouseX + ' ' + dy + ' 120 0 l 0 320 l -120 0 Z';
}
// Function to update the slider value
function updateValue() {
// Clear animations if are still running
anime.remove([rangeValues, rangeSliderPaths[0], rangeSliderPaths[1]]);
// Calc the `input` value using the current `y`
rangeValue = parseInt(currentY * max / rangeHeight);
// Calc `scale` value for numbers
scale = (rangeValue - rangeMin) / (rangeMax - rangeMin) * scaleMax;
// Update `input` value
rangeInput.value = rangeValue;
// rangeSum.innerText = rangeValue;
rangeValueNumberBottom.innerText = rangeValue;
// Match the javascript value to real input value;
rangeInput.setAttribute('value', rangeValue);
switch (wrapper) {
default:
rangeValueNumberBottom.innerText = rangeValue;
break;
case 'cpu':
cpu_cur_val = rangeValue;
break;
case 'ram':
if (rangeValueNumberBottom.innerText == '0') {
rangeValueTextBottom.innerText = 'זיכרון (MB)';
rangeValueNumberBottom.innerText = '500';
} else {
rangeValueTextBottom.innerText = 'זיכרון (GB)';
}
ram_cur_val = rangeValue;
break;
case 'disk':
rangeValueNumberBottom.innerText = rangeValue + '0';
disk_cur_val = rangeValue;
break;
case 'backup':
if (rangeValueNumberBottom.innerText == '0') {
rangeValueNumberBottom.innerText = '0';
} else {
rangeValueNumberBottom.innerText = rangeValue + '0';
}
backup_cur_val = rangeValue;
break;
case 'ips':
ips_cur_val = rangeValue;
break;
}
// Some maths calc
if (Math.abs(mouseDy) < mouseDyLimit) {
lastMouseDy = mouseDy;
} else {
lastMouseDy = mouseDy < 0 ? -mouseDyLimit : mouseDyLimit;
}
// Calc the `newSliderY` value to build the slider `path`
newSliderY = currentY + lastMouseDy / mouseDyFactor;
if (newSliderY < rangeMinY || newSliderY > rangeMaxY) {
newSliderY = newSliderY < rangeMinY ? rangeMinY : rangeMaxY;
}
// Build `path` string and update `path` elements
newPath = buildPath(lastMouseDy, rangeHeight - newSliderY);
rangeSliderPaths[0].setAttribute('d', newPath);
rangeSliderPaths[1].setAttribute('d', newPath);
}
// Function to simulate the elastic behavior
function elasticRelease() {
// Morph the paths to the opposite direction, to simulate a strong elasticity
anime({
targets: rangeSliderPaths,
d: buildPath(-lastMouseDy * 1.3, rangeHeight - (currentY - lastMouseDy / mouseDyFactor)),
duration: 150,
easing: 'linear',
complete: function () {
// Morph the paths to the normal state, using the `elasticOut` easing function (default)
anime({
targets: rangeSliderPaths,
d: buildPath(0, rangeHeight - currentY),
duration: 4000,
elasticity: 880
});
}
});
}
// Handle `mousedown` and `touchstart` events, saving data about mouse position
function mouseDown(e) {
mouseY = mouseInitialY = e.targetTouches ? e.targetTouches[0].pageY : e.pageY;
rangeWrapperLeft = rangeWrapper.getBoundingClientRect().left;
}
// Handle `mousemove` and `touchmove` events, calculating values to morph the slider `path` and translate values properly
function mouseMove(e) {
if (mouseY) {
pageX = e.targetTouches ? e.targetTouches[0].pageX : e.pageX;
pageY = e.targetTouches ? e.targetTouches[0].pageY : e.pageY;
mouseX = pageX - rangeWrapperLeft;
mouseDy = (pageY - mouseInitialY) * mouseDyFactor;
newY = currentY + mouseY - pageY;
// alert(newY);
if (newY >= rangeMinY && newY <= rangeMaxY) {
currentY = newY;
mouseY = pageY;
} else {
currentY = newY < rangeMinY ? rangeMinY : rangeMaxY;
}
// After doing maths, update the value
updateValue();
}
}
// Handle `mouseup`, `mouseleave` and `touchend` events
function mouseUp() {
// Trigger elastic animation in case `y` value has changed
if (mouseDy) {
elasticRelease();
}
// Reset values
mouseY = mouseDy = 0;
}
// Events listeners
rangeWrapper.addEventListener('mousedown', mouseDown);
rangeWrapper.addEventListener('touchstart', mouseDown);
rangeWrapper.addEventListener('mousemove', mouseMove);
rangeWrapper.addEventListener('touchmove', mouseMove);
rangeWrapper.addEventListener('mouseup', mouseUp);
rangeWrapper.addEventListener('mouseleave', mouseUp);
rangeWrapper.addEventListener('touchend', mouseUp);
}

Why doesn't my Javascript code work on Mozilla and upper versions of IE? [duplicate]

Currently createPopup() is only supported in IE (See http://help.dottoro.com/ljsxcrhv.php).
Is there a universal createPopup() replacement? Or is conditional code required based on browser detection?
Hopefully, I am looking for something that not only provides the same functionality, but has the same interface or at least could provide the ingredients to create createPopup() clone without too much work.
So I had a whole mess of legacy code that used window.createPopup() so changing to a library would have been a lot of effort, and now that IE 11 doesn't support this method, we had to do something since our app is built to support Explorer. I was able to solve this to work in other browsers by writing the following code:
if(!window.createPopup){
window.createPopup = function (){
var popup = document.createElement("iframe"), //must be iframe because existing functions are being called like parent.func()
isShown = false, popupClicked = false;
popup.src = "about:blank";
popup.style.position = "absolute";
popup.style.border = "0px";
popup.style.display = "none";
popup.addEventListener("load", function(e){
popup.document = (popup.contentWindow || popup.contentDocument);//this will allow us to set innerHTML in the old fashion.
if(popup.document.document) popup.document = popup.document.document;
});
document.body.appendChild (popup);
var hidepopup = function (event){
if(isShown)
setTimeout(function (){
if(!popupClicked){
popup.hide();
}
popupClicked = false;
}, 150);//timeout will allow the click event to trigger inside the frame before closing.
}
popup.show = function (x, y, w, h, pElement){
if(typeof(x) !== 'undefined'){
var elPos = [0, 0];
if(pElement) elPos = findPos(pElement);//maybe validate that this is a DOM node instead of just falsy
elPos[0] += y, elPos[1] += x;
if(isNaN(w)) w = popup.document.scrollWidth;
if(isNaN(h)) h = popup.document.scrollHeight;
if(elPos[0] + w > document.body.clientWidth) elPos[0] = document.body.clientWidth - w - 5;
if(elPos[1] + h > document.body.clientHeight) elPos[1] = document.body.clientHeight - h - 5;
popup.style.left = elPos[0] + "px";
popup.style.top = elPos[1] + "px";
popup.style.width = w + "px";
popup.style.height = h + "px";
}
popup.style.display = "block";
isShown = true;
}
popup.hide = function (){
isShown = false;
popup.style.display = "none";
}
window.addEventListener('click', hidepopup, true);
window.addEventListener('blur', hidepopup, true);
return popup;
}
}
function findPos(obj, foundScrollLeft, foundScrollTop) {
var curleft = 0;
var curtop = 0;
if(obj.offsetLeft) curleft += parseInt(obj.offsetLeft);
if(obj.offsetTop) curtop += parseInt(obj.offsetTop);
if(obj.scrollTop && obj.scrollTop > 0) {
curtop -= parseInt(obj.scrollTop);
foundScrollTop = true;
}
if(obj.scrollLeft && obj.scrollLeft > 0) {
curleft -= parseInt(obj.scrollLeft);
foundScrollLeft = true;
}
if(obj.offsetParent) {
var pos = findPos(obj.offsetParent, foundScrollLeft, foundScrollTop);
curleft += pos[0];
curtop += pos[1];
} else if(obj.ownerDocument) {
var thewindow = obj.ownerDocument.defaultView;
if(!thewindow && obj.ownerDocument.parentWindow)
thewindow = obj.ownerDocument.parentWindow;
if(thewindow) {
if (!foundScrollTop && thewindow.scrollY && thewindow.scrollY > 0) curtop -= parseInt(thewindow.scrollY);
if (!foundScrollLeft && thewindow.scrollX && thewindow.scrollX > 0) curleft -= parseInt(thewindow.scrollX);
if(thewindow.frameElement) {
var pos = findPos(thewindow.frameElement);
curleft += pos[0];
curtop += pos[1];
}
}
}
return [curleft,curtop];
}
I'll start by admitting that it's pretty ugly. However, this worked for me to make the code that calls this method work in other browsers, and was easier than changing dozens of legacy (and poorly coded otherwise) pages to use some outside library, so perhaps it will help someone else out there.
It uses an iframe and creates a document property on it because we had a lot of code that was along the lines of popup.document.body.innerHTML = "<span onclick = 'parent.someFunction()'>";. Using the iframe instead of a div allows this to remain in it's junky state and still work.
You may want to look at some of the JavaScript libraries out there. Things like Dojo, Yahoo UI, or JQuery can help to encapsulate most of the browser-specific headaches. For example, with Dojo, take a look at http://dojotoolkit.org/api/. This would get you similar functionality to createPopup().
Whats up with window.open()?
http://www.w3schools.com/jsref/met_win_open.asp

Float DIV is not fixed

I install Float Left Right Advertising plugin on my site: www.displej.me and I set banners at the side of site. But when you scroll baners are not fixed, they follow page but they are refreshing and blinking. Also, when I'm scrolling down they stay fixed aside and later start to follow the page. Ths is JS code:
function FloatTopDiv()
{
startLX = ((document.body.clientWidth -MainContentW)/2) - (LeftBannerW+LeftAdjust) , startLY = TopAdjust;
startRX = ((document.body.clientWidth -MainContentW)/2) + (MainContentW+RightAdjust) , startRY = TopAdjust;
var d = document;
function ml(id)
{
var el=d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
el.sP=function(x,y){this.style.left=x + 'px';this.style.top=y + 'px';};
el.x = startRX;
el.y = startRY;
return el;
}
function m2(id)
{
var e2=d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
e2.sP=function(x,y){this.style.left=x + 'px';this.style.top=y + 'px';};
e2.x = startLX;
e2.y = startLY;
return e2;
}
window.stayTopLeft=function()
{
if (document.documentElement && document.documentElement.scrollTop)
var pY = document.documentElement.scrollTop;
else if (document.body)
var pY = document.body.scrollTop;
if (document.body.scrollTop > 200){startLY = 3;startRY = 3;} else {startLY = TopAdjust;startRY = TopAdjust;};
ftlObj.y += (pY+startRY-ftlObj.y)/1;
ftlObj.sP(ftlObj.x, ftlObj.y);
ftlObj2.y += (pY+startLY-ftlObj2.y)/1;
ftlObj2.sP(ftlObj2.x, ftlObj2.y);
setTimeout("stayTopLeft()", 1);
}
ftlObj = ml("divAdRight");
//stayTopLeft();
ftlObj2 = m2("divAdLeft");
stayTopLeft();
}
function ShowAdDiv()
{
var objAdDivRight = document.getElementById("divAdRight");
var objAdDivLeft = document.getElementById("divAdLeft");
objAdDivRight.style.display = "block";
objAdDivLeft.style.display = "block";
FloatTopDiv();
}
What to do? I try to change the numbers in the code but not sucsses.
clear:both
is something I would try to keep the sides free from the centered divs movements.

jQuery: change class after conditional is met

I created this site where you have multiple sliders moving vertically using this example on stackoverflow > here < along with this fiddle.
The site when loaded has an overflow: hidden on the body and position fixed on my main content div(div class="content-fs row"). The idea is that when you first arrive on the page, you scroll through each slide and once you hit the last one, the position changes on the main content div(div class="content-fs row") from fixed to static and the overflow: hidden is removed from the body. I'm having trouble writing the conditional statement that says "if its the last slider, change the position." The jquery below is the code i'm using for the site along with the conditional statement that doesn't work.
Any pointers/advice would be greatly appreciated!
jquery:
function scrollLax(){
/*
initialize
*/
var scrollDown = false;
var scrollUp = false;
var scroll = 0;
var $view = $('#portfolio');
var t = 0;
var h = $view.height() - 250;
$view.find('.portfolio-sliders').each(function() {
var $moving = $(this);
// position the next moving correctly
if($moving.hasClass('from-bottom')) {
$moving.css('top', h); // subtract t so that a portion of the other slider is showing
}
// make sure moving is visible
$moving.css('z-index', 10);
});
var $moving = $view.find('.portfolio-sliders:first-child');
$moving.css('z-index', 10);
/*
event handlers
*/
var mousew = function(e) {
var d = 0;
if(!e) e = event;
if (e.wheelDelta) {
d = -e.wheelDelta/3;
} else if (e.detail) {
d = e.detail/120;
}
parallaxScroll(d);
}
if (window.addEventListener) {
window.addEventListener('DOMMouseScroll', mousew, false);
}
window.onmousewheel = document.onmousewheel = mousew;
/*
parallax loop display loop
*/
window.setInterval(function() {
if(scrollDown)
parallaxScroll(4);
else if(scrollUp)
parallaxScroll(-4);
}, 50);
function parallaxScroll(scroll) {
// current moving object
var ml = $moving.position().left;
var mt = $moving.position().top;
var mw = $moving.width();
var mh = $moving.height();
// calc velocity
var fromBottom = false;
var vLeft = 0;
var vTop = 0;
if($moving.hasClass('from-bottom')) {
vTop = -scroll;
fromBottom = true;
}
// calc new position
var newLeft = ml + vLeft;
var newTop = mt + vTop;
// check bounds
var finished = false;
if(fromBottom && (newTop < t || newTop > h)) {
finished = true;
newTop = (scroll > 0 ? t : t + h);
}
// set new position
$moving.css('left', newLeft);
$moving.css('top', newTop);
// if finished change moving object
if(finished) {
// get the next moving
if(scroll > 0) {
$moving = $moving.next('.portfolio-sliders');
if($moving.length == 0)
$moving = $view.find('.portfolio-sliders:last');
//this is where I am trying to add the if conditional statement.
if ('.portfolio-sliders:last')
$('.content-fs.row').css({'position': 'static'});
if('.portfolio-sliders:last' && (mt == 0))
$('html, body').removeClass('overflow');
} else {
$moving = $moving.prev('.portfolio-sliders');
if($moving.length == 0)
$moving = $view.find('.portfolio-sliders:first-child');
//reverse the logic and if last slide change position
if('.portfolio-sliders:first-child')
$('.content-fs.row').css({'position': 'fixed'});
}
}
// for debug
//$('#direction').text(scroll + "/" + t + " " + ml + "/" + mt + " " + finished + " " + $moving.text());
}
}
Your code as it is simply asks whether .portfolio-sliders:last exists. Seems you should be doing:
if ($moving == $('.portfolio-sliders:last') )
or something along those lines, instead checking whether the active slide is the last.

Adobe AIR application remember and set window state in JavaScript

I have a single window AIR application created with FlashDevelop and would like it to remember the size and position of the window when the user closes it. When it re opens it would resize and go to that position.
Found an AS3 script that will do that but my application has no AS3. There is only an html and js file.
When the window is closed it should save the state of the window and when it's opened it should load the saved state and resize/move to the saved state. Here is what I have on $(document).ready
var width = screen.width;
var height = screen.height;
var p=new DOMParser();
var xml,x,y,windowWidth,windowHeight;
var f = window.runtime.flash.filesystem.File
.applicationDirectory.resolvePath("appPosition.xml");
if (f.exists){
var s = new window.runtime.flash.filesystem.FileStream();
try {
s.open(f,window.runtime.flash.filesystem.FileMode.READ);
xml=p.parseFromString(s.readUTFBytes(s.bytesAvailable),"text/xml");
x = parseInt(xml.childNodes[0].getAttribute("x"),10);
y = parseInt(xml.childNodes[0].getAttribute("y"),10);
windowWidth = parseInt(xml.childNodes[0].getAttribute("width"),10);
windowHeight =
parseInt(xml.childNodes[0].getAttribute("height"),10);
x = (x >= width) ? 20 : x;
y = (y >= height) ? 0 : y;
x = (x <= (width*-1)) ? 20 : x;
y = (y <= (height*-1)) ? 0 : y;
if (windowWidth >= (width-60) && windowHeight >= (height-60)) {
//the x and y are not set
window.runtime.flash.display.NativeWindow.x =20;
window.runtime.flash.display.NativeWindow.y = 0;
window.resizeTo(900,600);
// not yet sure if the following works
window.runtime.flash.display.NativeWindow.maximize();
}else{
// x and y don't do anything here either
window.runtime.flash.display.NativeWindow.x = x;
window.runtime.trace("sitting window x:",x);
window.runtime.flash.display.NativeWindow.y = y;
window.resizeTo(windowWidth,windowHeight);
}
}catch (e) {
window.runtime.trace(e.message);
}finally{
s.close();
}
return;
When the window is closed I want my function to save the state of the window but whatever I try the function is never called: $(window).on("close"... or window.onclose= or <document onunluoad=... The lengthy guide doesn't seem to have anything on how to get the current window:
http://wwwimages.adobe.com/www.adobe.com/content/dam/Adobe/en/devnet/scripting/pdfs/javascript_tools_guide.pdf
Creating windows is covered and once having it you can manipulate it but I never create a window, the application.xml looks like this:
...
<initialWindow>
<title>App Title</title>
<content>main.html</content>
...
So I have the following questions:
How do I add event listeners to the current window?
How do I set current window x and y when it loads?
Can I size and move the window before it is visible as right now it
seems to resize but looks kind of flaky as it opens initially at
default size and then reiszes to the previously stored values.
Solved it using window.nativeWindow (note the lower case n of nativeWindow, it's upper case in AS3). Here is the code:
$(document).ready(function(){
var width = screen.width;
var height = screen.height;
var p=new DOMParser();
var xml,x,y,windowWidth,windowHeight;
var f = window.runtime.flash.filesystem.File
.applicationDirectory.resolvePath("appPosition.xml");
if (f.exists){
var s = new window.runtime.flash.filesystem.FileStream();
try {
s.open(f,window.runtime.flash.filesystem.FileMode.READ);
xml=p.parseFromString(s.readUTFBytes(s.bytesAvailable),"text/xml");
x = parseInt(xml.childNodes[0].getAttribute("x"),10);
y = parseInt(xml.childNodes[0].getAttribute("y"),10);
windowWidth = parseInt(xml.childNodes[0]
.getAttribute("width"),10);
windowHeight = parseInt(xml.childNodes[0]
.getAttribute("height"),10);
x = (x >= width) ? 20 : x;
y = (y >= height) ? 0 : y;
x = (x <= (width*-1)) ? 20 : x;
y = (y <= (height*-1)) ? 0 : y;
if (windowWidth >= (width-60) && windowHeight >= (height-60)) {
window.nativeWindow.x =20;
window.nativeWindow.y = 0;
window.resizeTo(866,600);
window.nativeWindow.height = height-60;
window.nativeWindow.maximize();
}else{
window.nativeWindow.x = x;
window.nativeWindow.y = y;
window.resizeTo(windowWidth,windowHeight);
}
}catch (e) {
window.runtime.trace(e.message);
}finally{
s.close();
window.nativeWindow.visible=true;
}
return;
}
try{
window.nativeWindow.x = 20;
window.nativeWindow.y = 0;
window.nativeWindow.width = 866;
window.nativeWindow.height = height-60;
window.nativeWindow.visible=true;
}catch(e){
window.runtime.trace(e.message);
}
window.nativeWindow.addEventListener
(window.runtime.flash.events.Event.CLOSING, function(e){
var xml = '<position x="'+window.nativeWindow.x
+'" y="'+window.nativeWindow.y+'" width="'
+ window.nativeWindow.width + '" height="'
+ window.nativeWindow.height + '"/>';
var f = window.runtime.flash.filesystem.File.
applicationDirectory.resolvePath("appPosition.xml");
f = new window.runtime.flash.filesystem.File(f.nativePath);
var s = new window.runtime.flash.filesystem.FileStream();
try{
s.open(f,window.runtime.flash.filesystem.FileMode.WRITE);
s.writeUTFBytes(xml);
}catch (e){
window.runtime.trace(e.message);
}finally{
s.close();
}
});
});
In the application.xml:
<initialWindow>
<title>app title</title>
<content>main.html</content>
<systemChrome>standard</systemChrome>
<transparent>false</transparent>
<visible>false</visible>
Setting visible false makes it smoothly appear in the last position the user closed it.

Categories

Resources