Javascript scrolling on XY axis - javascript

I have a jsfiddle here using jquery 1.8.3 and scrollTo to scoll to an element #en on an XY axis
https://jsfiddle.net/80kxdsxe/
var $scrollTo = $.scrollTo = function(target, duration, settings) {
return $(window).scrollTo(target, duration, settings);
};
$scrollTo.defaults = {
axis:'xy',
duration: 0,
limit:true
};
The jsfiddle that i need to work is using pure js but it only scrolls to the element #en on either the X or Y axis and i need it to scroll using XY
https://jsfiddle.net/43s8wpd7/
/* Note: In order to be subjected to chaining and animation options, scroll's tweening is routed through Velocity as if it were a standard CSS property animation. */
if (action === "scroll") {
/* The scroll action uniquely takes an optional "offset" option -- specified in pixels -- that offsets the targeted scroll position. */
var scrollDirection = (/^x$/i.test(opts.axis) ? "Left" : "Top"),
scrollOffset = parseFloat(opts.offset) || 0,
scrollPositionCurrent,
scrollPositionCurrentAlternate,
scrollPositionEnd;
if (opts.container) {
if (Type.isWrapped(opts.container) || Type.isNode(opts.container)) {
opts.container = opts.container[0] || opts.container;
scrollPositionCurrent = opts.container["scroll" + scrollDirection];
scrollPositionEnd = (scrollPositionCurrent + $(element).position()[scrollDirection.toLowerCase()]) + scrollOffset; /* GET */
} else {
opts.container = null;
}
} else {
scrollPositionCurrent = Velocity.State.scrollAnchor[Velocity.State["scrollProperty" + scrollDirection]];
scrollPositionCurrentAlternate = Velocity.State.scrollAnchor[Velocity.State["scrollProperty" + (scrollDirection === "Left" ? "Top" : "Left")]]; /* GET */
scrollPositionEnd = $(element).offset()[scrollDirection.toLowerCase()] + scrollOffset; /* GET */
}
/* Since there's only one format that scroll's associated tweensContainer can take, we create it manually. */
tweensContainer = {
scroll: {
rootPropertyValue: false,
startValue: scrollPositionCurrent,
currentValue: scrollPositionCurrent,
endValue: scrollPositionEnd,
unitType: "",
easing: opts.easing,
scrollData: {
container: opts.container,
direction: scrollDirection,
alternateValue: scrollPositionCurrentAlternate
}
},
element: element
};
if (Velocity.debug) console.log("tweensContainer (scroll): ", tweensContainer.scroll, element);
Can anyone help me fix the second NON-jquery fiddle to allow the scroll to be on the XY axis?
Thanks.

Related

Apex Charts: how do I change tooltip position to be always on top?

By default Apex Charts tooltip positioning is calculated automatically: https://codepen.io/apexcharts/pen/xYqyYm. According to their docs, you can only change it to fixed and put in one of the corners:
Apex.tooltip = {
fixed: {
enabled: true
}
};
How do I change it to be always centered on top of the marker?
In case anyone wants to change the position of tooltips without creating a custom one (cause it poses new difficulties). I am 100% sure there is a better way to do this, but here is my solution:
Apex.chart = {
events: {
mouseMove: function(event, chartContext, config) {
var tooltip = chartContext.el.querySelector('.apexcharts-tooltip');
var pointsArray = config.globals.pointsArray;
var seriesIndex = config.seriesIndex;
var dataPointIndex = config.dataPointIndex === -1 ? 0 : config.dataPointIndex;
if (seriesIndex !== -1) {
var position = pointsArray[seriesIndex][dataPointIndex];
tooltip.style.top = position[1] + 'px';
tooltip.style.left = position[0] + 'px';
}
}
}
};
codepen - https://codepen.io/Pratik__007/pen/oNgJajw
Source - Form GitHub post.

ui-grid, error when scrolling

I am getting the following error when I scroll in ui-grid:
Uncaught TypeError: Cannot read property 'percentage' of undefined
Interestingly I get the same error on the ui-grid tutorial site so it is possible it is just simply a bug.
Here is a plunker that shows the issue.
Here are the grid options I am using:
mc.gridOptions = {
data: mc.people,
enableSorting: true,
onRegisterApi: function( gridApi ) {
mc.gridApi = gridApi;
},
columnDefs: [
{field: 'name'},
{field: 'age'},
{field: 'state', enableSorting: false}
]
};
Any ideas as to what I am doing wrong here? As far as I can tell there is nothing wrong with this.
I would mention this in the comment box, but I need the space and the formatting to explain that you probably need to bring this up to their attention:
First you are using an unstable version, your best bet is to use a stable version that is being used and tested.
The unstable version is throwing a bug in the code below.. please review all my comments in asterisk (******) :
// Scroll the render container viewport when the mousewheel is used
$elm.bind('wheel mousewheel DomMouseScroll MozMousePixelScroll', function(evt) {
// use wheelDeltaY
var newEvent = GridUtil.normalizeWheelEvent(evt);
var args = { target: $elm };
*****THIS STATEMENT IS TRUE BECAUSE YOU SCROLLED VERTICALLY, ARGS.Y IS SET*****
if (newEvent.deltaY !== 0) {
var scrollYAmount = newEvent.deltaY * -120;
// Get the scroll percentage
var scrollYPercentage = (containerCtrl.viewport[0].scrollTop + scrollYAmount) / rowContainer.getVerticalScrollLength();
// Keep scrollPercentage within the range 0-1.
if (scrollYPercentage < 0) { scrollYPercentage = 0; }
else if (scrollYPercentage > 1) { scrollYPercentage = 1; }
***THIS IS SET***
args.y = { percentage: scrollYPercentage, pixels: scrollYAmount };
}
*****THIS STATEMENT IS FALSE BECAUSE YOU NEVER SCROLLED HORIZONTALLY, ARGS.X IS NOT SET*****
if (newEvent.deltaX !== 0) {
var scrollXAmount = newEvent.deltaX * -120;
// Get the scroll percentage
var scrollLeft = GridUtil.normalizeScrollLeft(containerCtrl.viewport);
var scrollXPercentage = (scrollLeft + scrollXAmount) / (colContainer.getCanvasWidth() - colContainer.getViewportWidth());
// Keep scrollPercentage within the range 0-1.
if (scrollXPercentage < 0) { scrollXPercentage = 0; }
else if (scrollXPercentage > 1) { scrollXPercentage = 1; }
***THIS DOESNT GET SET SINCE IT WILL NOT REACH THIS POINT***
args.x = { percentage: scrollXPercentage, pixels: scrollXAmount };
}
*****THROWS AN ERROR BECAUSE ARGS.X IS NULL & DOESNT EXIST*****
// Let the parent container scroll if the grid is already at the top/bottom
if ((args.y.percentage !== 0 && args.y.percentage !== 1) || (args.x.percentage !== 0 && args.x.percentage !== 1)) {
evt.preventDefault();
}
uiGridCtrl.fireScrollingEvent(args);
});

Ext.js DataGrid tab navigation not working correctly in RTL mode

I am using DataGrid component of Ext.js 4.2.2 in RTL mode
In official example of that component I am using CellEditing plugin.
When I press the tab key for tab navigation in cell editor.
But when the cell editor gets out of grid region the scroll bar doesn't adapt itself to new position.
You can see the problem in following image.
I am using Chrome as browser.
Any idea?
After debugging Ext.js code for about 2 days I found the problem.
The problem was in one of Dom.Element_Scroll's methods.
With overriding that method the problem solved.
Originally the problem cause was, not normalizing scrollLeft value for setting to container element in RTL mode.
you should change methods like this.
me.scrollChildFly.attach(container).ScrollTo('left', newPos, animate);
To
me.scrollChildFly.attach(container).rtlScrollTo('left', newPos, animate);
and the same for scroll top.
The full code to use is as follows.
NOTE: I am using Ext.JS 4.2.2
*/
Ext.define('Ext.rtl.dom.Element_scroll', {
override: 'Ext.dom.Element',
/**
* Scrolls this element into view within the passed container.
* #param {String/HTMLElement/Ext.Element} [container=document.body] The container element
* to scroll. Should be a string (id), dom node, or Ext.Element.
* #param {Boolean} [hscroll=true] False to disable horizontal scroll.
* #param {Boolean/Object} [animate] true for the default animation or a standard Element
* #param {Boolean} [highlight=false] true to {#link #highlight} the element when it is in view.
* animation config object
* #return {Ext.dom.Element} this
*/
scrollIntoView: function (container, hscroll, animate, highlight) {
var me = this,
dom = me.dom,
offsets = me.getOffsetsTo(container = Ext.getDom(container) || Ext.getBody().dom),
// el's box
left = offsets[0] + container.scrollLeft,
top = offsets[1] + container.scrollTop,
bottom = top + dom.offsetHeight,
right = left + dom.offsetWidth,
// ct's box
ctClientHeight = container.clientHeight,
ctScrollTop = parseInt(container.scrollTop, 10),
ctScrollLeft = parseInt(container.scrollLeft, 10),
ctBottom = ctScrollTop + ctClientHeight,
ctRight = ctScrollLeft + container.clientWidth,
newPos;
// Highlight upon end of scroll
if (highlight) {
if (animate) {
animate = Ext.apply({
listeners: {
afteranimate: function () {
me.scrollChildFly.attach(dom).highlight();
}
}
}, animate);
} else {
me.scrollChildFly.attach(dom).highlight();
}
}
if (dom.offsetHeight > ctClientHeight || top < ctScrollTop) {
newPos = top;
} else if (bottom > ctBottom) {
newPos = bottom - ctClientHeight;
}
if (newPos != null) {
//previous : me.scrollChildFly.attach(container).ScrollTo('top', newPos, animate);
me.scrollChildFly.attach(container).rtlScrollTo('top', newPos, animate);
}
if (hscroll !== false) {
newPos = null;
if (dom.offsetWidth > container.clientWidth || left < ctScrollLeft) {
newPos = left;
} else if (right > ctRight) {
newPos = right - container.clientWidth;
}
if (newPos != null) {
// previous : me.scrollChildFly.attach(container).rtlScrollTo('left', newPos, animate);
me.scrollChildFly.attach(container).rtlScrollTo('left', newPos, animate);
}
}
return me;
},
});

Jquery splitter plugin getting error too much recursion

I am using this jquery splitter plugin located here: http://methvin.com/splitter/
It is working fine with the version of jquery I am using until I enable the resizeToWidth property then it is giving me the error: too much recursion.
Here is a link to a demo I created on jsfiddle: http://jsfiddle.net/S97rv/4/
Iv looked at the plugin code but im not a javascript expert and don't want to mess with it to much.
Can anybody see a solution to this error?
Here is the plugin code but probably better just looking at the jsfiddle link:
;(function($){
$.fn.splitter = function(args){
args = args || {};
return this.each(function() {
var zombie; // left-behind splitbar for outline resizes
function startSplitMouse(evt) {
if ( opts.outline )
zombie = zombie || bar.clone(false).insertAfter(A);
panes.css("-webkit-user-select", "none"); // Safari selects A/B text on a move
bar.addClass(opts.activeClass);
A._posSplit = A[0][opts.pxSplit] - evt[opts.eventPos];
$(document)
.bind("mousemove", doSplitMouse)
.bind("mouseup", endSplitMouse);
}
function doSplitMouse(evt) {
var newPos = A._posSplit+evt[opts.eventPos];
if ( opts.outline ) {
newPos = Math.max(0, Math.min(newPos, splitter._DA - bar._DA));
bar.css(opts.origin, newPos);
} else
resplit(newPos);
}
function endSplitMouse(evt) {
bar.removeClass(opts.activeClass);
var newPos = A._posSplit+evt[opts.eventPos];
if ( opts.outline ) {
zombie.remove(); zombie = null;
resplit(newPos);
}
panes.css("-webkit-user-select", "text"); // let Safari select text again
$(document)
.unbind("mousemove", doSplitMouse)
.unbind("mouseup", endSplitMouse);
}
function resplit(newPos) {
// Constrain new splitbar position to fit pane size limits
newPos = Math.max(A._min, splitter._DA - B._max,
Math.min(newPos, A._max, splitter._DA - bar._DA - B._min));
// Resize/position the two panes
bar._DA = bar[0][opts.pxSplit]; // bar size may change during dock
bar.css(opts.origin, newPos).css(opts.fixed, splitter._DF);
A.css(opts.origin, 0).css(opts.split, newPos).css(opts.fixed, splitter._DF);
B.css(opts.origin, newPos+bar._DA)
.css(opts.split, splitter._DA-bar._DA-newPos).css(opts.fixed, splitter._DF);
// IE fires resize for us; all others pay cash
if ( !$.browser.msie )
panes.trigger("resize");
}
function dimSum(jq, dims) {
// Opera returns -1 for missing min/max width, turn into 0
var sum = 0;
for ( var i=1; i < arguments.length; i++ )
sum += Math.max(parseInt(jq.css(arguments[i])) || 0, 0);
return sum;
}
// Determine settings based on incoming opts, element classes, and defaults
var vh = (args.splitHorizontal? 'h' : args.splitVertical? 'v' : args.type) || 'v';
var opts = $.extend({
activeClass: 'active', // class name for active splitter
pxPerKey: 8, // splitter px moved per keypress
tabIndex: 0, // tab order indicator
accessKey: '' // accessKey for splitbar
},{
v: { // Vertical splitters:
keyLeft: 39, keyRight: 37, cursor: "e-resize",
splitbarClass: "vsplitbar", outlineClass: "voutline",
type: 'v', eventPos: "pageX", origin: "left",
split: "width", pxSplit: "offsetWidth", side1: "Left", side2: "Right",
fixed: "height", pxFixed: "offsetHeight", side3: "Top", side4: "Bottom"
},
h: { // Horizontal splitters:
keyTop: 40, keyBottom: 38, cursor: "n-resize",
splitbarClass: "hsplitbar", outlineClass: "houtline",
type: 'h', eventPos: "pageY", origin: "top",
split: "height", pxSplit: "offsetHeight", side1: "Top", side2: "Bottom",
fixed: "width", pxFixed: "offsetWidth", side3: "Left", side4: "Right"
}
}[vh], args);
// Create jQuery object closures for splitter and both panes
var splitter = $(this).css({position: "relative"});
var panes = $(">*", splitter[0]).css({
position: "absolute", // positioned inside splitter container
"z-index": "1", // splitbar is positioned above
"-moz-outline-style": "none" // don't show dotted outline
});
var A = $(panes[0]); // left or top
var B = $(panes[1]); // right or bottom
// Focuser element, provides keyboard support; title is shown by Opera accessKeys
var focuser = $('')
.attr({accessKey: opts.accessKey, tabIndex: opts.tabIndex, title: opts.splitbarClass})
.bind($.browser.opera?"click":"focus", function(){ this.focus(); bar.addClass(opts.activeClass) })
.bind("keydown", function(e){
var key = e.which || e.keyCode;
var dir = key==opts["key"+opts.side1]? 1 : key==opts["key"+opts.side2]? -1 : 0;
if ( dir )
resplit(A[0][opts.pxSplit]+dir*opts.pxPerKey, false);
})
.bind("blur", function(){ bar.removeClass(opts.activeClass) });
// Splitbar element, can be already in the doc or we create one
var bar = $(panes[2] || '<div></div>')
.insertAfter(A).css("z-index", "100").append(focuser)
.attr({"class": opts.splitbarClass, unselectable: "on"})
.css({position: "absolute", "user-select": "none", "-webkit-user-select": "none",
"-khtml-user-select": "none", "-moz-user-select": "none"})
.bind("mousedown", startSplitMouse);
// Use our cursor unless the style specifies a non-default cursor
if ( /^(auto|default|)$/.test(bar.css("cursor")) )
bar.css("cursor", opts.cursor);
// Cache several dimensions for speed, rather than re-querying constantly
bar._DA = bar[0][opts.pxSplit];
splitter._PBF = $.boxModel? dimSum(splitter, "border"+opts.side3+"Width", "border"+opts.side4+"Width") : 0;
splitter._PBA = $.boxModel? dimSum(splitter, "border"+opts.side1+"Width", "border"+opts.side2+"Width") : 0;
A._pane = opts.side1;
B._pane = opts.side2;
$.each([A,B], function(){
this._min = opts["min"+this._pane] || dimSum(this, "min-"+opts.split);
this._max = opts["max"+this._pane] || dimSum(this, "max-"+opts.split) || 9999;
this._init = opts["size"+this._pane]===true ?
parseInt($.curCSS(this[0],opts.split)) : opts["size"+this._pane];
});
// Determine initial position, get from cookie if specified
var initPos = A._init;
if ( !isNaN(B._init) ) // recalc initial B size as an offset from the top or left side
initPos = splitter[0][opts.pxSplit] - splitter._PBA - B._init - bar._DA;
if ( opts.cookie ) {
if ( !$.cookie )
alert('jQuery.splitter(): jQuery cookie plugin required');
var ckpos = parseInt($.cookie(opts.cookie));
if ( !isNaN(ckpos) )
initPos = ckpos;
$(window).bind("unload", function(){
var state = String(bar.css(opts.origin)); // current location of splitbar
$.cookie(opts.cookie, state, {expires: opts.cookieExpires || 365,
path: opts.cookiePath || document.location.pathname});
});
}
if ( isNaN(initPos) ) // King Solomon's algorithm
initPos = Math.round((splitter[0][opts.pxSplit] - splitter._PBA - bar._DA)/2);
// Resize event propagation and splitter sizing
if ( opts.anchorToWindow ) {
// Account for margin or border on the splitter container and enforce min height
splitter._hadjust = dimSum(splitter, "borderTopWidth", "borderBottomWidth", "marginBottom");
splitter._hmin = Math.max(dimSum(splitter, "minHeight"), 20);
$(window).bind("resize", function(){
var top = splitter.offset().top;
var wh = $(window).height();
splitter.css("height", Math.max(wh-top-splitter._hadjust, splitter._hmin)+"px");
if ( !$.browser.msie ) splitter.trigger("resize");
}).trigger("resize");
}
else if ( opts.resizeToWidth && !$.browser.msie )
$(window).bind("resize", function(){
splitter.trigger("resize");
});
// Resize event handler; triggered immediately to set initial position
splitter.bind("resize", function(e, size){
// Custom events bubble in jQuery 1.3; don't get into a Yo Dawg
if ( e.target != this ) return;
// Determine new width/height of splitter container
splitter._DF = splitter[0][opts.pxFixed] - splitter._PBF;
splitter._DA = splitter[0][opts.pxSplit] - splitter._PBA;
// Bail if splitter isn't visible or content isn't there yet
if ( splitter._DF <= 0 || splitter._DA <= 0 ) return;
// Re-divvy the adjustable dimension; maintain size of the preferred pane
resplit(!isNaN(size)? size : (!(opts.sizeRight||opts.sizeBottom)? A[0][opts.pxSplit] :
splitter._DA-B[0][opts.pxSplit]-bar._DA));
}).trigger("resize" , [initPos]);
});
};
})(jQuery);
The plugin you are using is based on a old jQuery version. For some reason, an infinite recursion was introduced by jQuery 1.6, probably due to event bubbling. It seems like a resize event triggered on a specific DOM element follow the event propagation path, all the way to document.
In the resize event handler, you can add a test to prevent recursion:
$(window).bind("resize", function (e) {
if (e.target === window) { splitter.trigger('resize'); }
});
That works, at least in Chrome and Firefox.
Using jQuery Migrate plugin will allow you to use jQuery 1.9 and even 2.0; but relying on browser specific behavior is generally a bad practice. You may have a look at this splitter.js fork, which already fixes your infinite recursion issue, using the same test as above.

textarea autogrow functionality jitters with every keystroke

I was playing around with the jquery autogrow plugin, which expands the height of the text automatically as the text needs it. The problem is that with every key down, the bottom border of the textarea jitters in a noticeable way. I'm not sure what the problem could be, so I'm going to go out on a limb and post the 132 lines of this GPL plugin here. Any hints where the problem could be or how to circumvent it?
/*
Auto Expanding Text Area (1.2.2) by Chrys Bader */
(function(jQuery) {
var self = null;
jQuery.fn.autogrow = function(o){
return this.each(function() {
new jQuery.autogrow(this, o);
});
};
/**
* The autogrow object.
*
* #constructor
* #name jQuery.autogrow
* #param Object e The textarea to create the autogrow for.
* #param Hash o A set of key/value pairs to set as configuration properties.
* #cat Plugins/autogrow
*/
jQuery.autogrow = function (e, o) {
this.options = o || {};
this.dummy = null;
this.interval = null;
this.line_height = this.options.lineHeight || parseInt(jQuery(e).css('line-height'));
this.min_height = this.options.minHeight || parseInt(jQuery(e).css('min-height'));
this.max_height = this.options.maxHeight || parseInt(jQuery(e).css('max-height'));;
this.textarea = jQuery(e);
if(this.line_height == NaN) this.line_height = 0;
// Only one textarea activated at a time, the one being used
this.init();
};
jQuery.autogrow.fn = jQuery.autogrow.prototype = { autogrow: '1.2.2' };
jQuery.autogrow.fn.extend = jQuery.autogrow.extend = jQuery.extend;
jQuery.autogrow.fn.extend({ init: function(){
var self = this;
this.textarea.css({overflow: 'hidden', display: 'block'});
this.textarea.bind('focus', function(){ self.startExpand() }).bind('blur', function() { self.stopExpand() });
this.checkExpand();
},
startExpand: function() {
var self = this;
this.interval = window.setInterval(function() { self.checkExpand()}, 400); },
stopExpand: function() { clearInterval(this.interval); },
checkExpand: function() {
if (this.dummy == null) {
this.dummy = jQuery('<div></div>');
this.dummy.css({
'font-size' : this.textarea.css('font-size'),
'font-family': this.textarea.css('font-family'),
'width' : this.textarea.css('width'),
'padding' : this.textarea.css('padding'),
'line-height': this.line_height + 'px',
'overflow-x' : 'hidden',
'position' : 'absolute',
'top' : 0,
'left' : -9999
}).appendTo('body');
}
// Strip HTML tags
var html = this.textarea.val().replace(/(<|>)/g,'');
// IE is different, as per usual
if ($.browser.msie){
html = html.replace(/\n/g, '<BR>new');
} else {
html = html.replace(/\n/g, '<br>new');
}
if (this.dummy.html() != html){
this.dummy.html(html);
if (this.max_height > 0 && (this.dummy.height() + this.line_height > this.max_height)){
this.textarea.css('overflow-y', 'auto');
} else {
this.textarea.css('overflow-y', 'hidden');
if (this.textarea.height() < this.dummy.height() + this.line_height || (this.dummy.height() < this.textarea.height())) {
this.textarea.animate({height: (this.dummy.height() + this.line_height) + 'px'}, 100);
}
}
}
}
});
})(jQuery);
In regard to jeerose's comment:
http://www.aclevercookie.com/aclevercookiecom-breached-problem-resolved/
It has been brought to my attention by
visitors that their virus protection
goes off when they come to this blog.
I investigated the matter and found
that harmful code had been injected
into the source of the site.
This has been resolved and measures
have been taken to increase the
security of the site.
Thanks for the report, and I apologize
for the alarm.
Which doesn't seem to be true. As my antivirus still fires when opening that site

Categories

Resources