Detect initial device orientation values - javascript

I'm trying to manually create a parallax effect of sorts, and so far here's my JavaScript:
var bottom = document.getElementById("bottom");
var top = document.getElementById("top");
window.addEventListener("deviceorientation", function(e) {
var gamma = e.gamma;
var beta = e.beta;
$(bottom).css('left',(gamma/2)+'px').css('top',(beta/2)+'px');
$(top).css('left',(gamma)+'px').css('top',(beta)+'px');
});
So far its working great and I have the effect I want, but the starting position of the device is not quite what I want. Currently the alpha, beta, and gamma values are only at 0,0,0 if the device is flat on the table. What I want to do is that when you load the page, that position is taken as 0,0,0.
For example, if I am reading my phone in my hand, then of course my phone is going to be at an angle already, and I want to take this starting position as 0,0,0 when the page is loaded.
So to put that into some sort of pseudo code, here's what I'm trying to achieve:
gammaOnLoad and betaOnLoad = initial device orientation
gammaCurrent and betaCurrent = e.gamma and e.beta (from event listener)
gammaDifference and betaDifference = Math.abs(gammaOnLoad - gammaCurrent)
$(elem).css('left', gammaDifference + 'px').css('top', betaDifference + 'px');
So essentially you take in the values when loading the page and use those as 0, your point of origin. This means that whatever angle your phone is at, when you load the page the image will always look normal and from there it will begin the parallax effect.

I wanted to do the same thing as you. This is very basic, but it seems to work:
$(document).ready(function() {
var origLR, origFB;
function setOrigin(eventData) {
origLR = eventData.gamma;
origFB = eventData.beta;
}
if (window.DeviceOrientationEvent) {
window.addEventListener('deviceorientation', setOrigin, false);
setTimeout(function() {
window.removeEventListener('deviceorientation', setOrigin, false);
window.addEventListener('deviceorientation', function(eventData) {
var tiltLR = eventData.gamma,
tiltFB = eventData.beta;
tiltLR = (origLR - tiltLR);
tiltFB = (origFB - tiltFB);
deviceOrientationHandler(tiltLR, tiltFB);
}, false);
}, 100);
};
function deviceOrientationHandler(tiltLR, tiltFB) {
$('.bottom').css('transform','translateX(' + (tiltLR/5) + 'px) translateY(' + (tiltFB/5) + 'px)');
$('.top').css('transform','translateX(' + (tiltLR/2.5) + 'px) translateY(' + (tiltFB/2.5) + 'px)');
}
});
I added an event listener for 100ms that sets the initial device orientation values, then removed it and replaced it with one that calculates the difference between initial and current.
This can probably be more efficient, I'm not a particularly experienced programmer.

Related

Adjust the scrolling speed when scrolling by dragging

I have a page on a website i am working on, that includes many images in a div in a grid (map). I made the div show a scroll bar at overflow and used jquery to enable scrolling via dragging and it works as intented with only a hundred or so showing at a time.
My only issue is, that since there are thousands of small images, moving the mouse only a bit will already result in blowing past a lot of objects.
My question now is, how can i modify my code, so that moving the mouse over the screen once will only scroll about one tenth of the div's width. So basically i want to reduce the scrolling speed.
I am super new to javascript etc. so please be patient.
<div id="map" class="center unselectable overflow">
lots of images here in a grid</div>
<script>
var clicked = false, clickY, clickX;
var map = document.getElementById('map');
$(document).on({
'mousemove': function(e) {
clicked && updateScrollPos(e);
},
'mousedown': function(e) {
clicked = true;
clickY = e.pageY;
clickX = e.pageX;
},
'mouseup': function() {
clicked = false;
$('html').css('cursor', 'auto');
}
});
var updateScrollPos = function(e) {
$('html').css('cursor', 'row-resize');
$(map).scrollTop($(map).scrollTop() + (clickY - e.pageY));
$(map).scrollLeft($(map).scrollLeft() + (clickX - e.pageX));
}
</script>
TLDR: how to I reduce the drag to scroll speed in jQuery?
A little more elabouration from my comment: it seems like you are trying to dampen the scrolling speed. Mathematically, this means all you need is to reduce the value you feed to the .scrollTop() and .scrollLeft() functions. This can be done by dividing them by a set, arbitrarily determined factor, so that the transformation is linear. An example will be, if you want to dampen your scrolling speed by a factor of 10×, then you simply divide the values by 10:
var updateScrollPos = function(e) {
var scrollTop = $(map).scrollTop() + (clickY - e.pageY);
var scrollLeft = $(map).scrollLeft() + (clickX - e.pageX);
$('html').css('cursor', 'row-resize');
$(map).scrollTop(scrollTop / 10);
$(map).scrollLeft(scrollLeft / 10);
}
Pro-tip: since you are accessing $(map) several times, you can (micro)optimize your code by caching it:
var updateScrollPos = function(e) {
var $map = $(map);
var scrollTop = $map.scrollTop() + (clickY - e.pageY);
var scrollLeft = $map.scrollLeft() + (clickX - e.pageX);
$('html').css('cursor', 'row-resize');
$map.scrollTop(scrollTop / 10);
$map.scrollLeft(scrollLeft / 10);
}

