jQuery horizontal ui scroll not calculating outerWidth in Chrome - jquery-ui

I'm having a problems to make a jQuery horizontal ui scrollbar work in Chrome. It works just fine in FireFox and even IE, but in Chrome I simply can't make it calculate the correct width of my "content" area. The "container" has a 920px fixed width, so no problem with that, but my "content" is, "on this page", exactly 4983px wide but when calculating with outerWidth() and even outerWidth(true), it will return a nonsense value that's a lot smaller than it should be!
Here's the link to the page I'm working on.
And here's the code I have until now. It's a mess because I'm still working and doing some tests...
var container = $('.gallery');
var content = $('.content', container);
var itemsWidth = content.outerWidth(true) - container.width();
var width = 0;
$('figure').each(function() {
width += $(this).width();
});
console.log('I dont know if I chose width: ' + width);
console.log('Or if I chose itemsWidth: ' + itemsWidth);
console.log('Actually, none of them is working on Chrome/webkit browsers');
$('.slider', container).slider({
min: 0,
max: itemsWidth - 20,
stop: function(event, ui){
content.animate({ 'margin-left' : ui.value * -1}, 500);
},
slide: function(event, ui){
console.log(ui.value);
content.css('margin-left',ui.value * -1);
}
});
Notice that I'm trying to calculate the width value in two different ways: itemsWidth (var) and width (var). None of them work. Strange thing is... if you keep refreshing the browser (Chrome), it will eventually grab the correct width of the "content", but it's like once in every 10–15 tries =\
It seems to be a Chrome/Webkit bug, but I have no idea about how to solve that!
Thanks for your time and help!

Related

Trigger resizable in jasmine [duplicate]

