How can I manipulate the UI for this jQuery div scroller? - scrolltop

I'm currently using the following code to scroll up/down text... I'd like to make the following modifications to the code, but am struggling on how to achieve it:
Check the location of the text and affect the opacity of the
up/down arrows. When the content of #scroll is at the top, the up (#scroll-up) arrow would be faded back. When the content of #scroll is at the bottom, the down (#scroll-down) arrow be faded back. Every where in between, both button's would be faded in.
Hide the scroll buttons if they are not needed
Here's the current code:
var ele = $('#scroll');
var speed = 25, scroll = 5, scrolling;
$('#scroll-up').mouseenter(function() {
scrolling = window.setInterval(function() {
ele.scrollTop( ele.scrollTop() - scroll );
}, speed);
});
$('#scroll-down').mouseenter(function() {
scrolling = window.setInterval(function() {
ele.scrollTop( ele.scrollTop() + scroll );
}, speed);
});
$('#scroll-up, #scroll-down').bind({
click: function(e) {
e.preventDefault();
},
mouseleave: function() {
if (scrolling) {
window.clearInterval(scrolling);
scrolling = false;
}
}
});

Looks like this might do the trick.
$(function() {
var ele = $('#scroll');
var speed = 25, scroll = 5, scrolling;
$("#scroll-up").css('opacity', 0.5);
$('#scroll-up').mouseenter(function() {
// Scroll the element up
scrolling = window.setInterval(function() {
ele.scrollTop( ele.scrollTop() - scroll );
$("#scroll-up").css("opacity", (ele.scrollTop() == 0) ? 0.5 : 1);
$("#scroll-down").css("opacity", (ele[0].scrollHeight - ele.scrollTop() == ele.outerHeight()) ? 0.5 : 1);
}, speed);
});
$('#scroll-down').mouseenter(function() {
// Scroll the element down
scrolling = window.setInterval(function() {
ele.scrollTop( ele.scrollTop() + scroll );
$("#scroll-up").css("opacity", (ele.scrollTop() == 0) ? 0.5 : 1);
$("#scroll-down").css("opacity", (ele[0].scrollHeight - ele.scrollTop() == ele.outerHeight()) ? 0.5 : 1);
}, speed);
});
$('#scroll-up, #scroll-down').bind({
click: function(e) {
// Prevent the default click action
e.preventDefault();
},
mouseleave: function() {
if (scrolling) {
window.clearInterval(scrolling);
scrolling = false;
}
}
});
var winHeight = $(window).height();
$("#scroll").css("height", winHeight - 220);
if (ele[0].scrollHeight == ele.outerHeight()){
$("#contentscrollnav").hide();
}
});
$(window).resize(function() {
var winHeight = $(window).height();
$("#scroll").css("height", winHeight - 220);
var ele = $('#scroll');
if (ele[0].scrollHeight <= ele.outerHeight()){
$("#contentscrollnav").hide();
} else if (ele[0].scrollHeight > ele.outerHeight()) {
$("#contentscrollnav").show();
}
});
You can see the code in action at:
http://jsfiddle.net/MzDst/11/

Related

I have synchronized charts with synch’d zooming. I would like to zoomout in steps (not just back to 1:1). Does anyone have a working example of this?

I am currently synchronizing my charts as below:
$('#container').bind('mousemove touchmove', function (e) {
var chart,
point,
points,
i;
for (i = 0; i < Highcharts.charts.length; i++) {
chart = Highcharts.charts[i];
e = chart.pointer.normalize(e); // Find coordinates within the chart
points = [];
Highcharts.each(chart.series, function(series){
point = series.searchPoint(e, true);
if (point) {
points.push(point);
point.onMouseOver(); // Show the hover marker
}
});
if (points.length > 0) {
chart.tooltip.refresh(points); // Show the tooltip
chart.xAxis[0].drawCrosshair(e, points[0]); // Show the crosshair
}
}
});
// ==================================================================================
// * Override the reset function, we don't need to hide the tooltips and crosshairs.
// * Synchronize zooming through the setExtremes event handler.
Highcharts.Pointer.prototype.reset = function () {};
// ====================================================================
function syncExtremes(e) {
var thisChart = this.chart;
if (e.trigger !== 'syncExtremes') { // Prevent feedback loop
Highcharts.each(Highcharts.charts, function (chart) {
if (chart !== thisChart) {
if (chart.xAxis[0].setExtremes) { // It is null while updating
chart.xAxis[0].setExtremes(e.min, e.max, undefined, false, { trigger: 'syncExtremes' });
}
}
});
}
}
You can calculate intermediate extremes and set them by setExtremes method, for example:
document.getElementById('zoomOut').addEventListener('click', function() {
var chart = Highcharts.charts[0],
yAxis = chart.yAxis[0],
xAxis = chart.xAxis[0],
yDistance = (yAxis.max - yAxis.min) / 2,
xDistance = (xAxis.max - xAxis.min) / 2;
yAxis.setExtremes(yAxis.min - yDistance, yAxis.max + yDistance);
xAxis.setExtremes(xAxis.min - xDistance, xAxis.max + xDistance);
});
Live demo: http://jsfiddle.net/BlackLabel/9vxgpn4z/
API Reference: https://api.highcharts.com/class-reference/Highcharts.Axis#setExtremes