Position element in centre of visible viewport window with overflow-y:scroll

I've rather roughly built this website which uses an effect similar to the iOS Safari tab view to look at various pages of a virtual book. Everything is working fine apart from the fact that I can't centre each page in the visible viewport. For example if you scroll down to the final 'page' and click on it, it jumps to the top of the document, instead of staying in the centre of the visible viewport.
I think this is to do with the fact that the scrollable div uses overflow-y:scroll, but I just can't figure out for the life of me how to fix the problem.
Any help would be greatly appreciated!!
Here's my jQuery:
jQuery(document.body).on('click', '.page', function() { //Change to touchstart
// Generate number between 1 + 2
var randomClass = 3;
var randomNumber = Math.round(Math.random() * (randomClass - 1)) + 1;
// Initialise & Random Number
jQuery(this).addClass("activated").addClass('scaled-' + randomNumber);
// Exiting - Reset All
jQuery(document.body).on('click', '.activated', function() { //Change to Touchstart
jQuery(this).removeClass("activated scaled-1 scaled-2 scaled-3");
});
});
And here is a jsfiddle with all my code in it so you can get a better idea of what I'm trying to achieve.
https://jsfiddle.net/ontu1ngq/
Thanks!
You need to get the amount that #wrapper has been scrolled, so that you can use that to set the top of the .page accordingly. Then, when you remove the .activated class, you will just need to remove the inline top style.
jQuery(document.body).on('click', '.page', function() {
var randomClass = 3;
var randomNumber = Math.round(Math.random() * (randomClass - 1)) + 1;
jQuery(this).addClass("activated").addClass('scaled-' + randomNumber);
var wrapper_scrollTop = $("#wrapper").scrollTop(); //gets amount scrolled
var half_wrapper = $("#wrapper").height()*(0.5); //50% of wrapper height
jQuery(this).css("top",half_wrapper+wrapper_scrollTop);
jQuery(document.body).on('click', '.activated', function() {
jQuery(this).removeClass("activated scaled-1 scaled-2 scaled-3");
jQuery(this).css("top","") //returns top to original value specified in css
});
});
Check out this working fiddle: https://jsfiddle.net/tardhepc/1/

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.

Creating a clickable progress bar

What I'm essentially building is a webkit based controller that communicates with a program called Ecoute.app.
The controller has a progressbar that indicates the progress made through the currently playing song, but I want to make this bar's position adjustable with a click.
function barClick() {
var progress = Ecoute.playerPosition();
var width = 142.5;
var percentElapsed = progress / length;
var position = width * percentElapsed;
Ecoute.setPlayerPosition(position);
}
Is what I have, with Ecoute.playerPosition() returning the player's current position.
Width has previously been defined as a dynamic value at
var width = 142.5 / length * progress + 1.63;
With length being the current track length and progress being the player's position. This has been able to dynamically stretch a progression overlay image to indicate the position of the track via the desktop controller.
However, the max width used in the second function does not appear to allow the first function to work properly.
Any help possibly determining the correct value or approach would be hugely appreciated.
It is hard to really know where you are getting stuck. My guess is you are having problems getting the click to work and determining where to set the progress.
My solution is to have 2 elements, one wrapping the other. The outer element takes the click event and the size gets reflected by the inner element. You will have to do your own work integrating with the Ecoute player but I showed how to calculate the percentage.
var outside = document.getElementById('outside');
var inside = document.getElementById('inside');
outside.addEventListener('click', function(e) {
inside.style.width = e.offsetX + "px";
// calculate the %
var pct = Math.floor((e.offsetX / outside.offsetWidth) * 100);
inside.innerHTML = pct + " %";
}, false);
I didn't bother with any cross browser work since this is for a webkit based application.
Demo: http://jsbin.com/ubana3/5
In your HTML,
0% played< /progress>
In JQuery,
mediaPlayer = document.getElementById(playerId);
progressBar = document.getElementById('progress-bar');
progressBar.addEventListener('click', function(e) {
var percentage = Math.floor((e.offsetX / this.offsetWidth) * 100);
mediaPlayer.currentTime = mediaPlayer.duration*(percentage/100);
progressBar.value = percentage;
progressBar.innerHTML = percentage + '% played';
});

How to detect mouse acceleration in javascript?

I'm logging the mouse movements in a web app.
I'd like to detect the mouse acceleration on a platform (e.g. Windows). Is it possible to do it from javascript, even just in an approximated way? I could ask the user to check their settings with a questionnaire, but it would be much better to detect it automatically.
Cheers
Check distance the mouse has moved over a set interval of time:
var mX:Number = _xmouse;
var mY:Number = _ymouse;
function checkDistance()
{
clear();
//trace('new distance: ' + Math.sqrt(Math.pow((mY - _ymouse), 2) + Math.pow((mX - _xmouse), 2)));
lineStyle(1, 0x000000);
moveTo(mX, mY);
lineTo(_xmouse, _ymouse);
mX = _xmouse;
mY = _ymouse;
}
setInterval(checkDistance, 1000);
from http://www.kirupa.com/forum/showthread.php?t=332961

Categories