I have a div element which is made jquery Resizable. It has alsoResize option set, so other elements resize simultaneously.
What I want to do, is to set size of this Resizable div element programmatically in such way, that all Resizable logic is triggered (especially this alsoResize option is taken into account).
How can I achieve that?
Update: It looks like the internals of jQuery UI have changed dramatically since I answered this and firing the event no longer works.
There's no direct way to fire the event anymore because the resizable plugin has been fundamentally changed. It resizes as the mouse is dragged rather than syncing items up at the end. This happens by it listening for the internal resize propagation event for resizable plugins which is now fired by the _mouseDrag handler. But it depends on variables set along the way, so just firing that even internally won't help.
This means even overriding it is messy at best. I'd recommend just manually resizing the alsoResize elements directly, independent of the UI widget altogether if that's possible.
But for fun let's say it isn't. The problem is that the internals of the plugin set various properties relating to previous and current mouse position in order to know how much to resize by. We can abuse use that to add a method to the widget, like this:
$.widget("ui.resizable", $.ui.resizable, {
resizeTo: function(newSize) {
var start = new $.Event("mousedown", { pageX: 0, pageY: 0 });
this._mouseStart(start);
this.axis = 'se';
var end = new $.Event("mouseup", {
pageX: newSize.width - this.originalSize.width,
pageY: newSize.height - this.originalSize.height
});
this._mouseDrag(end);
this._mouseStop(end);
}
});
This is just creating the mouse events that the resizable widget is looking for and firing those. If you wanted to do something like resizeBy it'd be an even simpler end since all we care about is the delta:
var end = $.Event("mouseup", { pageX: newSize.width, pageY: newSize.height });
You'd call the $.widget() method after jQuery UI and before creating your .resizable() instances and they'll all have a resizeTo method. That part doesn't change, it's just:
$(".selector").resizable({ alsoResize: ".other-selector" });
Then to resize, you'd call that new resizeTo method like this:
$(".selector").resizable("resizeTo", { height: 100, width: 200 });
This would act as if you instantly dragged it to that size. There are of course a few gotchas here:
The "se" axis is assuming you want resize by the bottom right - I picked this because it's by far the most common scenario, but you could just make it a parameter.
We're hooking into the internal events a bit, but I'm intentionally using as few internal implementation details as possible, so that this is less likely to break in the future.
It could absolutely break in future versions of jQuery UI, I've only tried to minimize the chances of that.
You can play with it in action with a fiddle here and the resizeBy version here.
Original answer:
You can do this:
$(".selector").trigger("resize");
alsoResize internally rigs up a handler to the resize event, so you just need to invoke that :)
You can trigger the bars programmatically. For example, to trigger the east-west resize event:
var elem =... // Your ui-resizable element
var eastbar = elem.find(".ui-resizable-handle.ui-resizable-e").first();
var pageX = eastbar.offset().left;
var pageY = eastbar.offset().top;
(eastbar.trigger("mouseover")
.trigger({ type: "mousedown", which: 1, pageX: pageX, pageY: pageY })
.trigger({ type: "mousemove", which: 1, pageX: pageX - 1, pageY: pageY })
.trigger({ type: "mousemove", which: 1, pageX: pageX, pageY: pageY })
.trigger({ type: "mouseup", which: 1, pageX: pageX, pageY: pageY }));
I am doing a 1px left followed by 1px right movement on the east bar handle.
To perform a full size, you can target .ui-resizable-handle.ui-resizable-se if you have east and south resize bars.
I needed the same thing for tests. Similar questions have only one promising answer https://stackoverflow.com/a/17099382/1235394, but it requires additional setup, so I ended with my own solution.
I have an element with resizable right edge
$nameHeader.resizable({handles: 'e', ... });
and I needed to trigger all callbacks during the test in order to resize all elements properly. The key part of test code:
var $nameHeader = $list.find('.list-header .name'),
$nameCell = $list.find('.list-body .name');
ok($nameHeader.hasClass('ui-resizable'), 'Name header should be resizable');
equal($nameCell.outerWidth(), 300, 'Initial width of Name column');
// retrieve instance of resizable widget
var instance = $nameHeader.data('ui-resizable'),
position = $nameHeader.position(),
width = $nameHeader.outerWidth();
ok(instance, 'Instance of resizable widget should exist');
// mouseover initializes instance.axis to 'e'
instance._handles.trigger('mouseover');
// start dragging, fires `start` callback
instance._mouseStart({pageX: position.left + width, pageY: position.top});
// drag 50px to the right, fires `resize` callback
instance._mouseDrag({pageX: position.left + width + 50, pageY: position.top});
// stop dragging, fires `stop` callback
instance._mouseStop({pageX: position.left + width + 50, pageY: position.top});
// ensure width of linked element is changed after resizing
equal($nameCell.outerWidth(), 350, 'Name column width should change');
Of course this code is brittle and may break when widget implementation changes.
Hack Disclaimer (tested on jQuery 1.12.4):
This basically waits for the dialog to be opened and then increments by 1px (which forces the resize() event) and then decrements by 1px (to regain original size)
just say this in the dialog open event handler:
$(this)
.dialog("option","width",$(this).dialog("option","width")+1)
.dialog("option","width",$(this).dialog("option","width")-1);
note:
This may not work with show effects (like fadeIn,slideDown etc) as the "resizer" code executes before the dialog is fully rendered.
$(".yourWindow").each(function(e) {
$(this).height($(this).find(".yourContent").height());
});
And the same with the width.

Is there a way of dynamically toggling the Highstock navigator to regain vertical space for the chart?

