Can stellar.js readjust element offsets on window resize? - javascript

Is there a way to reinitialize stellar.js on browser/window resize so that the element offsets get readjusted?

First of all, it sounds like you might be having an issue with horizontal alignment (assuming it's a vertical site). If so, it's likely that you only need to disable horizontal scrolling:
$.stellar({
horizontalScrolling: false
});
If this doesn't solve your issue, Stellar.js has an undocumented feature that allows you to refresh the plugin.
For example, let's assume you used Stellar.js like this:
$.stellar();
You can refresh it with the following:
$.stellar('refresh');
So, to refresh it on resize, you could do something like this:
$(window).resize(function() {
$.stellar('refresh');
});
Hopefully this should fix everything for you.

After a bit of sleuthing, I've figured this one out. In my case, I have 'slides', which contain my stellar elements, and they are sized to full width/height of the viewport. I needed to resize them for tablet orientation change.
$(window).resize(function(){
winHeight = $(window).height();
$("#scrollWrapper > div").height(winHeight);
// Find out all my elements that are being manipulated with stellar
var particles = $(window).data('plugin_stellar').particles;
// Temporarily stop stellar so we can move our elements around
// data('plugin_stellar') let's me access the instance of stellar
// So I can use any of its methods. See stellar's source code
$(window).data('plugin_stellar').destroy();
$.each(particles, function(i, el){
// destroy() sets the positions to their original PIXEL values.
// Mine were percentages, so I need to restore that.
this.$element.css('top', '');
// Once the loop is finished, re-initialize stellar
if(particles.length - 1 == i){
$(window).data('plugin_stellar').init();
}
});
});
If it doesn't matter that the elements get set to their original pixel values for left/top, then you can just call destroy & init one after the other:
$(window).data('plugin_stellar').destroy();
$(window).data('plugin_stellar').init();
If you instantiate stellar on an element (i.e., $("#element").stellar(); instead of $.stellar();) then replace "window" with your selector.

I also noticed odd offsets on mobiles that may be caused by the way Firefox/Chrome resizes the webview when scrolling down, when the location bar becomes visible again?
The answer to your question is in a section of the documentation: "Configuring everything":
// Refreshes parallax content on window load and resize
responsive: false,
So, this is false by default. To enable this, use .stellar( {responsive:true} )
The real question is... why is this disabled by default? It seemed to fix the problem I was noticing, except for iOS.

Related

Angular-gridster doesn't work on small screens

The problem
I noticed that angular-gridster stops working if the browser window is minimized to the point there's not much space around the gridster tiles (see image 2). However, gridster works alright when maximizing the window, and the elements are draggable and resizable again.
Progress
I modified the $scope.gridsterOpts object in the relevant controller and ensured that pushing, floating, swapping are all set to true, but that didn't solve the problem.
fiddle
In addition, I noticed that the same behavior could be found in
this fiddle - the "result" window has to be pretty big in height/width so the demo would work.
I do not include my project code as I think it's useless since I see this behavior in every demo of angular-gridster.
Did anyone experienced the same problem?
Thanks.
screenshot: working
screenshot: not working
This seems to be by design. As you can see here, angular-gridster has a so-called "mobile mode", meaning the plugin will stop working below a certain (configurable) screen width:
$scope.gridsterOpts = {
/// (...)
isMobile: false, // stacks the grid items if true
mobileBreakPoint: 600, // if the screen is not wider that this, remove the grid layout and stack the items
mobileModeEnabled: true, // whether or not to toggle mobile mode when screen width is less than mobileBreakPoint
/// (...)
};
The mobileBreakPoint is one more important think. The value of mobileBreakPoint 600 it means it will take half of the width in the screen if we set div width more then 600px it will work.If we need for minimum div width we need to change mobileBreakPoint value based on div width
$scope.gridsterOpts = {
mobileBreakPoint: 100, // if the screen is not wider that this,remove the grid layout and stack the items
};

Maintaining page view on window resize in a responsive website

Situation:
Suppose we are reading the content somewhere down the page that is built to be responsive. Suppose also that we resize the browser window to a smaller size and that some content above get extended down due to the thinner width, hence making the whole page longer. Then as we resize, whatever content we are looking at will get pushed down the page accordingly.
Example:
Suppose we were to look at the Helper classes section in this page. Then shrinking/expanding the window a sufficient amount moves the bit we were reading down/up the current view.
Prompt:
Is there any way we can fix this? I.e. maintain our current view of the page regardless of what happens to the contents above it when we resize the window.
Thoughts:
I am thinking that we could at least start with javascript and put an event on window resize. Then automatically scroll the page to the top-most element that was in our view on event fire. I don't know how this will affect the performance, however, especially in bigger pages.
There's also the problem of refering to the top-most element in current view. The top of our current view might be cutting off the top portion of some elements, not to mention that there's usually more than 1 element layered on top of one another at any point within the page. The notion of top-most element I've mentioned is not very well-defined :(
Also rather than a problem of responsive design in general, instead it seems to me like this is a problem with the default scrolling behaviour of web browsers? Or perhaps I am missing some circumstances where the current behaviour is desirable.
Edit 2 4
Updated fiddle (see fullscreen result) based on Rick Hitchcock's solution's solution.
With jQuery:
//onresize:
var scrollAmount;
if (topNode.getBoundingClientRect().top >= 0) {
scrollAmount = $(topNode).offset().top - topNode.getBoundingClientRect().top;
} else {
scrollAmount = $(topNode.offset().bottom - topNode.getBoundingClientRect().bottom;
}
$(window).scrollTop(scrollAmount);
The fiddle is acting a bit weird even in the same browsers, I've uploaded the same script using a free hosting here.
Still need to incorporate the IE, Opera and Safari fix for elementFromPoint.
Edit 3
Thanks for all the help, Rick Hitchcock. Welcome to stackoverflow, by the way :)
The discussion is turning into cross-browser compatibility issues so I've accepted your answer since we've pretty much got the answer to the original question. I'll still be fixing up my implementation though. The focus being cross-browser issues, topNode criteria, and topNode cut-off handling.
An edge case
While playing around with it, I noticed that when we were at the bottom of the page in a small viewport, then switch to a larger viewport (let us assume now that some more elements that were originally above the element we saw now came into view due to shorter container from wider viewport) the window cannot always lock the topNode to the top of the viewport in such a case since we've reached the scroll bottom. But then switching back to the small viewport now uses a new topNode that got into the viewport during the switch.
Although this should be expected from the behaviour being implemented, it is still a weird side-effect on scroll bottom.
I will also be looking into this in due course. Initially, I am thinking of simply adding a check for scroll bottom before we update topNode. I.e. to keep the old topNode when we've reached scroll bottom until we've scrolled up again. Not sure how this will turn out yet. I'll make sure to see how Opera handle this as well.
Here's what I've come up with:
(function(){
var topNode;
window.onscroll=function() {
var timer;
(function(){
clearTimeout(timer);
timer= setTimeout(
function() {
var testNode;
topNode= null;
for(var x = 0 ; x < document.body.offsetWidth ; x++) {
testNode= document.elementFromPoint(x,2);
if(!topNode || testNode.offsetTop>topNode.offsetTop) {
topNode = testNode;
}
}
},
100
)
}
)();
}
window.onresize=function() {
var timer;
(function(){
clearTimeout(timer);
if(topNode) {
timer= setTimeout(function(){topNode.scrollIntoView(true)},10);
}
}
)();
}
}
)();
If there were a window.onbeforeresize() function, this would be more straightforward.
Note that this doesn't take into account the scrolled position of the element's textNode. We could handle that if only the height of the window were resized. But resizing the width would generally cause reformatting.
This works in Chrome, Firefox, IE, and Safari.
Edit
How it works
The code's closures make variables private, and the timers prevent the code from running constantly during scrolling/resizing. But both tend to obfuscate the code, so here's another version, which may aid in understanding. Note that the onscroll timer is required in IE, because elementFromPoint returns null when it used in onscroll event.
var topNode;
window.onscroll=function() {
setTimeout(
function() {
var testNode;
topNode= null;
for(var x = 0 ; x < document.body.offsetWidth ; x++) {
testNode= document.elementFromPoint(x,2);
if(!topNode || testNode.offsetTop>topNode.offsetTop) {
topNode = testNode;
}
}
},
100
)
}
window.onresize=function() {
if(topNode) {
topNode.scrollIntoView(true)
}
}
topNode maintains the screen's top-most element as the window scrolls.
The function scans the screen left to right, along the 3rd row: document.elementFromPoint(x,2)*
It doesn't scan along the 1st row, because when IE does scrollIntoView, it pushes the element down a couple pixels, making the top-most screen element the previous element. (Figured this out through trial and error.)
When the window is resized, it simply positions topNode at the top of the screen.
[*Originally, onscroll scanned left to right along the 11th row (in pixels) until it found an element with just one child. The child would often be a textNode, but that wouldn't always be the case. Example:
<div><ul><li>...<li>...<li>...</ul></div>
The div has only one child – the ul. If the window were scrolled to the 50th li, scanning left to right would incorrectly return the div due to the inherent padding of lis.
The original code has been updated.
]

jQuery's $(selector).position().left Sometimes Fails in Firefox, Chrome Browsers

I have a content slideshow:
slide container
|--> wrapper
|------> slide1, slide2, etc.
that works as simple as calculating wrapper's position X and slide's position X to determine where to slide the wrapper for the next/previous slide to show up within container's viewport. It's pretty straight forward.
For Firefox and Chrome I am using CSS3 transform and transition-duration to animate the slides. Everything works perfect. Almost.
The problem is only when I click next button very fast. I am using jQuery's
$(selector).position().left
to read the slide's position X (left) and position becomes 0 (instead of expected, say, 300px). I do have a flag isAnimating to prevent users from going too fast but that does not help either. It does prevent from scrolling content too fast but position left may still be 0 as if something else is causing it to fail to determine.
I did a brief search and discovered that if it was image being loaded, some browsers would fail to determine its position until loading is over. However, each slide has an image but inside of it. The slide's CSS seems to have all widths and margins set fine.
The question is why may this be happening based on the scenario I described and possibly what can be improved to determine position X at all times for Firefox, Chrome browsers?
I've decided that if offsetLeft is not reliable for me at all times, I could use width of an element and its index position within container to figure out position X
var newWrapperPos = undefined;
$(lotWrapper).children('div').each(function(index){
if($(this).attr("id") === "slot"+id){
var width = $(this).width();
newWrapperPos = index * width;
return false;
}
});
//now I can shift wrapper to position = newWrapperPos
Sorry I couldn't share the code - it is a bit time consuming to rip off all pieces of functionality involved. But if somebody has a better answer, let me know. For now this works fine for me.

Draggable element in VML get stuck when size change (height, width) in IE 8

I'm having issue with VML (which I use as fallback for svg)
I use jQuery UI draggable to let user be able to move an element around. The problem occurs when I resize the image (which is a v:image) by changing the style attribute of height and width.
What happen at this point is that the element get stuck at the left top corner of it's container and cannot be dragged anymore.
A strange thing is that when I ask for the position (top, left) of the draggable element in the JavaScript console, I get value, and those values change when I click and drag - even though the element isn't visually moving...
Anyone run into this problem before?
Here's where I change then size of my element.
$($image)
.css({
'width' : zoomInPx_width + "px",
'height' : zoomInPx_height + "px"
});
The draggable is set pretty straight forward
$($image).draggable({
drag: function () { /*callback here*/ }
})
Finaly I manage to make this work.
Seems that VML crash on IE 8 when we change size of a draggable element. So, I had to destroy the element and recreate it from scratch when sliding occurs...
That's not really performant, but that's the only fix to work for me up here.
By the way, .detach() didn't work, you have to destroy it and recreate it from scratch.
You can get some info there too: http://www.acumen-corp.com/Blog/tabid/298/EntryId/26/Using-jqueryRotate-ui-draggable-and-resizable-images-in-IE7-IE8-and-any-other-browser.aspx
on my application I used this code:
var $cloned_image = $($image).clone().get(0);
$($image).remove();
// need add draggable again
$($cloned_image).draggable();
document.getElementById('k').appendChild($cloned_image);
$image = $cloned_image;

jQueryui animation with inital undefined height

See the following fiddle:
[edit: updated fiddle => http://jsfiddle.net/NYZf8/5/ ]
http://jsfiddle.net/NYZf8/1/ (view in different screen sizes, so that ideally the image fits inside the %-width layouted div)
The image should start the animation from the position where it correctly appears after the animation is done.
I don't understand why the first call to setMargin() sets a negative margin even though the logged height for container div and img are the very same ones, that after the jqueryui show() call set the image where I would want it (from the start on). My guess is that somehow the image height is 0/undefined after all, even though it logs fine :?
js:
console.log('img: ' + $('img').height());
console.log('div: ' + $('div').height());
$('img').show('blind', 1500, setMargin);
function setMargin() {
var marginTop =
( $('img').closest('div').height() - $('img').height() ) / 2;
console.log('marginTop: ' + marginTop);
$('img').css('marginTop', marginTop + 'px');
}
setMargin();
Interesting problem...after playing around with your code for a while (latest update), I saw that the blind animation was not actually firing in my browser (I'm testing on Chrome, and maybe it was firing but I wasn't seeing it as the image was never hidden in the first place), so I tried moving it inside the binded load function:
$('img').bind('load', function() {
...
$(this).show('blind', 500);
});
Now that it was animating, it seemed to 'snap' or 'jump' after the animation was complete, and also seemed to appear with an incorrect margin. This smacks of jQuery not being able to correctly calculate the dimensions of something that hadn't been displayed on the screen yet. On top of that, blind seems to need more explicit dimensions to operate correctly. So therein lies the problem: how to calculate elements' rendered dimensions before they've actually appeared on the screen?
One way to do this is to fade in the element whose dimensions you're trying to calculate very slightly - not enough to see yet - do some calculations, then hide it again and prep it for the appearance animation. You can achieve this with jQuery using the fadeTo function:
$('img').bind('load', function() {
$(this).fadeTo(0, 0.01, function() {
// do calculations...
}
}
You would need to work out dimensions, apply them with the css() function, blind the image in and then reset the image styles back to their original states, all thanks to a blind animation that needs these dimensions explicitly. I would also recommend using classes in the css to help you manage things a little better. Here's a detailed working example: jsfiddle working example
Not the most elegant way of doing things, but it's a start. There are a lot more easier ways to achieve seemingly better results, and I guess I just want to know why you're looking to do image blinds and explicit alignment this way? It's just a lot more challenging achieving it with the code you used...anyways, hope this helps! :)

Categories