iOS: Animated scroll position jumps on long touch gestures

Based on TweenMax, the ScrollTo Plugin and ScrollMagic (this is probably not where the problem came from):
I wanna have a hero section on top of a page, only tweening downwards if the user is scrolling from the very beginning. Everything works as expected on my laptop (MBP). Following problem: If I use a touch-device (iPhone SE, iOS 12.4.1) and use a short touch gesture, the window is tweening to the destination withouth any issue. But if I keep my finger on the screen, the page starts to flicker and jumps back to the top after the tween finished.
Codepen
Since it's not working with Codepen on my mobile device:
Reduced test
Is there any way to fix this behaviour? Already tried to toggle preventDefault with eventListeners on Callbacks as well as setting the position again onComplete.
var vh = window.innerHeight * 0.01;
document.documentElement.style.setProperty('--vh', `${vh}px`);
// assume the feature isn't supported
var supportsPassive = false;
// create options object with a getter to see if its passive property is accessed
var opts = Object.defineProperty && Object.defineProperty({}, 'passive', { get: function(){ supportsPassive = true }});
// create a throwaway element & event and (synchronously) test out our options
document.addEventListener('test', function() {}, opts);
// var allowScroll = true;
function preventDefault(e) {
e = e || window.event;
if (e.preventDefault) {
e.preventDefault();
}
// if (e.stopImmediatePropagation) {
// e.stopImmediatePropagation();
// }
if (e.stopPropagation) {
e.stopPropagation();
}
e.returnValue = false;
}
function getBodyScrollTop() {
var el = document.scrollingElement || document.documentElement;
return el.scrollTop;
// return window.pageYOffset
}
function setBodyScrollTop(scrollTop) {
var el = document.scrollingElement || document.documentElement;
el.scrollTop = scrollTop;
// window.pageYOffset = scrollTop;
}
function addMousewheelListener() {
if (e.addEventListener)
{
// IE9, Chrome, Safari, Opera
e.addEventListener("mousewheel", preventScroll, supportsPassive ? { passive: false } : false);
// Firefox
e.addEventListener("DOMMouseScroll", preventScroll, supportsPassive ? { passive: false } : false);
}
// IE 6/7/8
else
{
e.attachEvent("onmousewheel", preventScroll);
}
}
function removeMousewheelListener() {
if (e.removeEventListener)
{
// IE9, Chrome, Safari, Opera
e.removeEventListener("mousewheel", preventScroll, supportsPassive ? { passive: false } : false);
// Firefox
e.removeEventListener("DOMMouseScroll", preventScroll, supportsPassive ? { passive: false } : false);
}
// IE 6/7/8
else
{
e.detachEvent("onmousewheel", preventScroll);
}
}
function removeTouchListeners(e) {
window.removeEventListener("touchmove", preventScroll);
window.removeEventListener("touchstart", removeTouchListeners);
window.removeEventListener("touchend", removeTouchListeners);
}
function preventScroll(e) {
// if(TweenMax.isTweening(window) || !allowScroll) {
// e.preventDefault();
// e.stopImmediatePropagation();
preventDefault(e)
// }
}
function deactivateScroll() {
// allowScroll = false;
console.log('fired 1');
// window.addEventListener("touchstart", preventScroll, { passive: false });
window.addEventListener("touchmove", preventScroll, { passive: false });
addMousewheelListener();
}
function activateScroll() {
// allowScroll = true;
removeMousewheelListener();
// var scrollTop = y;
// var scrollTop = getBodyScrollTop;
// setBodyScrollTop(scrollTop);
window.addEventListener("touchstart", removeTouchListeners, { passive: false });
window.addEventListener("touchend", removeTouchListeners, { passive: false });
// var event1 = new Event('touchstart');
// var event2 = new Event('touchmove');
// var event3 = new Event('touchend');
// window.dispatchEvent(event1);
// window.dispatchEvent(event2);
// window.dispatchEvent(event3);
}
var ctrl = new ScrollMagic.Controller();
var sceneLeave = new ScrollMagic.Scene({
triggerElement: "#content",
triggerHook: "onEnter",
offset: 1
})
.addTo(ctrl)
.on("enter", function(event) {
TweenMax.to(window, 1, {
scrollTo: {
y: "#content",
autoKill: false
},
onStart: deactivateScroll,
onComplete: activateScroll
});
});

