jScrollPane scrolling on element drag - javascript

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.

Related

How to remove jank when setting an element to a fixed position using JavaScript

I have a webpage that when scrolled down, the text freezes when it reaches the last paragraph of text but the images keep on scrolling. I've got the implementation working but there is a lot of jank when scrolling with a mouse wheel, not so much if I click and drag the scroll bar.
Are there any optimizations I can make to this code to make work as intended or is there a different way to accomplish the same task?
window.addEventListener('scroll', function (e) {
window.requestAnimationFrame(keepTextStationary);
//keepTextStationary(); // Less janky, but still horrible
});
function keepTextStationary() {
var textRect = writtenContent.getBoundingClientRect();
var imageRec = images.getBoundingClientRect();
if (textRect.bottom < window.innerHeight && document.documentElement.scrollTop > 0) {
writtenContent.style.position = 'relative';
writtenContent.style.bottom = (225 - document.documentElement.scrollTop) + 'px';
if (imagesTop === undefined) {
imagesTop = imageRec.y;
}
} else {
writtenContent.style.bottom = (225 - document.documentElement.scrollTop) + 'px';
}
if (imageRec.y >= imagesTop) {
writtenContent.style.position = '';
}
}
Here is the site so you can see the problem.
https://bowerbankninow.azurewebsites.net/exhibitions/oscar-perry-the-pheasant
You are causing layout trashing every time you call getBoundingClientRect. Try debouncing your scroll events:
var lastScrollY = 0;
var ticking = false;
function keepTextStationary() {
var textRect = writtenContent.getBoundingClientRect();
var imageRec = images.getBoundingClientRect();
if (textRect.bottom < window.innerHeight && lastScrollY > 0) {
writtenContent.style.position = 'relative';
writtenContent.style.bottom = (225 - lastScrollY) + 'px';
if (imagesTop === undefined) {
imagesTop = imageRec.y;
}
} else {
writtenContent.style.bottom = (225 - lastScrollY) + 'px';
}
if (imageRec.y >= imagesTop) {
writtenContent.style.position = '';
}
ticking = false;
}
function onScroll() {
lastScrollY = document.documentElement.scrollTop;
requestTick();
}
function requestTick() {
if (!ticking) {
requestAnimationFrame(keepTextStationary);
ticking = true;
}
}
window.addEventListener('scroll', onScroll );
See this article for in-depth explanation: https://www.html5rocks.com/en/tutorials/speed/animations/
You dont.
Relocations / styling in javascript take place after the CSS has been loaded. Bad practise. What you can do, is make it animated to make it look less horrible.
Why is pure CSS not an option ?

tips.hide() function. Potential bug in infoVis/JIT?

I have a force directed graph with "Tips" enabled. I don't want to show tips for those nodes which are hidden i.e. for whom "alpha" is zero. In onShow call back function I am trying to use tips.hide() but it is not hiding the tip. Here is my code.
Tips: {
enable: true,
type: 'Native',
onShow: function(tip, node) {
if( node.getData('alpha') == 0 ) this.fd.tips.hide(false);
else tip.innerHTML = node.name;
}
}
When I drilled down into infovis library jit.js I found something which looks like a bug. Below is the hide function which basically sets style.display to 'none'.
hide: function(triggerCallback) {
this.tip.style.display = 'none';
triggerCallback && this.config.onHide();
}
Now look at the code below.
onMouseMove: function(e, win, opt) {
if(this.dom && this.isLabel(e, win)) {
this.setTooltipPosition($.event.getPos(e, win));
}
if(!this.dom) {
var node = opt.getNode();
if(!node) {
this.hide(true);
return;
}
if(this.config.force || !this.node || this.node.id != node.id) {
this.node = node;
this.config.onShow(this.tip, node, opt.getContains());
}
this.setTooltipPosition($.event.getPos(e, win));
}
},
setTooltipPosition: function(pos) {
var tip = this.tip,
style = tip.style,
cont = this.config;
style.display = ''; //This looks like a problem
//get window dimensions
var win = {
'height': document.body.clientHeight,
'width': document.body.clientWidth
};
//get tooltip dimensions
var obj = {
'width': tip.offsetWidth,
'height': tip.offsetHeight
};
//set tooltip position
var x = cont.offsetX, y = cont.offsetY;
style.top = ((pos.y + y + obj.height > win.height)?
(pos.y - obj.height - y) : pos.y + y) + 'px';
style.left = ((pos.x + obj.width + x > win.width)?
(pos.x - obj.width - x) : pos.x + x) + 'px';
}
As you can see the onShow function is called from the onMouseMove function. And after onShow, setTooltipPosition function is called which sets the style.display back to ' ' (see my comment in code). Because of this the tip is not being hidden even after calling hide() from onShow function.
When I commented out that line in setTooltipPosition, it worked i.e. tool tips were hidden for nodes which were hidden.
Is this a bug in infovis or am I doing something wrong. I would like to know how is hide function supposed to be used if its not a bug.
Also, does anyone know of any other better way to hide a tool tip?
I had a similar problem. The solution was to use the .css('visibility', 'visible') instead of .hide() - because the element was hidden to start with using css styling.

Scrolling child div scrolls the window, how do I stop that?

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;
}
}
}

Only swipeone is working with jGestures

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");
}
}
}

Changing element style depending on the style of scrollable content

Need help to newbie. I have a list elements inside scrollable div(tiny scrollbar) with different background colors: red and blue. Also i have a two square divs with red and blue background colors.
ToDo: add class 'border' to the blue square div, when list is scrolled to the first blue colored element.
Here's example: http://jsfiddle.net/uy4hK/19/
I guess there should be something like a position trigger for different colored list elements. Need help!
You may customize the plugin to support scrolling events. Modify the whell and drag functions as below:
function wheel(oEvent) {
if (!(oContent.ratio >= 1)) {
oEvent = $.event.fix(oEvent || window.event);
var iDelta = oEvent.wheelDelta ? oEvent.wheelDelta / 120 : -oEvent.detail / 3;
iScroll -= iDelta * options.wheel;
iScroll = Math.min((oContent[options.axis] - oViewport[options.axis]), Math.max(0, iScroll));
oThumb.obj.css(sDirection, iScroll / oScrollbar.ratio);
oContent.obj.css(sDirection, -iScroll);
oEvent.preventDefault();
// New code
if (options.onScroll && typeof (options.onScroll) == "function") {
options.onScroll.call(this);
}
};
};
function drag(oEvent) {
if (!(oContent.ratio >= 1)) {
iPosition.now = Math.min((oTrack[options.axis] - oThumb[options.axis]), Math.max(0, (iPosition.start + ((sAxis ? oEvent.pageX : oEvent.pageY) - iMouse.start))));
iScroll = iPosition.now * oScrollbar.ratio;
oContent.obj.css(sDirection, -iScroll);
oThumb.obj.css(sDirection, iPosition.now);
// New code
if (options.onScroll && typeof (options.onScroll) == "function") {
options.onScroll.call(this);
}
}
return false;
};
Then you can pass a custom function that will be executed on scrolling:
$(function () {
var fisrtBlueOffset = $(".overview li.blue:first").offset().top;
var viewportHeight = $(".viewport").height();
$('#scrollbar1').tinyscrollbar({
"onScroll": function () {
var viewportTop = parseInt($(".overview").css("top"));
if (fisrtBlueOffset + viewportTop < viewportHeight) {
$(".blue-block").css("border", "1px solid #000");
}
else {
$(".blue-block").css("border", "");
}
}
});
});

Categories

Resources