I'm trying to implement touch evens with jGestures. swipeone works fine but anything else (swipeleft, swiperight etc) is not firing.
<div id="wrap" style="height:500px; width:500px; background: blue;">
</div>
<script type="text/javascript">
$('#wrap').bind('swipeleft', function(){
alert("test");
});
</script>
This is just a test page I did. It was actually working at one point in my main project but seemed to have stopped for no reason at all, not even when I reverted to an older version. I've tried a different version of jGestures with no luck.
SwipeLeft, SwipeRight, -Up and -Down are kind of poorly implemented. They are only triggered if you stay EXACTLY on the axis where you started the touch event.
For example, SwipeRight will only work if your finger moves from (X,Y) (120, 0) to (250, 0).
If the Y-Coordinates from Start- and Endpoint differ, it's not gonna work.
jGestures.js (ca. line 1095) should better look something like this (readable):
/**
* U Up, LU LeftUp, RU RightUp, etc.
*
* \U|U/
* LU\|/RU
*L---+---R
* LD/|\RD
* /D|D\
*
*/
if ( _bHasTouches && _bHasMoved === true && _bHasSwipeGesture===true) {
_bIsSwipe = true;
var deltaX = _oDetails.delta[0].lastX;
var deltaY = _oDetails.delta[0].lastY;
var hor = ver = '';
if (deltaX > 0) { // right
hor = 'right';
if (deltaY > 0) {
ver = 'down'
} else {
ver = 'up';
}
if (Math.abs(deltaY) < deltaX * 0.3) {
ver = '';
} else if (Math.abs(deltaY) >= deltaX * 2.2) {
hor = '';
}
} else { // left
hor = 'left';
if (deltaY > 0) {
ver = 'down'
} else {
ver = 'up';
}
if (Math.abs(deltaY) < Math.abs(deltaX) * 0.3) {
ver = '';
} else if (Math.abs(deltaY) > Math.abs(deltaX) * 2.2) {
hor = '';
}
}
// (_oDetails.delta[0].lastX < 0) -> 'left'
// (_oDetails.delta[0].lastY > 0) -> 'down'
// (_oDetails.delta[0].lastY < 0) -> 'up'
// alert('function swipe_' + hor + '_' + ver);
_oDetails.type = ['swipe', hor, ver].join('');
_$element.triggerHandler(_oDetails.type, _oDetails);
}
try this:
$('#wrap').bind('swipeone', function (event, obj) {
var direction=obj.description.split(":")[2]
if(direction=="left"){
doSomething();
}
});
This is already answered here:
stackoverflow about jGesture swipe events
The trick is:
… .bind('swipeone swiperight', …
You have to bind it to both events. only swiperight won't work. took me 3 hrs to figure that out :D
Best,
Rico
replace the cases on line 1326 in version 0.90.1 with this code
if ( _bHasTouches && _bHasMoved === true && _bHasSwipeGesture===true) {
_bIsSwipe = true;
_oDetails.type = 'swipe';
_vLimit = $(window).height()/4;
_wLimit = $(window).width()/4;
_sMoveY = _oDetails.delta[0].lastY;
_sMoveX = _oDetails.delta[0].lastX;
_sMoveYCompare = _sMoveY.toString().replace('-','');
_sMoveXCompare = _sMoveX.toString().replace('-','');
if(_sMoveX < 0){
if(_oDetails.delta[0].lastY < _vLimit) {
if(_sMoveYCompare < _vLimit) {
_oDetails.type += 'left';
}
}
}else if(_sMoveX > 0){
if(_sMoveYCompare < _vLimit) {
_oDetails.type += 'right'
}
}else{
_oDetails.type += '';
}
if(_sMoveY < 0){
if(_sMoveXCompare < _wLimit) {
_oDetails.type += 'up'
}
}else if(_sMoveY > 0){
if(_sMoveXCompare < _wLimit) {
_oDetails.type += 'down'
}
}else{
_oDetails.type += '';
}
// alert(_oDetails.type);
_$element.triggerHandler(_oDetails.type, _oDetails);
}
You could try both:
$('#wrap').bind('swipeleftup', function(){
doSomething();
});
$('#wrap').bind('swipeleftdown', function(){
doSomething();
});
And forget about 'swipeleft' as is quite difficult to trigger, as mentioned before.
I was just looking for the same thing and figured out that you can try all in the same function like so:
$("#wrap").on('swipeleft swipeleftup swipeleftdown', function(e){
doSomething();
});
as well as the equivalent for right:
$("#wrap").on('swiperight swiperightup swiperightdown', function(e){
doSomething();
});
You can list multiple events together with the on method.
I'm using Willian El-Turk's solution like this:
// jGestures http://stackoverflow.com/a/14403116/796538
$('.slides').bind('swipeone', function (event, obj) {
var direction=obj.description.split(":")[2]
if (direction=="left"){
//alert("left");
} else if (direction=="right"){
//alert("right");
}
});
Excellent solution, except because it executes as soon as there's movement left to right it's really sensitive even with more of a vertical swipe. it'd be great to have a minimum swipe distance on the x axis. Something like:
if (direction=="left" && distance>=50px){
Except i'm not sure how... Please feel free to edit this !
Edit - You can check distance (x axis) like this, it works for me :
$('.slides').bind('swipeone', function (event, obj) {
var xMovement = Math.abs(obj.delta[0].lastX);
var direction=obj.description.split(":")[2]
//I think 75 treshold is good enough. You can change this.
if(xMovement >= 75) {
//continue to event
//ONLY x axis swipe here. (left-right)
if (direction=="left"){
//alert("left");
} else if (direction=="right"){
//alert("right");
}
}
}
Related
I have been trying to make a simple "smoothscroll" function using location.href that triggers on the mousewheel. The main problem is that the EventListener(wheel..) gets a bunch of inputs over the span of ca. 0,9 seconds which keeps triggering the function. "I only want the function to run once".
In the code below I have tried to remove the eventlistener as soon as the function runs, which actually kinda work, the problem is that I want it to be added again, hence the timed function at the bottom. This also kinda work but I dont want to wait a full second to be able to scroll and if I set it to anything lover the function will run multiple times.
I've also tried doing it with conditions "the commented out true or false variables" which works perfectly aslong as you are only scrolling up and down but you cant scroll twice or down twice.
window.addEventListener('wheel', scrolltest, true);
function scrolltest(event) {
window.removeEventListener('wheel', scrolltest, true);
i = event.deltaY;
console.log(i);
if (webstate == 0) {
if (i < 0 && !upexecuted) {
// upexecuted = true;
location.href = "#forside";
// downexecuted = false;
} else if (i > 0 && !downexecuted) {
// downexecuted = true;
location.href = "#underside";
// upexecuted = false;
}
}
setTimeout(function(){ window.addEventListener('wheel', scrolltest, true); }, 1000);
}
I had hoped there was a way to stop the wheel from constantly produce inputs over atleast 0.9 seconds.
"note: don't know if it can help in some way but when the browser is not clicked (the active window) the wheel will registre only one value a nice 100 for down and -100 for up"
What you're trying to do is called "debouncing" or "throttling". (Those aren't exactly the same thing, but you can look up the difference in case it's going to matter to you.) Functions for this are built into libraries like lodash, but if using a library like that is too non-vanilla for what you have in mind, you can always define your own debounce function: https://www.geeksforgeeks.org/debouncing-in-javascript/
You might also want to look into requestanimationframe.
a different approach
okey after fiddeling with this for just about 2 days i got fustrated and started over. no matter what i did the browsers integrated "glide-scroll" was messing up the event trigger. anyway i decided to animate the scrolling myself and honestly it works better than i had imagined: here is my code if anyone want to do this:
var body = document.getElementsByTagName("BODY")[0];
var p1 = document.getElementById('page1');
var p2 = document.getElementById('page2');
var p3 = document.getElementById('page3');
var p4 = document.getElementById('page4');
var p5 = document.getElementById('page5');
var whatpage = 1;
var snap = 50;
var i = 0;
// this part is really just to read what "page" you are on if you update the site. if you add more pages you should remember to add it here too.
window.onload = setcurrentpage;
function setcurrentpage() {
if (window.pageYOffset == p1.offsetTop) {
whatpage = 1;
} else if (window.pageYOffset == p2.offsetTop) {
whatpage = 2;
} else if (window.pageYOffset == p3.offsetTop) {
whatpage = 3;
} else if (window.pageYOffset == p4.offsetTop) {
whatpage = 4;
} else if (window.pageYOffset == p5.offsetTop) {
whatpage = 5;
}
}
// this code is designet to automaticly work with any "id" you have aslong as you give it a variable called p"number" fx p10 as seen above.
function smoothscroll() {
var whatpagenext = whatpage+1;
var whatpageprev = whatpage-1;
var currentpage = window['p'+whatpage];
var nextpage = window['p'+whatpagenext];
var prevpage = window['p'+whatpageprev];
console.log(currentpage);
if (window.pageYOffset > currentpage.offsetTop + snap && window.pageYOffset < nextpage.offsetTop - snap){
body.style.overflowY = "hidden";
i++
window.scrollTo(0, window.pageYOffset+i);
if (window.pageYOffset <= nextpage.offsetTop + snap && window.pageYOffset >= nextpage.offsetTop - snap) {
i=0;
window.scrollTo(0, nextpage.offsetTop);
whatpage += 1;
body.style.overflowY = "initial";
}
} else if (window.pageYOffset < currentpage.offsetTop - snap && window.pageYOffset > prevpage.offsetTop + snap){
body.style.overflowY = "hidden";
i--
window.scrollTo(0, window.pageYOffset+i);
if (window.pageYOffset >= prevpage.offsetTop - snap && window.pageYOffset <= prevpage.offsetTop + snap) {
i=0;
window.scrollTo(0, prevpage.offsetTop);
whatpage -= 1;
body.style.overflowY = "initial";
}
}
}
to remove the scrollbar completely just add this to your stylesheet:
::-webkit-scrollbar {
width: 0px;
background: transparent;
}
The Highstock scrollbar only responds when you physically click and drag the bar or use the arrow keys. However ideally i'd be able to use the track pad while hovering over the scrollbar or graph itself. I've searched the Highstock/Highcharts API and found nothing that points toward a solution so i thought i'd query the internet hive mind
Looked into eventing and the followTouch attributes to no avail
Scroll by mouse wheel or trackpad is not implemented in Highcharts by default, but you can add it:
(function(H) {
//internal functions
function stopEvent(e) {
if (e) {
if (e.preventDefault) {
e.preventDefault();
}
if (e.stopPropagation) {
e.stopPropagation();
}
e.cancelBubble = true;
}
}
//the wrap
H.wrap(H.Chart.prototype, 'render', function(proceed) {
var chart = this,
mapNavigation = chart.options.mapNavigation;
proceed.call(chart);
// Add the mousewheel event
H.addEvent(chart.container, document.onmousewheel === undefined ? 'DOMMouseScroll' : 'mousewheel', function(event) {
var delta, extr, step, newMin, newMax, axis = chart.xAxis[0];
e = chart.pointer.normalize(event);
// Firefox uses e.detail, WebKit and IE uses wheelDelta
delta = e.detail || (e.wheelDelta / 120);
delta = delta < 0 ? 1 : -1;
if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
extr = axis.getExtremes();
step = (extr.max - extr.min) / 5 * delta;
axis.setExtremes(extr.min + step, extr.max + step, true, false);
}
stopEvent(event); // Issue #5011, returning false from non-jQuery event does not prevent default
return false;
});
});
}(Highcharts));
Highcharts.chart('container', ...);
Live demo: http://jsfiddle.net/BlackLabel/wjovscb9/
SELF ANSWER: see additionall logic to only add listener to subset of charts that we specifically want the trackpad behavior on. Additionally i added some logic to force the steps to be whole numbers and not go into the negative or super positive territory. Works awesome !
Highcharts.wrap(Highcharts.Chart.prototype, 'render', function(proceed) {
var chart = this;
proceed.call(chart);
if (chart.options['chart']['type'] === "xrange" && chart.options['yAxis'][0]['scrollbar']['enabled']) {
// Add the mousewheel event
Highcharts.addEvent(chart.container, document.onmousewheel === undefined ? 'DOMMouseScroll' : 'mousewheel', function (event) {
var delta, diff, extr, newMax, newMin, step, axis = chart.yAxis[0];
e = chart.pointer.normalize(event);
// Firefox uses e.detail, WebKit and IE uses wheelDelta
delta = e.detail || -(e.wheelDelta / 120);
delta = delta < 0 ? 1 : -1;
/* Up or Down */
if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
extr = axis.getExtremes();
diff = extr.max - extr.min;
step = diff / 5; /* move by fifths */
step = step > 1 ? Math.ceil(step) : 1; /* Min step is 1, Move by whole numbers */
step = step * delta; /* Up/Down */
// todo some logic for refuse to move ?
if (step > 0) {
/* UP */
if (extr.max + step > extr.dataMax) {
newMax = extr.dataMax;
newMin = extr.dataMax - diff; /* Enforce window not getting too small */
} else {
newMin = extr.min + step;
newMax = extr.max + step;
}
} else {
/* DOWN */
if (extr.min + step < 0) {
newMin = 0;
newMax = diff;
} else {
newMin = extr.min + step;
newMax = extr.max + step;
}
}
axis.setExtremes(newMin, newMax, true, false);
}
stopEvent(event); // Issue #5011, returning false from non-jQuery event does not prevent default
return false;
});
}
});
}());
I need to create jQuery mobile like Swipe gestures $("#slider ul li div").swipeleft(); using core jQuery without using any library or plugins not even jQuery mobile.
I know that jQuery mobile widgets are now going to be decoupled, so that we can take swipe alone from it. But I can't wait for that long.
I need some manual jQuery code similar to swipe gestures for swipe left and right functions.
I've seen this, but i couldn't understand how to get swipe gestures from it.
Can anyone help me out on that code?
This is the code for touch swipe using javascript. Finally I found it hard by searching all over the internet. Thanks to padilicious.Below is the HTML code for slider.
<div id="slider" ontouchstart="touchStart(event,'slider');" ontouchend="touchEnd(event);"
ontouchmove="touchMove(event);" ontouchcancel="touchCancel(event);">
<ul id="slideul"><li><img src="1.jpg"></li><li>....</ul>
</div>
Below is the javascript code for the touch swipe. It's bit long. But it works for me. You don't have to change anything. Only place you have to change is processingRoutine() function. I've called 2 slide function i.e previous & next using this code sliders.goToNext() & sliders.goToPrev(). You can modify as you want..
var triggerElementID = null; // this variable is used to identity the triggering element
var fingerCount = 0;
var startX = 0;
var startY = 0;
var curX = 0;
var curY = 0;
var deltaX = 0;
var deltaY = 0;
var horzDiff = 0;
var vertDiff = 0;
var minLength = 72; // the shortest distance the user may swipe
var swipeLength = 0;
var swipeAngle = null;
var swipeDirection = null;
// The 4 Touch Event Handlers
// NOTE: the touchStart handler should also receive the ID of the triggering element
// make sure its ID is passed in the event call placed in the element declaration, like:
// <div id="picture-frame" ontouchstart="touchStart(event,'picture-frame');" ontouchend="touchEnd(event);" ontouchmove="touchMove(event);" ontouchcancel="touchCancel(event);">
function touchStart(event,passedName) {
// disable the standard ability to select the touched object
event.preventDefault();
// get the total number of fingers touching the screen
fingerCount = event.touches.length;
// since we're looking for a swipe (single finger) and not a gesture (multiple fingers),
// check that only one finger was used
if ( fingerCount == 1 ) {
// get the coordinates of the touch
startX = event.touches[0].pageX;
startY = event.touches[0].pageY;
// store the triggering element ID
triggerElementID = passedName;
} else {
// more than one finger touched so cancel
touchCancel(event);
}
}
function touchMove(event) {
event.preventDefault();
if ( event.touches.length == 1 ) {
curX = event.touches[0].pageX;
curY = event.touches[0].pageY;
} else {
touchCancel(event);
}
}
function touchEnd(event) {
event.preventDefault();
// check to see if more than one finger was used and that there is an ending coordinate
if ( fingerCount == 1 && curX != 0 ) {
// use the Distance Formula to determine the length of the swipe
swipeLength = Math.round(Math.sqrt(Math.pow(curX - startX,2) + Math.pow(curY - startY,2)));
// if the user swiped more than the minimum length, perform the appropriate action
if ( swipeLength >= minLength ) {
caluculateAngle();
determineSwipeDirection();
processingRoutine();
touchCancel(event); // reset the variables
} else {
touchCancel(event);
}
} else {
touchCancel(event);
}
}
function touchCancel(event) {
// reset the variables back to default values
fingerCount = 0;
startX = 0;
startY = 0;
curX = 0;
curY = 0;
deltaX = 0;
deltaY = 0;
horzDiff = 0;
vertDiff = 0;
swipeLength = 0;
swipeAngle = null;
swipeDirection = null;
triggerElementID = null;
}
function caluculateAngle() {
var X = startX-curX;
var Y = curY-startY;
var Z = Math.round(Math.sqrt(Math.pow(X,2)+Math.pow(Y,2))); //the distance - rounded - in pixels
var r = Math.atan2(Y,X); //angle in radians (Cartesian system)
swipeAngle = Math.round(r*180/Math.PI); //angle in degrees
if ( swipeAngle < 0 ) { swipeAngle = 360 - Math.abs(swipeAngle); }
}
function determineSwipeDirection() {
if ( (swipeAngle <= 45) && (swipeAngle >= 0) ) {
swipeDirection = 'left';
} else if ( (swipeAngle <= 360) && (swipeAngle >= 315) ) {
swipeDirection = 'left';
} else if ( (swipeAngle >= 135) && (swipeAngle <= 225) ) {
swipeDirection = 'right';
} else if ( (swipeAngle > 45) && (swipeAngle < 135) ) {
swipeDirection = 'down';
} else {
swipeDirection = 'up';
}
}
function processingRoutine() {
var swipedElement = document.getElementById(triggerElementID);
if ( swipeDirection == 'left' ) {
sliders.goToNext();
} else if ( swipeDirection == 'right' ) {
sliders.goToPrev();
} else if ( swipeDirection == 'up' ) {
sliders.goToPrev();
} else if ( swipeDirection == 'down' ) {
sliders.goToNext();
}
}
I have a div, with a scroll bar, When it reaches the end, my page starts scrolling. Is there anyway I can stop this behavior ?
You can inactivate the scrolling of the whole page by doing something like this:
<div onmouseover="document.body.style.overflow='hidden';" onmouseout="document.body.style.overflow='auto';"></div>
Found the solution.
http://jsbin.com/itajok
This is what I needed.
And this is the code.
http://jsbin.com/itajok/edit#javascript,html
Uses a jQuery Plug-in.
Update due to deprecation notice
From jquery-mousewheel:
The old behavior of adding three arguments (delta, deltaX, and deltaY)
to the event handler is now deprecated and will be removed in later
releases.
Then, event.deltaY must now be used:
var toolbox = $('#toolbox'),
height = toolbox.height(),
scrollHeight = toolbox.get(0).scrollHeight;
toolbox.off("mousewheel").on("mousewheel", function (event) {
var blockScrolling = this.scrollTop === scrollHeight - height && event.deltaY < 0 || this.scrollTop === 0 && event.deltaY > 0;
return !blockScrolling;
});
Demo
The selected solution is a work of art. Thought it was worthy of a plugin....
$.fn.scrollGuard = function() {
return this
.on( 'wheel', function ( e ) {
var event = e.originalEvent;
var d = event.wheelDelta || -event.detail;
this.scrollTop += ( d < 0 ? 1 : -1 ) * 30;
e.preventDefault();
});
};
This has been an ongoing inconvenience for me and this solution is so clean compared to other hacks I've seen. Curious to know how more about how it works and how widely supported it would be, but cheers to Jeevan and whoever originally came up with this. BTW - stackoverflow answer editor needs this!
UPDATE
I believe this is better in that it doesn't try to manipulate the DOM at all, only prevents bubbling conditionally...
$.fn.scrollGuard2 = function() {
return this
.on( 'wheel', function ( e ) {
var $this = $(this);
if (e.originalEvent.deltaY < 0) {
/* scrolling up */
return ($this.scrollTop() > 0);
} else {
/* scrolling down */
return ($this.scrollTop() + $this.innerHeight() < $this[0].scrollHeight);
}
})
;
};
Works great in chrome and much simpler than other solutions... let me know how it fares elsewhere...
FIDDLE
You could use a mouseover event on the div to disable the body scrollbar and then a mouseout event to activate it again?
E.g. The HTML
<div onmouseover="disableBodyScroll();" onmouseout="enableBodyScroll();">
content
</div>
And then the javascript like so:
var body = document.getElementsByTagName('body')[0];
function disableBodyScroll() {
body.style.overflowY = 'hidden';
}
function enableBodyScroll() {
body.style.overflowY = 'auto';
}
As answered here, most modern browsers now support the overscroll-behavior: none; CSS property, that prevents scroll chaining. And that's it, just one line!
Here's a cross-browser way to do this on the Y axis, it works on desktop and mobile. Tested on OSX and iOS.
var scrollArea = this.querySelector(".scroll-area");
scrollArea.addEventListener("wheel", function() {
var scrollTop = this.scrollTop;
var maxScroll = this.scrollHeight - this.offsetHeight;
var deltaY = event.deltaY;
if ( (scrollTop >= maxScroll && deltaY > 0) || (scrollTop === 0 && deltaY < 0) ) {
event.preventDefault();
}
}, {passive:false});
scrollArea.addEventListener("touchstart", function(event) {
this.previousClientY = event.touches[0].clientY;
}, {passive:false});
scrollArea.addEventListener("touchmove", function(event) {
var scrollTop = this.scrollTop;
var maxScroll = this.scrollHeight - this.offsetHeight;
var currentClientY = event.touches[0].clientY;
var deltaY = this.previousClientY - currentClientY;
if ( (scrollTop >= maxScroll && deltaY > 0) || (scrollTop === 0 && deltaY < 0) ) {
event.preventDefault();
}
this.previousClientY = currentClientY;
}, {passive:false});
I wrote resolving for this issue
var div;
div = document.getElementsByClassName('selector')[0];
div.addEventListener('mousewheel', function(e) {
if (div.clientHeight + div.scrollTop + e.deltaY >= div.scrollHeight) {
e.preventDefault();
div.scrollTop = div.scrollHeight;
} else if (div.scrollTop + e.deltaY <= 0) {
e.preventDefault();
div.scrollTop = 0;
}
}, false);
If I understand your question correctly, then you want to prevent scrolling of the main content when the mouse is over a div (let's say a sidebar). For that, the sidebar may not be a child of the scrolling container of the main content (which was the browser window), to prevent the scroll event from bubbling up to its parent.
This possibly requires some markup changes in the following manner:
<div id="wrapper">
<div id="content">
</div>
</div>
<div id="sidebar">
</div>
See it's working in this sample fiddle and compare that with this sample fiddle which has a slightly different mouse leave behavior of the sidebar.
See also scroll only one particular div with browser's main scrollbar.
this disables the scrolling on the window if you enter the selector element.
works like charms.
elements = $(".selector");
elements.on('mouseenter', function() {
window.currentScrollTop = $(window).scrollTop();
window.currentScrollLeft = $(window).scrollTop();
$(window).on("scroll.prevent", function() {
$(window).scrollTop(window.currentScrollTop);
$(window).scrollLeft(window.currentScrollLeft);
});
});
elements.on('mouseleave', function() {
$(window).off("scroll.prevent");
});
You can inactivate the scrolling of the whole page by doing something like this but display the scrollbar!
<div onmouseover="document.body.style.overflow='hidden'; document.body.style.position='fixed';" onmouseout="document.body.style.overflow='auto'; document.body.style.position='relative';"></div>
$this.find('.scrollingDiv').on('mousewheel DOMMouseScroll', function (e) {
var delta = -e.originalEvent.wheelDelta || e.originalEvent.detail;
var scrollTop = this.scrollTop;
if((delta < 0 && scrollTop === 0) || (delta > 0 && this.scrollHeight - this.clientHeight - scrollTop === 0)) {
e.preventDefault();
}
});
Based on ceed's answer, here is a version that allows nesting scroll guarded elements. Only the element the mouse is over will scroll, and it scrolls quite smoothly. This version is also re-entrant. It can be used multiple times on the same element and will correctly remove and reinstall the handlers.
jQuery.fn.scrollGuard = function() {
this
.addClass('scroll-guarding')
.off('.scrollGuard').on('mouseenter.scrollGuard', function() {
var $g = $(this).parent().closest('.scroll-guarding');
$g = $g.length ? $g : $(window);
$g[0].myCst = $g.scrollTop();
$g[0].myCsl = $g.scrollLeft();
$g.off("scroll.prevent").on("scroll.prevent", function() {
$g.scrollTop($g[0].myCst);
$g.scrollLeft($g[0].myCsl);
});
})
.on('mouseleave.scrollGuard', function() {
var $g = $(this).parent().closest('.scroll-guarding');
$g = $g.length ? $g : $(window);
$g.off("scroll.prevent");
});
};
One easy way to use is to add a class, such as scroll-guard, to all the elements in the page that you allow scrolling on. Then use $('.scroll-guard').scrollGuard() to guard them.
If you apply an overflow: hidden style it should go away
edit: actually I read your question wrong, that will only hide the scroll bar but I don't think that's what you are looking for.
I couldn't get any of the answers to work in Chrome and Firefox, so I came up with this amalgamation:
$someElement.on('mousewheel DOMMouseScroll', scrollProtection);
function scrollProtection(event) {
var $this = $(this);
event = event.originalEvent;
var direction = (event.wheelDelta * -1) || (event.detail);
if (direction < 0) {
if ($this.scrollTop() <= 0) {
return false;
}
} else {
if ($this.scrollTop() + $this.innerHeight() >= $this[0].scrollHeight) {
return false;
}
}
}
I am trying to scroll by highlighting text and dragging down. Now, as you are probably aware, this is standard, default behavior for a standard overflow: auto element, however I am trying to do it with some fancy scrollbars courtesy of jQuery jScrollPane by Kelvin Luck.
I have created a fiddle here: DEMO
basically as you can see, highlighting and scrolling works in the top box (the default overflow: auto box) but in the second it doesn't and, to compound matters, once you reach the bottom it INVERTS your selection!
So, my question(s) is(are) this(these): is there a way to fix this? If so, how?
UPDATE
I have been working on this quite a bit and have found a slight solution using setTimeout()
however, it doesn't work as intended and if anybody is willing to help I have forked it to a new fiddle here: jsFiddle
the code itself is:
pane = $('#scrolldiv2');
pane.jScrollPane({animateEase: 'linear'});
api = pane.data('jsp');
$('#scrolldiv2').on('mousedown', function() {
$(this).off().on('mousemove', function(e) {
rel = $(this).relativePosition();
py = e.pageY - rel.y;
$t = $(this);
if (py >= $(this).height() - 20) {
scroll = setTimeout(scrollBy, 400, 20);
}
else if (py < 20) {
scroll = setTimeout(scrollBy, 400, -20);
}
else {
clearTimeout(scroll);
}
})
}).on('mouseup', function() {
$(this).off('mousemove');
clearTimeout(scroll);
})
var scrollBy = function(v) {
if (api.getContentPositionY < 20 & v == -20) {
api.scrollByY(v + api.getContentPositionY);
clearTimeout(scroll);
} else if (((api.getContentHeight - $t.height()) - api.getContentPositionY) < 20 & v == 20) {
api.scrollByY((api.getContentHeight - $t.height()) - api.getContentPositionY);
clearTimeout(scroll);
} else {
api.scrollByY(v, true)
scroll = setTimeout(scrollBy, 400, v)
}
}
$.fn.extend({
relativePosition: function() {
var t = this.get(0),
x, y;
if (t.offsetParent) {
x = t.offsetLeft;
y = t.offsetTop;
while ((t = t.offsetParent)) {
x += t.offsetLeft;
y += t.offsetTop;
}
}
return {
x: x,
y: y
}
},
})
You just have to scroll down/up depending on how close the mouse is to the end of the div; is not as good as the native solution but it gets the job done ( http://jsfiddle.net/PWYpu/25/ )
$('#scrolldiv2').jScrollPane();
var topScroll = $('#scrolldiv2').offset().top,
endScroll = topScroll + $('#scrolldiv2').height(),
f = ($('#scrolldiv2').height() / $('#scrolldiv2 .jspPane').height())*5 ,
selection = false,
_prevY;
$(document).mousemove(function(e){
var mY;
var delta = _prevY - e.pageY;
if((e.pageY < endScroll && (mY = ((e.pageY - endScroll + 80)/f)) > 0) ||
(e.pageY > topScroll && (mY = (e.pageY - (topScroll + 80))/f) < 0)){
if(selection && (delta > 10 || delta < -10) )
$('#scrolldiv2').data('jsp').scrollByY(mY, false) ;
}
})
$('#scrolldiv2').mousedown(function(e){_prevY = e.pageY; selection = true ;})
$(window).mouseup(function(){selection = false ;})
BTW, the reason it inverts the selection is because it reached the end of the document, just put some white space down there and problem solved.
I really hate to say it, I know it's an issue even I ran into with the update to this plugin, but in the old plugin (seen here) it works just fine with basic call. So I just reverted my copy.