I'd like to be able to be able to dynamically toggle the presence of the Highstock navigator and allow the chart to expand into the vertical space it occupied.
I've tried simply toggling chart.userOptions.navigator.enabled but it has no effect.
This thread explains how to use .hide() and .show() methods to conceal the individual components of the navigator and scrollbar, but these use visibility:hidden so the space does not become available for the chart. However, using .css({display: 'none'}) works, but the series itself has no .css() method, and I've been unable to find a way of removing the series from just the navigator.
Does anyone know a method to achieve what I want?
Thanks.
In short: it's not supported to hide navigator in real time. The best way would be to destroy chart and create new one with disabled navigator.
Other solution is to use workaround provided by Sebastian Bochan. Then you will need to update manually yAxis.height, for example: http://jsfiddle.net/dJbZT/91/
$('#btn').toggle(function () {
chart.yAxis[0].defaultHeight = chart.yAxis[0].height;
chart.xAxis[0].defaultHeight = chart.xAxis[0].height;
chart.yAxis[0].update({
height: 500 - chart.plotTop - 35
}, false);
chart.xAxis[0].update({
height: 500 - chart.plotTop - 35
});
chart.scroller.xAxis.labelGroup.hide();
chart.scroller.xAxis.gridGroup.hide();
chart.scroller.series.hide();
chart.scroller.scrollbar.hide();
chart.scroller.scrollbarGroup.hide();
chart.scroller.navigatorGroup.hide();
$.each(chart.scroller.elementsToDestroy, function (i, elem) {
elem.hide();
})
}, function () {
chart.yAxis[0].update({
height: chart.yAxis[0].defaultHeight
}, false);
chart.xAxis[0].update({
height: chart.xAxis[0].defaultHeight
});
chart.scroller.xAxis.labelGroup.show();
chart.scroller.xAxis.gridGroup.show();
chart.scroller.series.show();
chart.scroller.navigatorGroup.show();
chart.scroller.scrollbar.show();
chart.scroller.scrollbarGroup.show();
$.each(chart.scroller.elementsToDestroy, function (i, elem) {
elem.show();
})
});
There's another way to do this: reduce the chart height by the navigator's height, and set chart.reflow to false to prevent the Y-axis from adapting to the new chart height (try setting it to true in the fiddle -- notice the flicker when you show / hide the navigator?).
I've added this answer to the other thread, and the demo is here: http://jsfiddle.net/dJbZT/148/ (credits to Sebastian Bochan for the original answer).
I'm not sure when highcharts added this ability via options, but this worked for me:
var chart = $('#graphContainer').highcharts();
chart.options.navigator.enabled = !chart.options.navigator.enabled;
$('#graphContainer').highcharts(chart.options);

Integrate jquery ui draggable with jquery.gantt (works but breaks scrolling)

I am using the jquery-ui draggable component with jquery.gantt here. I could do enable drag on the items easily by $('.ganttRed').draggable() but the problem with this is that once we start scrolling the graph left to right using the slider below, the elements that are moved remain where they are instead of scrolling with the graph.
I looked through the source and from my understanding the margin-left is being changed during the scrolling; but jquery-ui uses the left attribute and in the presence of left the element keeps its position. My CSS knowledge ends just about there so if any of you are willing to provide any suggestions on how this can be fixed; I will greatly appreciate it.
I have a created a fiddle demonstrating the problem at: http://jsfiddle.net/Y2cxa/. In order to see the behavior I am speaking about:
Scroll the graph (either with your mouse wheel or the slider at the bottom); things should look and behave as expected.
Move any of the magenta(-ish) bars around and then scroll.
Again, thank you for your time and any assistance will be greatly appreciated.
Best regards
You have probably solved this or done something else by now but since I needed this aswell i solved it.
Got a solution for you here:
http://jsfiddle.net/Y2cxa/18/
First I simply copied the left value to margin-left and then removed the left value completely, however this led to some strange numbers.
To solve this I compared the start value of left with the final value of left and applied the same difference in pixels to margin-left!
Simply replace:
$('.ganttRed').draggable({axis:'x'});
with:
$('.ganttRed').draggable({
axis:'x',
start: function(event, ui) {
$(this).data("startx",$(this).offset().left);
},
stop: function(event, ui) {
var change = $(this).offset().left - $(this).data("startx");
var value = $(this).css('margin-left');
value = value.split("px");
value = parseInt(value[0]) + change;
$(this).css('margin-left', value);
$(this).css('left', '');
}
});
I believe below is a better solution and I am using it in my application
For vertical and horizonal dragging
$('.ganttRed').draggable(
{
start: function (event, ui) {
$(this).data("startx", $(this).css('left').split("px")[0]);
$(this).data("starty", $(this).css('top').split("px")[0]);
},
stop: function (event, ui) {
var left = parseInt($(this).css('left').split("px")[0]);
var changex = left - parseInt($(this).data("startx"));
var top = parseInt($(this).css('top').split("px")[0]);
top -= top % 24;
$(this).css('top', top);
var changey = top - parseInt($(this).data("starty"));
}
});
changex, changey will be used in calculation while updating in database
For horizontal resizing
$(".ganttRed").resizable({ handles: 'e, w' });