Titanium - Changing orientation between windows

I'm developing an application for ipad and iphone using Titanium. You can navigate between different views. 1st view (the main view where you can go to another views) will be only on portrait mode, the rest of views can be in any orientation.
For this, I use different windows:
var winPortrait = Ti.UI.createWindow({
orientationModes : [Ti.UI.PORTRAIT],
fullscreen : false,
navBarHidden : true,
backgroundColor : "#00669c",
});
var appWindow = Titanium.UI.createWindow({
width : Ti.UI.FILL,
height : Ti.UI.FILL,
fullscreen : false,
navBarHidden : true,
backgroundColor : "#00669c",
backgroundImage : "Default-Portrait.png",
orientationModes : [Ti.UI.PORTRAIT, Ti.UI.LANDSCAPE_LEFT, Ti.UI.LANDSCAPE_RIGHT]
});
This works ok. When I open each window, orientation changes works ok.
To explain my problem, I'm going to specify the steps I do to reproduce it.
I'm viewing a screen on landscape:
I click to go to main view (portrait only) with device in landscape.
Main view is shown in portrait mode.
I rotate the device to portrait.
I go to the view again with device in portrait:
If I change device orientation, I receive the orientation change event, app detects is landscape mode and draw elements like landscape, but window or view (I don't know) its drawing like portrait, so it doesn't adjust correctly:
This doesn't occur on ios 7, but when I've tried with ios 5.1, it happens (I doesn't have a device with ios 6.x to try it)
Do you know how can I solve it or is a SO problem?
Thank you very much.
UPDATE
This is a simplification of the code I use:
In app.js:
var appWindow = Titanium.UI.createWindow({
width : Ti.UI.FILL,
height : Ti.UI.FILL,
fullscreen : false,
navBarHidden : true,
backgroundColor : "#00669c",
backgroundImage : "Default-Portrait.png",
orientationModes : [Ti.UI.PORTRAIT, Ti.UI.LANDSCAPE_LEFT, Ti.UI.LANDSCAPE_RIGHT]
});
var winPortrait = Ti.UI.createWindow({
orientationModes : [Ti.UI.PORTRAIT],
fullscreen : false,
navBarHidden : true,
backgroundColor : "#00669c",
});
var openView = function(e) {
currentView = e.win;
if (winPortraitHomeOpened && e.win != 'Home') {
appWindow.backgroundImage = '';
appWindow.addEventListener('open', function() {
//alert("appwindowopen")
if (appWindow != null) {
appWindow.height = Ti.UI.FILL;
appWindow.width = Ti.UI.FILL;
}
});
appWindow.open();
}
// Dependiendo de la vista, abre una ventana u otra
if (e.win == 'Home') {
winPortrait.open();
winPortraitHomeOpened = true;
setTimeout(function() {
var Home = require('/views/Home2');
activeView = Home.Constructor(winPortrait);
addActiveViewCloseWin();
}, 10);
} else if (e.win == 'test') {
var Test = require('/views/test/test');
activeView = Test.Constructor(appWindow, true);
}
if (currentView != 'Home') {
addActiveViewCloseWin();
}
};
var addActiveViewCloseWin = function() {
var anim_invisible = Titanium.UI.createAnimation({
opacity : 0,
duration : 300
});
var anim_visible = Titanium.UI.createAnimation({
opacity : 1,
duration : 300
});
if (winPortraitHomeOpened && currentView == 'Home') {
winPortrait.add(activeView);
} else {
appWindow.add(activeView);
}
if (lastActiveView != null) {
Trace.info("lastActiveView != null");
lastActiveView.animate(anim_invisible);
setTimeout(function() {
activeView.animate(anim_visible);
lastActiveView.close();
lastActiveView = activeView;
}, 300);
} else {
activeView.animate(anim_visible);
lastActiveView = activeView;
}
activeView.updateOrientation();
setTimeout(function() {
if (currentView == 'Home') {
appWindow.close();
} else {
if (winPortraitHomeOpened) {
winPortrait.close();
winPortraitHomeOpened = false;
}
}
}, 500);
};
Ti.Gesture.addEventListener('orientationchange', function(e) {
// Comprobar que ha cambiado de orientación. Se envían varios eventos juntos
var _currentOrientacion = 0;
if (utils.isLandscape())
_currentOrientacion = 1;
if (_currentOrientacion == orientacion) {
return;
}
orientacion = _currentOrientacion;
// Se actualiza las dimensiones y la orientación de los elementos
if (!winPortraitHomeOpened && !winPortraitConfOpened) {
if (appWindow != null) {
appWindow.height = Ti.UI.FILL;
appWindow.width = Ti.UI.FILL;
}
}
if (activeView != null) {
activeView.updateOrientation();
}
});
The code of Test.js:
exports.Constructor = function(parent) {
var view = Ti.UI.createView({
height : utils.getScreenHeight(),
width : utils.getScreenWidth(),
backgroundColor : 'red'
});
var cabeceraView = Cabecera.Constructor(view);
view.add(cabeceraView);
cabeceraView.setTitle('Prueba');
var backButton = Ti.UI.createImageView({
image : utils.imagesFolder() + "common/returnHome.png",
//top : view.height / 4,
left : utils.todp(8),
height : utils.todp(25),
width : utils.todp(65)
});
view.add(backButton);
backButton.addEventListener('click', function() {
openView({
win : 'Home'
});
});
var updateFechaCabecera = function() {
fechaView.setFecha('XXXX-XX-XX');
};
view.updateFechaCabecera = updateFechaCabecera;
var fechaView = Fecha.Constructor(view);
view.add(fechaView);
updateFechaCabecera();
// Vista ocupa todo salvo cabecera y fecha
var mainView = Ti.UI.createView({
height : utils.getScreenHeight() - utils.getCabeceraHeight() - utils.getFechaHeight(),
width : '100%',
top : utils.getCabeceraHeight() + utils.getFechaHeight(),
backgroundColor : "transparent",
});
view.add(mainView);
// Create a Label.
var aLabel = Ti.UI.createLabel({
text : 'aLabel',
color : 'pink',
font : {
fontSize : 40
},
textAlign : 'center'
});
// Add to the parent view.
mainView.add(aLabel);
var updateOrientation = function() {
Trace.info("updateOrientation de interconexines height width " + utils.getScreenHeight() + ' ' + utils.getScreenWidth());
view.height = utils.getScreenHeight();
view.width = utils.getScreenWidth();
if (utils.isPortrait()) {
aLabel.text = "PORTRAIT";
} else {
aLabel.text = "LANDSCAPE";
}
};
view.updateOrientation = updateOrientation;
var cerrar = function() {
Trace.info('cerrar Template');
view.visible = false;
view.hide();
if (cabeceraView != null) {
cabeceraView.close();
view.remove(cabeceraView);
cabeceraView = null;
}
if (fechaView != null) {
fechaView.close();
view.remove(fechaView);
fechaView = null;
}
// Eliminamos los elementos de la vista
if (view != null) {
utils.removeChildrens(view);
parent.remove(view);
};
view = null;
};
view.close = cerrar;
return view;
};
Have you tried to remove orientationModes in var winPortrait?
Your code should look like this:
var winPortrait = Ti.UI.createWindow({
fullscreen : false,
navBarHidden : true,
backgroundColor : "#00669c",
});

Two linked jQuery Sliders adding up to 100%

I'm trying to link two jQuery UI sliders so they'll add up to 100%. I've found the perfect solution for three sliders here on SO, but for some reason I am unable to get the math to add up correctly when modifying this jsFiddle example to strip out the third slider: http://jsfiddle.net/gWbMp/3/
Can anyone help me out in forking this to simply include two sliders instead of three?
Here's the (close) javascript I've ended up with but it's not quite right:
var min = 0;
var max = 100;
$("input").change(function(){
console.log("a");
var index = $(this).attr('class').substring(0,1);
$("#slider_"+ index).slider('value', this.value);
refreshSliders( index - 0 );
});
$('.selector').slider({
animate : true
}, {
min : min
}, {
max : max
}, {
change : function(event, ui) {
totalvalue = $("#slider_1").slider("value") + $("#slider_2").slider("value");
$('.1percent').val($("#slider_1").slider("value"));
$('.2percent').val($("#slider_2").slider("value"));
}
}, {
slide : function(event, ui) {
$('.1percent').val($("#slider_1").slider("value"));
$('.2percent').val($("#slider_2").slider("value"));
}
});
$("#slider_1").slider('value', 10);
$("#slider_2").slider('value', 90);
$('.1percent').val($("#slider_1").slider("value"));
$('.2percent').val($("#slider_2").slider("value"));
function refreshSliders(slidermainin) {
var value1 = $("#slider_1").slider("option", "value");
var value2 = $("#slider_2").slider("option", "value");
var valuechange = (value1 + value2) - 100;
var valuemain = 0, valueother1 = 0;
switch(slidermainin) {
case 1:
slidermain = "#slider_1";
sliderother1 = "#slider_2";
valuemain = value1;
valueother1 = value2;
break;
case 2:
slidermain = "#slider_2";
sliderother1 = "#slider_1";
valuemain = value2;
valueother1 = value1;
break;
}
if (valueother1 === 0) {
if (valueother1 === 0) {
if (valuechange <= 0) {
$(sliderother1).slider('value', valueother1 - (valuechange / 2));
}
} else {
if (valuechange <= 0) {
$(sliderother1).slider('value', valueother1 - (valuechange / 2));
} else {
$(sliderother1).slider('value', valueother1 - valuechange);
}
}
} else {
$(sliderother1).slider('value', valueother1 - (valuechange / 2));
}
}
var bindSliders = function(selector, value) {
$(selector).bind("slidechange slide", function(event, ui) {
event.originalEvent && (event.originalEvent.type == 'mousemove' || event.originalEvent.type == 'mouseup' || event.originalEvent.type == 'keydown') && refreshSliders(value);
});
};
bindSliders("#slider_1", 1);
bindSliders("#slider_2", 2);
I think this can be done much shorter for two sliders
You can rewrite refreshSliders function to calculate second value on the basis of max value
And call it directly on slider "change" and "slide" (or even just second one)
function refreshSliders(thisSlider, ui){
var thisNum = $(thisSlider).attr("id").replace("slider_", "");
var otherNum = (thisNum==1)?2:1;
$('.'+thisNum+'percent').val(ui.value);
if ($("#slider_"+otherNum).slider("value")!=max-ui.value){
$("#slider_"+otherNum).slider("value", max-ui.value);
$('.'+otherNum+'percent').val(max-ui.value);
}
}
have a look at this jsfiddle, i forked it from original one and adjusted a bit: http://jsfiddle.net/paulitto/fBxCm/1/

Scroll div when element is dragging without moving mouse

I developped a code including a table with all its cells as droppable. The table container is div with a fix height and a scrollbar.
I would like drag an element (yellow square in my example) into the last table cell at the bottom of my table. Everything works fine, but to activate the scrollbar of my div container when I am dragging the element, I must move the mouse all the time.
Is there a possibility to scroll down automatically when my element is dragging near the bottom of my div container without moving mouse?
Here is my example : http://jsbin.com/upunek/19/edit
Thanks in advance
I figure it out this morning.
I created setInterval function when the drag event position is located at 70px of the border
Here is the fiddle I made : http://jsfiddle.net/pPn3v/22/
var yellow = $('#yellow');
var offset = yellow.offset();
var offsetWidth = offset.left + yellow.width();
var offsetHeight = offset.top + yellow.height();
var red = $('#red');
var intRightHandler = null;
var intLeftHandler = null;
var intTopHandler= null;
var intBottomHandler= null;
var distance = 70;
var timer = 100;
var step = 10;
function clearInetervals()
{
clearInterval(intRightHandler);
clearInterval(intLeftHandler);
clearInterval(intTopHandler);
clearInterval(intBottomHandler);
}
red.draggable({
start : function(){},
stop: function(){clearInetervals(); },
drag : function(e){
var isMoving = false;
//Left
if((e.pageX - offset.left) <= distance)
{
isMoving = true;
clearInetervals();
intLeftHandler= setInterval(function(){
yellow.scrollLeft(yellow.scrollLeft() - step)
},timer);
console.log('left')
}
//Right
if(e.pageX >= (offsetWidth - distance))
{
isMoving = true;
clearInetervals();
intRightHandler = setInterval(function(){
yellow.scrollLeft(yellow.scrollLeft() + step)
},timer);
console.log('right')
}
//Top
if((e.pageY - offset.top) <= distance)
{
isMoving = true;
clearInetervals();
intTopHandler= setInterval(function(){
yellow.scrollTop(yellow.scrollTop() - step)
},timer);
console.log('top')
}
//Bottom
if(e.pageY >= (offsetHeight - distance))
{
isMoving = true;
clearInetervals();
intBottomHandler= setInterval(function(){
yellow.scrollTop(yellow.scrollTop() + step)
},timer);
console.log('bottom')
}
//No events
if(!isMoving)
clearInetervals();
}
});
​

Resources