I have a smooth scrolling script that scrolls you down to a section when you click a link. The script has worked in Firefox on multiple computers but has only worked on Chrome on one computer.
link.linkName.onclick = function() {
clearInterval(scroll);
var viewport = window.innerHeight;
var scroll = setInterval(function() {
document.documentElement.scrollTop += 25;
if (document.documentElement.scrollTop >= viewport * 3) {
clearInterval(scroll);
document.documentElement.scrollTop = viewport * 3;
}
}, 10);
};
Related
Some context:
I'm working on a Chrome Extension where the user can launch it via default "popup.html", or if the user so desires this Extension can be detached from the top right corner and be used on a popup window via window.open
This question will also apply for situations where users create a Shortcut for the extension on Chrome via:
"..." > "More tools" > "Create Shortcut"
Problem:
So what I need is for those cases where users use the extension detached via window.open or through a shortcut, when navigating through different options, for the Height of the window to be resized smoothly.
I somewhat achieve this but the animation is clunky and also the final height is not always the same. Sometimes I need to click twice on the button to resize too because 1 click won't be enough. Another issue is there is also some twitching of the bottom text near the edge of the window when navigating.
Here's what I got so far:
(strWdif and strHdif are used to compensate for some issues with CSS setting proper sizes which I haven't figured out yet.)
const popup = window;
function resizeWindow(popup) {
setTimeout(function () {
var strW = getComputedStyle(window.document.querySelector(".body_zero")).getPropertyValue("width");
var strW2 = strW.slice(0, -2);
var strWdif = 32;
var bodyTargetWidth = (parseFloat(strW2) + parseFloat(strWdif));
var strH = getComputedStyle(window.document.querySelector(".body_zero")).getPropertyValue("height");
var strH2 = strH.slice(0, -2);
var strHdif = 54;
var bodyTargetHeight = (parseFloat(parseInt(strH2)) + parseFloat(strHdif));
var height = window.innerHeight;
console.log("Window Height: ", height, "CSS Height: ", bodyTargetHeight);
var timer = setInterval(function () {
if (height < bodyTargetHeight) {
popup.resizeTo(bodyTargetWidth, height += 5);
if (height >= bodyTargetHeight) {
clearInterval(timer);
}
} else if (height > bodyTargetHeight) {
popup.resizeTo(bodyTargetWidth, height -= 5);
if (height <= bodyTargetHeight) {
clearInterval(timer);
}
} else {
clearInterval(timer);
}
}, 0);
}, 0400);
}
Question:
Is there a way to make this more responsive, and smooth and eliminate all the twitching and clunkiness?
I guess the issue might be that I am increasing/diminishing by 5 pixels at a time but that is the speed I need. Maybe there is another way to increase/decrease by 1px at a faster rate? Could this be the cause of the twitching and clunkiness?
Also, I should add that troubleshooting this is difficult because the browser keeps crashing so there is also a performance issue sometimes when trying different things.
EDIT:
Another option using resizeBy:
function animateClose(time) {
setTimeout(function () {
var strW = getComputedStyle(window.document.querySelector(".body_zero")).getPropertyValue("width");
var strW2 = strW.slice(0, -2);
var strWdif = 32;
var bodyTargetWidth = (parseFloat(strW2) + parseFloat(strWdif));
var strH = getComputedStyle(window.document.querySelector(".body_zero")).getPropertyValue("height");
var strH2 = strH.slice(0, -2);
var strHdif = 54;
var bodyTargetHeight = (parseFloat(parseInt(strH2)) + parseFloat(strHdif));
var w = window.innerWidth; //Get window width
var h = window.innerHeight; //Get window height
var loops = time * 0.1; //Get nb of loops
var widthPercentageMinus = (w / loops) * -0;
var heightPercentageMinus = (h / loops) * -1;
var widthPercentagePlus = (w / loops) * +0;
var heightPercentagePlus = (h / loops) * +1;
console.log("Window Height: ", h, "CSS Height: ", bodyTargetHeight);
var loopInterval = setInterval(function () {
if (h > bodyTargetHeight) {
window.resizeBy(widthPercentageMinus, heightDecrheightPercentageMinuseasePercentageMinus);
} else if (h < bodyTargetHeight) {
window.resizeBy(widthPercentagePlus, heightPercentagePlus);
} else {
clearInterval(loopInterval);
}
}, 1);
}, 0400);
}
This one is a bit more smooth but I can't make it stop at the desired Height. It also is not differentiating between resizing up or down, also crashes the browser sometimes.
maybe with requestAnimationFrame
try something like this (not tested):
function resizeWindow(popup) {
var gcs = getComputedStyle(window.document.querySelector(".body_zero"));
var strW = gcs.getPropertyValue("width");
var strW2 = strW.slice(0, -2);
var strWdif = 32;
var bodyTargetWidth = (parseFloat(strW2) + parseFloat(strWdif));
var strH = gcs.getPropertyValue("height");
var strH2 = strH.slice(0, -2);
var strHdif = 54;
var bodyTargetHeight = (parseFloat(parseInt(strH2)) + parseFloat(strHdif));
var height = window.innerHeight;
console.log("Window Height: ", height, "CSS Height: ", bodyTargetHeight);
window.myRequestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame;
var hStep = 2; //choose the step. Must be an integer
function internalFunc() {
if (Math.abs(height - bodyTargetHeight) > hStep) {
if (height < bodyTargetHeight)
hStep *= 1;
else if (height > bodyTargetHeight)
hStep *= -1;
popup.resizeBy(0, hStep);
height += hStep;
window.myRequestAnimationFrame(internalFunc)
} else
popup.resizeBy(0, bodyTargetHeight - height)
}
popup.resizeTo(bodyTargetWidth, height);
window.myRequestAnimationFrame(internalFunc)
}
<html>
<head>
<script>
const bodyTargetWidth = 150;
const bodyTargetHeight = 250; //target height
var height; //height at beginning
window.myRequestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame;
var hStep = 5; //choose the step. Must be an integer
var dir;
var myPopup;
function doResize() {
function internalFunc() {
console.log('height: ', height) ;
if (Math.abs(height - bodyTargetHeight) > hStep) {
dir = Math.sign(bodyTargetHeight - height);
myPopup.resizeBy(0, dir * hStep);
height += dir * hStep;
window.myRequestAnimationFrame(internalFunc)
} else
myPopup.resizeBy(0, bodyTargetHeight - height)
}
if (!myPopup || myPopup?.closed) {
myPopup = window.open("about:blank", "hello", "left=200,top=200,menubar=no,status=no,location=no,toolbar=no");
height = 150;
myPopup.resizeTo(bodyTargetWidth, height);
} else {
myPopup.focus();
height = myPopup.outerHeight
}
myPopup.resizeTo(bodyTargetWidth, height);
window.myRequestAnimationFrame(internalFunc)
}
document.addEventListener('DOMContentLoaded', _ => document.getElementById('myBtn').addEventListener('click', doResize))
</script>
</head>
<body>
<button type="button" id="myBtn">Create popup<br>\<br>Reset popup height</button><br>
<p>First create the popup, then change popup height and click the button above again</p>
</body>
</html>
I have a functionality on the site I am developing, which resizes a block when you scroll. I do it with two functions:
headerHeight: function () {
this.header = window.innerHeight + 50
this.minHeader = this.header - 300;
this.maxHeader = this.header + 300;
},
handleScroll: function () {
var hotOffsetTop = this.getElementOffset(document.querySelectorAll('.hot')[0]).top;
var scrollPos = window.pageYOffset || document.documentElement.scrollTop;
if (this.lastScrollPos != 0 && scrollPos !=0 && scrollPos < hotOffsetTop) {
let h = hotOffsetTop - scrollPos
let difInPercent = Math.floor((h / 1200) * 100)
let a = (difInPercent * (this.maxHeader - this.minHeader)) / 100
this.header = this.minHeader + a;
}
this.lastScrollPos = scrollPos;
},
When the page is opened these functions are called like that:
this.headerHeight();
window.addEventListener('scroll', this.handleScroll);
getElementOffset is just a function which returns an object with top and left offsets of an element.
The idea is: this header covers all your screen and whe you scroll down it resizes, so it looks like parallax-ish thing and the second block appears faster than you scroll. And when you scroll back, this header covers full screen height again
You can see this in action here: https://zapomni-7b57b.firebaseapp.com/
My problem is that this works well on desktop and in mobile view in chrome, but it doesn't work well on android chrome. Sometimes this block doesn't resize and in most cases when you scroll to top it doesn't cover all screen(it does on desktop). Probably this problem is present on iOS too.
I'm looking to make something exactly like Facebook's Android app's UX for swiping between News Feed, Friend Requests, Messages, and Notifications. You should be able to "peek" at the next view by panning to the right of left, and it should snap to the next page when released if some threshold has been passed or when swiped.
Every scroll snap solution I've seen only snaps after the scrolling stops, whereas I only ever want to scroll one page at a time.
EDIT: Here's what I have so far. It seems to work fine when emulating an Android device in Google Chrome, but doesn't work when I run it on my Galaxy S4 running 4.4.2. Looking into it a bit more, it looks like touchcancel is being fired right after the first touchmove event which seems like a bug. Is there any way to get around this?
var width = parseInt($(document.body).width());
var panThreshold = 0.15;
var currentViewPage = 0;
$('.listContent').on('touchstart', function(e) {
console.log("touchstart");
currentViewPage = Math.round(this.scrollLeft / width);
});
$('.listContent').on('touchend', function(e) {
console.log("touchend");
var delta = currentViewPage * width - this.scrollLeft;
if (Math.abs(delta) > width * panThreshold) {
if (delta < 0) {
currentViewPage++;
} else {
currentViewPage--;
}
}
$(this).animate({
scrollLeft: currentViewPage * width
}, 100);
});
In case anyone wants to do this in the future, the only way I found to actually do this was to manually control all touch events and then re-implement the normally-native vertical scrolling.
It might not be the prettiest, but here's a fiddle to what I ended up doing (edited to use mouse events instead of touch events): http://jsfiddle.net/xtwzcjhL/
$(function () {
var width = parseInt($(document.body).width());
var panThreshold = 0.15;
var currentViewPage = 0;
var start; // Screen position of touchstart event
var isHorizontalScroll = false; // Locks the scrolling as horizontal
var target; // Target of the first touch event
var isFirst; // Is the first touchmove event
var beginScrollTop; // Beginning scrollTop of ul
var atanFactor = 0.6; // atan(0.6) = ~31 degrees (or less) from horizontal to be considered a horizontal scroll
var isMove = false;
$('body').on('mousedown', '.listContent', function (e) {
isMove = true;
isFirst = true;
isHorizontalScroll = false;
target = $(this);
currentViewPage = Math.round(target.scrollLeft() / width);
beginScrollTop = target.closest('ul').scrollTop();
start = {
x: e.originalEvent.screenX,
y: e.originalEvent.screenY
}
}).on('mousemove', '.listContent', function (e) {
if (!isMove) {
return false;
}
e.preventDefault();
var delta = {
x: start.x - e.originalEvent.screenX,
y: start.y - e.originalEvent.screenY
}
// If already horizontally scrolling or the first touchmove is within the atanFactor, horizontally scroll, otherwise it's a vertical scroll of the ul
if (isHorizontalScroll || (isFirst && Math.abs(delta.x * atanFactor) > Math.abs(delta.y))) {
isHorizontalScroll = true;
target.scrollLeft(currentViewPage * width + delta.x);
} else {
target.closest('ul').scrollTop(beginScrollTop + delta.y);
}
isFirst = false;
}).on('mouseup mouseout', '.listContent', function (e) {
isMove = false;
isFirst = false;
if (isHorizontalScroll) {
var delta = currentViewPage * width - target.scrollLeft();
if (Math.abs(delta) > width * panThreshold) {
if (delta < 0) {
currentViewPage++;
} else {
currentViewPage--;
}
}
$(this).animate({
scrollLeft: currentViewPage * width
}, 100);
}
});
});
In my client's website, (http://slnyaadev45.herokuapp.com/),I have used a JS slider on the top. It will contiguously move the images across the site. In Firefox, it works perfectly. But in Google Chrome, it doesn't. Sometimes it work but if I reload the page it stops working. Sometimes, it start to work. Then if I just click a link to another page, it will still work. But if I reload, it breaks again. The problem is also there in the Android's default browser. What is going wrong? How to fix it?
PS : The site is built with Rails 3.2.
The javascript :
$(function(){
var scroller = $('#scroller div.innerScrollArea');
var scrollerContent = scroller.children('ul');
scrollerContent.children().clone().appendTo(scrollerContent);
var curX = 0;
scrollerContent.children().each(function(){
var $this = $(this);
$this.css('left', curX);
curX += $this.width();
});
var fullW = curX / 2;
var viewportW = scroller.width();
// Scrolling speed management
var controller = {curSpeed:0, fullSpeed:1};
var $controller = $(controller);
var tweenToNewSpeed = function(newSpeed, duration)
{
if (duration === undefined)
duration = 600;
$controller.stop(true).animate({curSpeed:newSpeed}, duration);
};
// Pause on hover
scroller.hover(function(){
tweenToNewSpeed(0);
}, function(){
tweenToNewSpeed(controller.fullSpeed);
});
// Scrolling management; start the automatical scrolling
var doScroll = function()
{
var curX = scroller.scrollLeft();
var newX = curX + controller.curSpeed;
if (newX > fullW*2 - viewportW)
newX -= fullW;
scroller.scrollLeft(newX);
};
setInterval(doScroll, 20);
tweenToNewSpeed(controller.fullSpeed);
});
because the distance between the elements is 4px, set the ''left'' of each element is equal to previous elements widths sum
OR
you can remove position:absolute for style of li, and add float:left
Because all my images have the same size, I added the width in this line of the script :
curX += $this.width();
as :
curX += 224;
I have a problem with Safari in a web application that contains a position:fixed element. When the page is zoomed out (smaller 100%) things break and would need to be fixed by calling a function. So I'd like to detect the user's zooming. I found this jQueryPlug-in a while ago:
http://mlntn.com/2008/12/11/javascript-jquery-zoom-event-plugin/
http://mlntn.com/demos/jquery-zoom/
It detects keyboard and mouse events that might lead to a page zoom level change. Fair enough. It works on current FF and IE but not on Safari. Any ideas what could be done to do something simmilar in current WebKit browsers?
It's not a direct duplicate of this question since that deals with Mobile Safari, but the same solution will work.
When you zoom in, window.innerWidth is adjusted, but document.documentElement.clientWidth is not, therefore:
var zoom = document.documentElement.clientWidth / window.innerWidth;
Furthermore, you should be able to use the onresize event handler (or jQuery's .resize()) to check for this:
var zoom = document.documentElement.clientWidth / window.innerWidth;
$(window).resize(function() {
var zoomNew = document.documentElement.clientWidth / window.innerWidth;
if (zoom != zoomNew) {
// zoom has changed
// adjust your fixed element
zoom = zoomNew
}
});
There is a nifty plugin built from yonran that can do the detection. Here is his previously answered question on StackOverflow. It works for most of the browsers. Application is as simple as this:
window.onresize = function onresize() {
var r = DetectZoom.ratios();
zoomLevel.innerHTML =
"Zoom level: " + r.zoom +
(r.zoom !== r.devicePxPerCssPx
? "; device to CSS pixel ratio: " + r.devicePxPerCssPx
: "");
}
Demo
srceen.width is fixed value but where as window.innerWidth value will change as per the zoom effect. please try the below code:
$(window).resize(function() {
if(screen.width == window.innerWidth){
alert("you are on normal page with 100% zoom");
} else if(screen.width > window.innerWidth){
alert("you have zoomed in the page i.e more than 100%");
} else {
alert("you have zoomed out i.e less than 100%");
}
});
Differentiate between window resize, browser zoom change, and system dpi change
;(() => {
const last = {
devicePixelRatio: devicePixelRatio,
innerWidth: innerWidth,
innerHeight: innerHeight,
outerWidth: outerWidth,
outerHeight: outerHeight,
}
const browser = navigator.appVersion.includes('WebKit')
const almostZero = n => n <= 1 && n >= -1
window.addEventListener('resize', () => {
if (last.devicePixelRatio !== devicePixelRatio) {
if (browser ? almostZero(last.innerWidth - innerWidth) && almostZero(last.innerHeight - innerHeight)
:almostZero(last.outerWidth - outerWidth) && almostZero(last.outerHeight - outerHeight)) {
console.log('system wide dpi change')
} else {
console.log('browser level zoom change')
}
} else {
console.log('window resize')
}
last.devicePixelRatio = devicePixelRatio
last.innerWidth = innerWidth
last.innerHeight = innerHeight
last.outerWidth = outerWidth
last.outerHeight = outerHeight
})
})()
Works in Chrome & Firefox on Windows