SVG 'getBBox' fails in a jQueryUI tab

I have a stand-alone SVG chart generator that works with all the major browsers. However, I've just added code to display the charts inside a jQuery UI tab, and the code has broken. Specifically, 'getBBox' now generally fails. It throws an exception in FF, works as expected in Opera, and gives the wrong answer in Chrome and Safari.
The difference between the old and new code is only, I think, in my understanding of what a 'document' is inside a tab. In the old stand-alone code, I could display a rectangle and get it's bbox as follows (in all browsers):
var svgDocument;
var svgNS = "http://www.w3.org/2000/svg";
...
if(window.svgDocument == null)
svgDocument = evt.target.ownerDocument;
...
var lbox = svgDocument.createElementNS(svgNS, "rect");
lbox.setAttributeNS(null, "x", 50);
lbox.setAttributeNS(null, "y", 50);
lbox.setAttributeNS(null, "width", 40);
lbox.setAttributeNS(null, "height", 40);
lbox.setAttributeNS(null, "stroke", "#E810D6");
lbox.setAttributeNS(null, "stroke-width", 2);
lbox.setAttributeNS(null, "fill-opacity", 1);
lbox.setAttributeNS(null, "stroke-opacity", 1);
lbox.setAttributeNS(null, "stroke-dasharray", 0);
svgDocument.documentElement.appendChild(lbox); // displays the box
var bbox = lbox.getBBox(); // gets the box bounds
The problem is that, when I try to display inside a tab, it's not obvious what svgDocument should be. This is my current code:
var svgDocument = document;
var svgNS = "http://www.w3.org/2000/svg";
var svgRoot;
...
// handle jQuery UI tabs as follows:
var top, svg, chart;
top = $(ui.panel).get(0);
svg = svgDocument.createElementNS(svgNS, "svg");
chart = "chart" + "-" + ui.panel.id;
svg.setAttributeNS(null, "id", chart);
top.appendChild(svg);
svgRoot = svgDocument.getElementById(chart);
...
// SVG draw is identical, except that svgDocument.documentElement is now svgRoot:
var lbox = svgDocument.createElementNS(svgNS, "rect");
lbox.setAttributeNS(null, "x", 50);
lbox.setAttributeNS(null, "y", 50);
lbox.setAttributeNS(null, "width", 40);
lbox.setAttributeNS(null, "height", 40);
lbox.setAttributeNS(null, "stroke", "#E810D6");
lbox.setAttributeNS(null, "stroke-width", 2);
lbox.setAttributeNS(null, "fill-opacity", 1);
lbox.setAttributeNS(null, "stroke-opacity", 1);
lbox.setAttributeNS(null, "stroke-dasharray", 0);
svgRoot.appendChild(lbox);
var bbox = lbox.getBBox();
The new code works "correctly" in Opera. FF, Chrome, and Safari display the rectangle correctly in the new tab, but get the bbox calculation wrong.
Any idea what I'm doing wrong here? Thanks.
[this is probably the same issue as Doing Ajax updates in SVG breaks getBBox, is there a workaround?, but there were no answers on that].
EDIT
I failed to mention that I'm rendering into a hidden tab, which is only displayed when the chart completes. Googling the FF exception code (in the comment below) indicates that there's some issue with getBBox when the element is not displayed. However, I don't understand this. I routinely use getBBox with visibility:hidden to size complex elements before displaying them, on all browsers (when I'm not using tabs). Besides, the rectangle in the example does actually render, as I can see it when the tab becomes visible, so shouldn't getBBox should also work?
Fixed - the answer is actually in the tabs documentation. Whoops.
From http://docs.jquery.com/UI/Tabs#...my_slider.2C_Google_Map.2C_sIFR_etc._not_work_when_placed_in_a_hidden_.28inactive.29_tab.3F
Any component that requires some dimensional computation for its initialization won't work in a hidden tab, because the tab panel itself is hidden via display: none so that any elements inside won't report their actual width and height (0 in most browsers).
There's an easy workaround. Use the off-left technique for hiding inactive tab panels. E.g. in your style sheet replace the rule for the class selector ".ui-tabs .ui-tabs-hide" with
.ui-tabs .ui-tabs-hide {
position: absolute;
left: -10000px;
}

