Jquery splitter plugin getting error too much recursion - javascript

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.

Related

Auto Scaling Image Annotation

Scalize is a jQuery plugin used for adding custom markers (hotspots) with custom popovers and animations to containers or images.
But now When I click one by one on pointer it show all one by one But I am trying to show only one so when click another pointer will close the other which already opened.
Here is my EXAMPLE
(function(jQuery) {
"use strict";
//----------------------------------------//
// Variable
//----------------------------------------//
var variable = {
width : 0,
height : 0,
selector : '.item-point',
styleSelector : 'circle',
animationSelector : 'pulse2',
animationPopoverIn : 'flipInY',
animationPopoverOut : 'flipOutY',
onInit : null,
getSelectorElement : null,
getValueRemove : null
}
//----------------------------------------//
// Scaling
//----------------------------------------//
var scaling = {
settings : null,
//----------------------------------------//
// Initialize
//----------------------------------------//
init: function(el, options){
this.settings = jQuery.extend(variable, options);
this.event(el);
scaling.layout(el);
jQuery(window).on('load', function(){
scaling.layout(el);
});
jQuery(el).find('.target').on('load', function(){
scaling.layout(el);
});
jQuery(window).on('resize', function(){
scaling.layout(el);
});
},
//----------------------------------------//
// Event
//----------------------------------------//
event : function(elem){
// Set Style Selector
if ( this.settings.styleSelector ) {
jQuery(this.settings.selector).addClass( this.settings.styleSelector );
}
// Set Animation
if ( this.settings.animationSelector ) {
if( this.settings.animationSelector == 'marker' ){
jQuery(this.settings.selector).addClass( this.settings.animationSelector );
jQuery(this.settings.selector).append('<div class="pin"></div>')
jQuery(this.settings.selector).append('<div class="pulse"></div>')
}else{
jQuery(this.settings.selector).addClass( this.settings.animationSelector );
}
}
// Event On Initialize
if ( jQuery.isFunction( this.settings.onInit ) ) {
this.settings.onInit();
}
// Content add class animated element
jQuery(elem).find('.content').addClass('animated');
// Wrapper selector
jQuery(this.settings.selector).wrapAll( "<div class='wrap-selector' />");
// Event Selector
jQuery(this.settings.selector).each(function(){
// Toggle
jQuery('.toggle', this).on('click', function(e){
e.preventDefault();
jQuery(this).closest(scaling.settings.selector).toggleClass('active');
// Selector Click
var content = jQuery(this).closest(scaling.settings.selector).data('popover'),
id = jQuery(content);
if(jQuery(this).closest(scaling.settings.selector).hasClass('active') && !jQuery(this).closest(scaling.settings.selector).hasClass('disabled')){
if ( jQuery.isFunction( scaling.settings.getSelectorElement ) ) {
scaling.settings.getSelectorElement(jQuery(this).closest(scaling.settings.selector));
}
id.fadeIn(500,function(){
if( getBrowserName() == "Safari" ){
setTimeout(function(){
id.removeClass('flipInY');
},125);
}
});
scaling.layout(elem);
id.removeClass(scaling.settings.animationPopoverOut);
id.addClass(scaling.settings.animationPopoverIn);
}else{
if(jQuery.isFunction( scaling.settings.getValueRemove )){
scaling.settings.getValueRemove(jQuery(this).closest(scaling.settings.selector));
}
id.removeClass(scaling.settings.animationPopoverIn);
id.addClass(scaling.settings.animationPopoverOut);
id.delay(500).fadeOut();
}
});
// Exit
var target = jQuery(this).data('popover'),
idTarget = jQuery(target);
idTarget.find('.exit').on('click', function(e){
e.preventDefault();
// selector.removeClass('active');
jQuery('[data-popover="'+ target +'"]').removeClass('active');
idTarget.removeClass(scaling.settings.animationPopoverIn);
idTarget.addClass(scaling.settings.animationPopoverOut);
idTarget.delay(500).fadeOut();
});
});
},
//----------------------------------------//
// Layout
//----------------------------------------//
layout : function(elem){
// Get Original Image
var image = new Image();
image.src = elem.find('.target').attr("src");
// Variable
var width = image.naturalWidth,
height = image.naturalHeight,
getWidthLess = jQuery(elem).width(),
setPersenWidth = getWidthLess/width * 100,
setHeight = height * setPersenWidth / 100;
// Set Heigh Element
jQuery(elem).css("height", setHeight);
// Resize Width
if( jQuery(window).width() < width ){
jQuery(elem).stop().css("width","100%");
}else{
jQuery(elem).stop().css("width",width);
}
// Set Position Selector
jQuery(this.settings.selector).each(function(){
if( jQuery(window).width() < width ){
var getTop = jQuery(this).data("top") * setPersenWidth / 100,
getLeft = jQuery(this).data("left") * setPersenWidth / 100;
}else{
var getTop = jQuery(this).data("top"),
getLeft = jQuery(this).data("left");
}
jQuery(this).css("top", getTop + "px");
jQuery(this).css("left", getLeft + "px");
// Target Position
var target = jQuery(this).data('popover'),
allSize = jQuery(target).find('.head').outerHeight() + jQuery(target).find('.body').outerHeight() + jQuery(target).find('.footer').outerHeight();
jQuery(target).css("left", getLeft + "px");
jQuery(target).css("height", allSize + "px");
if(jQuery(target).hasClass('bottom')){
var getHeight = jQuery(target).outerHeight(),
getTopBottom = getTop - getHeight;
jQuery(target).css("top", getTopBottom + "px");
}else if(jQuery(target).hasClass('center')){
var getHeight = jQuery(target).outerHeight() * 0.50,
getTopBottom = getTop - getHeight;
jQuery(target).css("top", getTopBottom + "px");
}else{
jQuery(target).css("top", getTop + "px");
}
jQuery('.toggle', this).css('width', jQuery(this).outerWidth());
jQuery('.toggle', this).css('height', jQuery(this).outerHeight());
// Toggle Size
if(jQuery(this).find('.pin')){
var widthThis = jQuery('.pin', this).outerWidth(),
heightThis = jQuery('.pin', this).outerHeight();
jQuery('.toggle', this).css('width', widthThis);
jQuery('.toggle', this).css('height', heightThis);
}
});
}
};
//----------------------------------------//
// Scalize Plugin
//----------------------------------------//
jQuery.fn.scalize = function(options){
return scaling.init(this, options);
};
}(jQuery));
function getBrowserName() {
var name = "Unknown";
if(navigator.userAgent.indexOf("MSIE")!=-1){
name = "MSIE";
}
else if(navigator.userAgent.indexOf("Firefox")!=-1){
name = "Firefox";
}
else if(navigator.userAgent.indexOf("Opera")!=-1){
name = "Opera";
}
else if(navigator.userAgent.indexOf("Chrome") != -1){
name = "Chrome";
}
else if(navigator.userAgent.indexOf("Safari")!=-1){
name = "Safari";
}
return name;
}
Add this to your initialisation:
getSelectorElement: function(el) {
$('.item-point.active').not($(el)[0]).find('.toggle').click();
}
This hooks into the getSelectorElement method in the Scalize plugin and triggers a click on any active (open) elements that don't match the most recently clicked item.
Add it like so:
$(document).ready(function(){
$('.scalize').scalize({
styleSelector: 'circle',
animationPopoverIn: 'fadeIn',
animationPopoverOut: 'fadeOut',
animationSelector: 'pulse2',
getSelectorElement: function(el) {
$('.item-point.active').not($(el)[0]).find('.toggle').click();
}
});
});
Note, because this is hooking into existing methods in the plugin it's a little safer (no unpredictable side effects, plus you get the intended transition out on the disappearing elements). Fiddle.
I've modified your jsFiddle to work.
TL;DR: Anytime an point is clicked, if there are other active siblings, loop over them and hide their popups.
It isn't a pretty way of doing it but it is working in the Fiddle.
$('.scalize').on('click', '.item-point', (function() {
$(this).siblings('.item-point.active').each(function() {
var popover = $(this).data('popover');
$(popover).removeClass('fadeIn').css({
'display': 'none'
});
$(this).removeClass('active');
});
}));

Javascript scrolling on XY axis

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.

Displaying google maps within nested divs (splitter)

I've read many answers to the issue of map not being displayed when put inside nested divs, i tried everything but still could not get it working.
I need to have a splitter between directions panel and the actual map, and i am using the code i've found for splitter, combined with the map code. But map is never displayed, only grey background.
I have to admit i am illiterate with HTML design, CSS and JavaScript. Please if anyone could easily see the issue, i would be very grateful. Thank you.
<HTML>
<HEAD>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&language=en&libraries=drawing&key=AIzaSyASrsCWlCQ1YlOlkgyf3tMQf8EiOU8rKv0"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<style>
html, body, {
margin: 0;
padding: 0;
height: 500px;
width: 500px;
}
.simple {
height: 1000px;
width: 1000px;
position: absolute
}
.simple div {
overflow: auto
}
.hsplitbar {
height: 5px;
background: #cab
}
.hsplitbar:hover{
background: #eab
}
</style>
<script type="text/javascript">
;(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 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);
var geocoder;
var map;
var startMarker;
var AllMarkers = [];
var routeRectangle;
var drawingManager;
var directionsService;
var directionsDisplay;
var waypts = [];
var routeWaypts = [];
var routeMarkers = [];
var start;
var finish;
var route;
var addresses = [];
var innerHTML;
var totalDistance = 0;
var totalDuration = 0;
function initialize() {
$().ready(function() {
$(".simple").splitter({type: 'h', accessKey: 'M'});
});
geocoder = new google.maps.Geocoder();
var myOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
panControl: true,
zoomControl: true,
mapTypeControl: true,
scaleControl: true,
streetViewControl: true,
overviewMapControl: true
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
geocoder.geocode({'address': 'US'}, function (results, status) {
var ne = results[0].geometry.viewport.getNorthEast();
var sw = results[0].geometry.viewport.getSouthWest();
map.setZoom(20);
map.fitBounds(results[0].geometry.viewport);
});
</script>
</head>
<body onload="initialize()">
<div class="simple">
<div id="directions_panel" style="500px;height:500px"></div>
<div id="map_canvas" style="500px;height:500px"></div>
</div>
</body>
</html>
replace this:
.simple div {
overflow: auto
}
with that:
.simple>div {
overflow: auto
}

Why can't I draw elements to the stage?

Fiddle - http://liveweave.com/JS9EBN
This is a starter template for web design applications. (well almost except for the drawing problem)
Elements are drawn to the stage like so.
// Handles Drawable Elements
$("#canvas").on('mousedown touchstart', function(e) {
if(drawable) {
drawing = true;
mS.x = e.pageX;
mS.y = e.pageY;
dBox = $("<" + $('.draw-elements input[type=radio]:checked').val() + " class='box' />")
.html("Certains textes");
$(this).append(dBox);
// Do not select text when drawing
return false;
}
});
$(document).on('mousemove touchmove', function(e) {
if(drawing && drawable){
var mPos = {x:e.pageX, y:e.pageY};
var css = {};
css.position = 'absolute';
css.left = (mPos.x > mS.x) ? mS.x : mPos.x;
css.top = (mPos.y > mS.y) ? mS.y : mPos.y;
css.width = Math.abs(mPos.x - mS.x);
css.height = Math.abs(mPos.y - mS.y);
css.border = '1px dotted rgb(0, 34, 102)';
dBox.css(css);
// Do not select text when drawing
return false;
}
}).on('mouseup touchend', function(e) {
drawing = false;
});
As long as my select tool is not called I can draw elements without a problem, but when it is called and I come back to draw a div I can no longer draw elements to my stage.
After some tinkering I noticed the problem resides with my drag function for each element that's selected.
var HandleSelectedElement = function() {
if ($(".select-tool.activetool").is(":visible")) {
if(elmstyle) {
$('#canvas').children().drag("start",function( ev, dd ){
dd.attrc = $( ev.target ).prop("className");
dd.attrd = $( ev.target ).prop("id");
dd.width = $( this ).width();
dd.height = $( this ).height();
})
.drag(function( ev, dd ){
var props = {};
if ( dd.attrc.indexOf("E") > -1 ){
props.width = Math.max( 32, dd.width + dd.deltaX );
}
if ( dd.attrc.indexOf("S") > -1 ){
props.height = Math.max( 32, dd.height + dd.deltaY );
}
if ( dd.attrc.indexOf("W") > -1 ){
props.width = Math.max( 32, dd.width - dd.deltaX );
props.left = dd.originalX + dd.width - props.width;
}
if ( dd.attrc.indexOf("N") > -1 ){
props.height = Math.max( 32, dd.height - dd.deltaY );
props.top = dd.originalY + dd.height - props.height;
}
if ( dd.attrd.indexOf("stylethis") > -1 ){
props.top = dd.offsetY;
props.left = dd.offsetX;
}
$('#stylethis').css( props );
}, {relative:true});
}
};
I don't understand what's wrong.
I couldn't find out how to solve the initial problem. So I decided to do a work around.
Here's the fiddle: http://liveweave.com/g2aKlD
I decided to refresh the canvas each time a tool is clicked. I take the canvas's html and set that as a textarea's value. I then set the textarea's value as the canvas's html.
$("#code").val($("#canvas").html());
$("#canvas").html($("#code").val());
This way whatever called the initial bug is removed completely. However last time I did this all spaces where turned into a otherwise known as a non-breakable space (I've also seen this also add unnecessary line breaks and paragraphs when not needed)
I still don't understand why my draw function did not work when drag was turned off.
I really hate having to do this (being refreshing the canvas) because the more elements that are in there and the more refreshing is done, the more ram it uses which makes the browser work the cpu that much harder.
I hope someone can come across a better solution.

create fn function with callback

I did the following little plugIn (to add to query.transit by Rico St Cruz):
$.fn.translateLeft = function( left, duration, easing, callback ) {
var $this = $(this);
var currentLeftPx = parseInt( $this.css('left') );
var parentWidth = $this.parent().width();
// final left layout destination in px
var finalLeftPx = parentWidth/100 * left;
// actual distances to final left layout destination in px
var distanceLeftPx = currentLeftPx - finalLeftPx;
$this.transition( { x: -distanceLeftPx }, duration, easing, function() {
$this.stop(true).css( { left: left +'%', x: 0 } );
callback();
} );
}
I used it (without the callback I tried to implement it worked well so far) so:
$("#someElement").translateLeft( 10.5, 300, 'easeOutSine', function() {
// do something else
} );
This helps to make smooth x translate instead of left, yet keeps the possibility to set % values that refer to the parent (which is not possible with x alone which refers alway to the element). This only for explanation.
And as I said it works very good, yet my inserted callback does not.
Did I do something wrong here semantically?
Thanks for advice!
Garavani
EDIT:
Thanks so far for your comments that made me think. Actually even in my (beginner) fn code the callback actually works if I put for example alert( "Callback" ) in there instead of the other code. So it seems it is not possible to mix up my plugIn with any kind of code. To complete my question here is the whole code involved even if I am quite aware that it is quite complicated and will make you run out of nerves.:
This is the function IN which I liked to use my plugIn:
function switchMenuItem( id ) {
var $menuItem = $("#"+ id );
var $menu = $menuItem.parent();
var $menuImg = $menu.children(); //all siblings including selected element by id
var $prev = $menuItem.prev();
// calculate animation values
var index = $menuImg.index( $menuItem );
var ww = $(window).width();
var cssLeftPx = parseInt( $menuItem.css('left') );
var cssLeftPercent = 100 * cssLeftPx/ww;
if ( index == 1 ) { var dur = ww/2.4; };
if ( index == 2 ) { var dur = ww/1.5; };
$menuItem .stop(true)
.animate( { left: '10.5%' }, dur, 'easeOutSine', function() {
$(this) .prependTo($menu );
} );
$menuImg .first()
.stop(true)
.animate( { left: cssLeftPercent+'%' }, dur, 'easeOutSine', function() {
$(this) .insertAfter( $prev );
$menuItem.siblings()
.animate( { opacity: 1 }, 150, 'linear' )
.css( { cursor: 'pointer' } );
switchComplete = true;
subReady = true;
} );
…
}
and I would love to get rid of the query animate and substitute it with a smooth x translate with the help of Rico St Cruz transit plugIn (in the way I did successfully before with my kind of plugIn:
$.fn.translateLeft = function( left, duration, easing, callback ) {
var $this = $(this);
var currentLeftPx = parseInt( $this.css('left') );
var parentWidth = $this.parent().width();
// final left layout destination in px
var finalLeftPx = parentWidth/100 * left;
// actual distances to final left layout destination in px
var distanceLeftPx = currentLeftPx - finalLeftPx;
$this.transition( { x: -distanceLeftPx }, duration, easing, function() {
$this.stop(true).css( { left: left +'%', x: 0 } );
callback();
} );
}
So instead of „animate“ I want to use „translate Left“ which uses a smooth x translate and then return at the end a „cleaned up“ css position so that it is ready for other window resizing etc.
Did I explain myself? Any advice is appreciated a lot. Thank you in advance!

Categories

Resources