getting jQuery UI's datepicker to always open in a certain direction?

I'm using jQuery UI's datepicker control in a position: fixed toolbar at the bottom of my page. Occasionally, on random computers, the datepicker appears below the toolbar, which means it's off the page and impossible to view or interact with.
Is there a way to force the positioning of the datepicker control to always be above and to the right of its <input>?
The only way to be certain (for the jQueryUI version of datepicker) is to disable the functionality of the datepicker that tries to render inside the viewport. Here's a way to do it without modifying the source code files:
$.extend(window.DP_jQuery.datepicker,{_checkOffset:function(inst,offset,isFixed){return offset}});
on later versions of JQuery UI try:
$.extend($.datepicker,{_checkOffset:function(inst,offset,isFixed){return offset}});
That just nukes the _checkOffset function inside datepicker that makes it squirrelly. Then you can use the .ui-datepicker css to make sure it stays fixed if that's what you're after. More info at how-to-control-positioning-of-jqueryui-datepicker.
Problem is that element in position: fixed show top position 0px (check with: alert$('#datepicker2').position()).
Solution:
$('#datepicker').datepicker( {beforeShow: function(input) {
var x = 100; //add offset
var y = 20;
field = $(input);
left = field.position().left + x;
bottom = y;
setTimeout(function(){
$('#ui-datepicker-div').css({'top':'', 'bottom':bottom + 'px', 'left': left + 'px'});
},1);
}}
Test HTML:
<form style="position:fixed; bottom:0; width:100%" name="form1" method="post" action="">
<label>
<input style="left:300px; position:absolute; bottom:0" type="text" name="textfield" id="datepicker">
</label>
</form>
You could change the lines:
offset.left -= (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ? Math.abs(offset.left + dpWidth - viewWidth) : 0;
offset.top -= (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ? Math.abs(offset.top + dpHeight + inputHeight*2 - viewHeight) : 0;
...to read:
offset.left = $(inst.input).position().left + dpWidth;
offset.top = $(inst.input).position().top - dpHeight;
This loses flexibility, though. If your input happens to be at the top of the page, you'll have the opposite problem from before.
http://www.mindfiresolutions.com/Make-jQuery-datepicker-to-popup-in-different-positions-995.php
check this. I used this and was able to position the datepicker control in all browsers.
I had a similar problem. I have a page with date pickers potentially used at various placed on the page but also on a fixed header where the user can scroll the page both horizonally and vertically with the fixed header staying in place. The header also has a datepicker. So I can't do a global change of datepicker.
This is what I did. It is admittedly a kluge but it works so I thought it might help someone else. Hopefully in the future the jquery datepicker will add a position option.
beforeShow: function(input, inst) {
$("#ui-datepicker-div").css({ "visibility": "hidden", "display": "none" );
window.setTimeout(function() {
var leftPosition = parseInt($(window).width() / 2);
$("#ui-datepicker-div").css({ "position": "fixed", "top": 0, "left": leftPosition });
$("#ui-datepicker-div").css({ "visibility": "visible", "display": "inherit" );
}, 500);
}
From the documentation, it looks like you might be able to use the 'dialog' method of the datepicker plugin to achieve your desired outcome. However, using this most likely means that you will have to implement some of the glue that you would otherwise get out-of-the-box with datepicker, such as a callback handler to extract the date, etc.
I tried to mock up some code to see it in action and short of getting the datepicker to display, I couldn't quite get it working, though. Anyway, I wanted to point you to it in case you have better luck than I did.

Resources