jQuery animation affects content below (Chrome) - javascript

I've create an affect that runs when a row of icons are visible on screen.
The animation is essentially changing the padding of a div, giving the effect of a pulse from the icons.
It works perfectly in every browser except Chrome (surprisingly!). Chrome for some reason wobbles the text under each icon while it animates. I used padding in the hopes that it would only affect the content within the div (using the box-sizing: border-box model).
I did write a fix for it which works in Chrome but then breaks the layout in Safari.
So I'm not sure if I can fix the wobble in Chrome or if I can alter my fix to help Safari out.
Here's the link to the page as it is at the moment, without the jQuery fix. It's in the JS file but commented out.
Here's the code that runs the animation, the fix is in here, just commented out:
$('.wrapper').scroll(function(e) {
var tTop = target.offset().top;
var tTopOffset = tTop+target.height();
if( tTop < height ) {
if (flag) {
targetDiv.animate({
opacity: 1
}, 500);
targetDiv.each(function(i){
// FIX breaks on safari, but fixes issue in Chrome...
// targetDiv.css('height', targetDivHeight);
$(this).delay((i++) * 900).animate({
padding: '0em'
}, 400);
$(this).animate({
padding: '0.5em'
}, 400);
});
flag = false
}
} else {
targetDiv.css('opacity', '0');
flag = true;
}
});

I think it is because you didn't specified the width and height of the element you are trying to animate. border-box doesn't just ignore padding value, it needs width and height value that includes padding and border. Using transform:scale could be nice either as commented above, but IMHO it is a bit tricky to achieve with .animate() and has less browser support.
Try this in console and try modify your code. I tried and it works well in the latest Safari and Chrome. (should use .outerHeight() to get correct value, since you use padding value to animate)
$ = jQuery;
var targetDiv = $('.icon-img-div');
var targetDivHeight = $('.icon-img-div').outerHeight();
var targetDivWidth = $('.icon-img-div').outerWidth();
targetDiv.each(function (i) {
// this breaks on safari, but fixes issue in Chrome...
targetDiv.css({
height: targetDivHeight,
width: targetDivWidth
});
$(this).delay((i++) * 900).animate({
padding: '0em'
}, 400);
$(this).animate({
padding: '0.5em'
}, 400);
});

Related

Optimize scroll speed for Internet Explorer 11

I currently have an agenda-like application where the first column is absolute horizontal and the first row absolute vertical. I am achieving this by catching the scroll effect and change the left or top property of the CSS class it's attached to. ( these classes can be up to 700 items ( 2 years each day )).
$(window).scroll(function () {
$('.Planning tr > td:first-child').css("left", "" + $(this).scrollLeft() + "px");
$('.Planning thead > tr:first-child').css("top", $(this).scrollTop()+50 + "px");
});
This works as expected in all browsers (I tested in Chrome, Firefox and Internet Explorer)
But on Internet Explorer, it's very slow.
The scroll only shows after you stopped scrolling, whereas in Chrome and Firefox it looks like the top row is fixed, which looks better and more user friendly.
Is there any way to boost this? Or any libraries who are optimized for Internet Explorer so I can avoid this "slow" behaviour in IE?
https://jsfiddle.net/7mfcrLh5/12/ For a jsfiddle example ( this works great in chrome but not in internet explorer )
You could try to throttle the functionality of the scroll function every 100ms or 200ms which is still pretty fast each second.
var planningCol = $('.Planning tr > td:first-child'),
planningHead = $('.Planning thead > tr:first-child');
$(window).scroll(function(){
var self = this;
throttle(function(){
planningCol.css({ left: $(self).scrollLeft() });
planningHead.css('top', $(self).scrollTop() + 50 + 'px');
}(), 200); // call your function directly upon return
});
Or you can use CSS on the body, detecting when a page is scrolled or scrolling. Then apply .scrolling { pointer-events: none !important; } which boosts the UI.
Also try to move the selections out of the scroll function if they are always the same.
var win = $(window),
body = $(document.body),
planning = $('.Planning'),
planningCol = planning.find('tr > td').first(),
planningHead = planning.find('thead > tr').first();
win.scroll(function(){
// scrolled
body.toggleClass('scrolled', !!win.scrollTop());
// scrolling
body.addClass('scrolling');
planningCol.css({ left: win.scrollLeft() });
planningHead.css({ top: win.scrollTop() });
setTimeout(function(){
body.removeClass('scrolling');
}, 200);
});

Better way to get the viewport of a scrollable DIV in RTL mode?

I need a better way to calculate a scrollable div's viewport.
Under normal circumstances, I would use the following attributes: (scrollLeft, scrollTop, clientWidth, clientHeight)
Using these numbers I can accurately determine which part of a scrollable DOM element's viewport is currently visible, I use this information to asynchronously load things that are visible to the user on demand when scrolling to the content horizontally or vertically. When the content of the DIV is massive, this will avoid an embarassing browser crashing bug because of too many DOM elements being loaded.
My component has worked for a while now with no issues, this build we are introducing RTL support. Now everything is thrown off because of browser inconsistencies.
To demonstrate, I have created a simple example which will output the scrollLeft attribute of a scrollable element in a JSFiddle.
The behavior of the scrollLeft attribute on this simple scrollable element is not consistent from one browser to the next. The 3 major browsers I've tried all behaved differently.
FF-latest scrollLeft starts at 0 and goes negative when scrolling left
IE 9 scrollLeft starts at 0 and goes positive when scrolling left
Chrome-latest scrollLeft starts at a higher number and goes to 0 when scrolling left
I want to avoid having code like if(ie){...}else if(ff){...}else if (chrome){...} that would be horrible, and not maintainable in the long run in case browsers change behavior.
Is there a better way to figure out precisely which part of the DIV is currently visible?
Perhaps there is some other reliable DOM attribute other than scrollLeft?
Maybe there is a jQuery plugin that will do it for me, keeping in mind which browser version it is?
Maybe there is a technique I can use to figure out which of the cases it is at runtime without relying on some unreliable browser detection (i.e. userAgent)
Fiddle Example (code copied below)
HTML
<div id="box"><div id="content">scroll me</div></div>
<div id="output">Scroll Left: <span id="scrollLeft"></span></div>
CSS
#box {
width: 100px; height: 100px;
overflow: auto;
direction: rtl;
}
#content { width: 300px; height: 300px; }
JS
function updateScroll() {
$('#scrollLeft').text(box.scrollLeft());
}
var box = $('#box').scroll(updateScroll);
updateScroll();
Here's a jQuery plugin which does not use browser detection: https://github.com/othree/jquery.rtl-scroll-type
Using this plugin you could replace jQuery's scrollLeft function with your own predictable version, like this:
var origScrollLeft = jQuery.fn.scrollLeft;
jQuery.fn.scrollLeft = function(i) {
var value = origScrollLeft.apply(this, arguments);
if (i === undefined) {
switch(jQuery.support.rtlScrollType) {
case "negative":
return value + this[0].scrollWidth - this[0].clientWidth;
case "reverse":
return this[0].scrollWidth - value - this[0].clientWidth;
}
}
return value;
};
I didn't include the code for setting the scroll offset, but you get the idea.
Here's the fiddle: http://jsfiddle.net/scA63/
Also, this lib may be of interest too.
You can try this:-
var initialScrollLeft = $('#box').scrollLeft(), negativeToZero, startFromZero;
if(initialScrollLeft === 0){
startFromZero = true;
} else if(initialScrollLeft < 0){
negativeToZero = true;
}
var box = $('#box').scroll(function(){
if(startFromZero){
if(box.scrollLeft()>0){
$('#scrollLeft').text(- (box.scrollLeft()));
}else {
$('#scrollLeft').text(box.scrollLeft());
}
} else if(negativeToZero){
$('#scrollLeft').text(box.scrollLeft()+(box[0].scrollWidth - box[0].clientWidth));
} else{
$('#scrollLeft').text(box.scrollLeft()-(box[0].scrollWidth - box[0].clientWidth));
}
});
Problem: (Ex. Scroll Width = 100)
Chrome - Most Right: 100 Most Left: 0.
IE- Most Right: 0 Most Left: 100.
Firefox - Most Right: 0 Most Left: -100.
Solution #1
As mentioned by #Lucas Trzesniewski.
You could use this Jquery plugin:
https://github.com/othree/jquery.rtl-scroll-type
The plugin is used to detect which type is the browser are using.
Assign the result to jQuery's support object named 'rtlScrollType'.
You will need the scrollWidth of the element to transform between
these three types of value
Solution #2
Credits: jQuery.scrollLeft() when direction is rtl - different values in different browsers
I know you didn't want to include browser detection individually for each browser. With this example, only 2 extra lines of code are added for Safari and Chrome and it works like a charm!
Modified it to demonstrate it better for you.
$('div.Container').scroll(function () {
st = $("div.Container").scrollLeft() + ' ' + GetScrollLeft($("div.Container"));
$('#scrollLeft').html(st);
});
function GetScrollLeft(elem) {
var scrollLeft = elem.scrollLeft();
if ($("body").css("direction").toLowerCase() == "rtl") {
// Absolute value - gets IE and FF to return the same values
var scrollLeft = Math.abs(scrollLeft);
// Get Chrome and Safari to return the same value as well
if ($.browser.webkit) {
scrollLeft = elem[0].scrollWidth - elem[0].clientWidth - scrollLeft;
}
}
return scrollLeft;
}
JSFiddle:
http://jsfiddle.net/SSZRd/1/
The value on the left should be the same for all browser while the value on the right is the older value which is different on all browser. (Tested on Firefox, Safari, Chrome, IE9).
1. FF-latest scrollLeft starts at 0 and goes negative when scrolling left
2. IE 9 scrollLeft starts at 0 and goes positive when scrolling left
3. Chrome-latest scrollLeft starts at a higher number and goes to when scrolling left
I want to avoid having code like if(ie){...}else if(ff){...}else if(chrome){...}
that would be horrible, and not maintainable in the long run in case browsers change behavior
FYI:
Chrome 85 (final shipping Aug. 2020) fixed this bug and aligns behaviour with Firefox and Safari and the spec.
See https://www.chromestatus.com/feature/5759578031521792
Is there a feature detection available for this?
Yes, e.g. use one of two scrips (from Frédéric Wang) available here:
https://people.igalia.com/fwang/scrollable-elements-in-non-default-writing-modes/
either this
function scroll_coordinates_behavior_with_scrollIntoView() {
/* Append a RTL scrollable 1px square containing two 1px-wide descendants on
the same line, reveal each of them successively and compare their
scrollLeft coordinates. The scrollable square has 'position: fixed' so
that scrollIntoView() calls don't scroll the viewport. */
document.body.insertAdjacentHTML("beforeend", "<div style='direction: rtl;\
position: fixed; left: 0; top: 0; overflow: hidden; width: 1px; height: 1px;'>\
<div style='width: 2px; height: 1px;'><div style='display: inline-block;\
width: 1px;'></div><div style='display: inline-block; width: 1px;'></div>\
3</div></div>");
var scroller = document.body.lastElementChild;
scroller.firstElementChild.children[0].scrollIntoView();
var right = scroller.scrollLeft;
scroller.firstElementChild.children[1].scrollIntoView();
var left = scroller.scrollLeft;
/* Per the CSSOM specification, the standard behavior is:
- decreasing coordinates when scrolling leftward.
- nonpositive coordinates for scroller with leftward overflow. */
var result = { "decreasing": left < right, "nonpositive": left < 0 };
document.body.removeChild(scroller);
return result;
}
or that
function scroll_coordinates_behavior_by_setting_nonpositive_scrollLeft() {
/* Append a RTL scrollable 1px square containing a 2px-wide child and check
the initial scrollLeft and whether it's possible to set a negative one.*/
document.body.insertAdjacentHTML("beforeend", "<div style='direction: rtl;\
position: absolute; left: 0; top: 0; overflow: hidden; width: 1px;\
height: 1px;'><div style='width: 2px; height: 1px;'></div></div>");
var scroller = document.body.lastElementChild;
var initially_positive = scroller.scrollLeft > 0;
scroller.scrollLeft = -1;
var has_negative = scroller.scrollLeft < 0;
/* Per the CSSOM specification, the standard behavio999r is:
- decreasing coordinates when scrolling leftward.
- nonpositive coordinates for scroller with leftward overflow. */
var result = { "decreasing": has_negative ||
initially_positive, "nonpositive": has_negative };
document.body.removeChild(scroller);
return result;
}

How to implement jquery like slideDown() in zepto

I am using zepto library for my mobile web site. I have recently learnt that zepto does not have slideDown() plugin like jquery. I would like to implement the same for zepto.
I have tried one on jsfiddle (http://jsfiddle.net/goje87/keHMp/1/). Here it does not animate while showing the element. It just flashes down. How do I bring in the animation?
PS: I cannot provide a fixed height because I would be applying this plugin to the elements whose height property would not be known.
Thanks in advace!!
Demo: http://jsfiddle.net/6zkSX/5
JavaScript:
(function ($) {
$.fn.slideDown = function (duration) {
// get old position to restore it then
var position = this.css('position');
// show element if it is hidden (it is needed if display is none)
this.show();
// place it so it displays as usually but hidden
this.css({
position: 'absolute',
visibility: 'hidden'
});
// get naturally height
var height = this.height();
// set initial css for animation
this.css({
position: position,
visibility: 'visible',
overflow: 'hidden',
height: 0
});
// animate to gotten height
this.animate({
height: height
}, duration);
};
})(Zepto);
$(function () {
$('.slide-trigger').on('click', function () {
$('.slide').slideDown(2000);
});
});​
​
This worked for me:
https://github.com/Ilycite/zepto-slide-transition
The Zepto Slide Transition plugin add to Zepto.js the functions bellow :
slideDown();
slideUp();
slideToggle();
Speransky's answer was helpful, and I'm offering a simplified alternative for a common drop-down navigation list, and separated into slideUp and slideDown on jsfiddle: http://jsfiddle.net/kUG3U/1/
$.fn.slideDown = function (duration) {
// show element if it is hidden (it is needed if display is none)
this.show();
// get naturally height
var height = this.height();
// set initial css for animation
this.css({
height: 0
});
// animate to gotten height
this.animate({
height: height
}, duration);
};
This would work for what you need:
https://github.com/NinjaBCN/zepto-slide-transition

(jQuery plugin: backstretch) Margin on the sides

I am using this great jQuery plugin to have the fullscreen backgound for my website.
This plugin currently fills the entire background on the screen, I was wondering if it is possible to give it a margin.
For instance I want to have a gap in the right side of the screen for 150px (so I can see the body background) and the rest of the page will be filled with backstretch.
I have played with _adjustBG function but I can't get this working.
Any helps will be appreciated.
Since the author of this plugin didn't make an option for margin, I'll tweak it for you.
Below is the modified _adjustBG() function that you may need.
Just open the file "jquery.backstretch.js" (the normal version, not the minimized) then replace the original _adjustBG() function (at the end of file) with this function.
function _adjustBG(fn) {
var rightMargin = 150; //--- edit the margin value here
try {
bgCSS = {left: 0, top: 0}
bgWidth = rootElement.width()-rightMargin;
bgHeight = bgWidth / imgRatio;
// Make adjustments based on image ratio
// Note: Offset code provided by Peter Baker (http://ptrbkr.com/). Thanks, Peter!
if(bgHeight >= rootElement.height()) {
bgOffset = (bgHeight - rootElement.height()) /2;
if(settings.centeredY) $.extend(bgCSS, {top: "-" + bgOffset + "px"});
} else {
bgHeight = rootElement.height();
bgWidth = bgHeight * imgRatio-rightMargin;
bgOffset = (bgWidth - rootElement.width()) / 2;
if(settings.centeredX) $.extend(bgCSS, {left: "-" + bgOffset + "px"});
}
$("#backstretch, #backstretch img:last").width( bgWidth ).height( bgHeight )
.filter("img").css(bgCSS);
} catch(err) {
// IE7 seems to trigger _adjustBG before the image is loaded.
// This try/catch block is a hack to let it fail gracefully.
}
// Executed the passed in function, if necessary
if (typeof fn == "function") fn();
}
Update:
By poking around w/ console, I found that if you subtract 150 from the width of the background-image, it will, by default, give you a margin on the right. You may want to adjust the height so your image scales, but, maybe something like this to run in $(document).ready():
var $bg = $('#backstretch');
var newImgWidth = $bg.width() - 150;
$bg.css('width', newImgWidth);
If IE6 is no issue, you can try to put the following in your stylesheet:
#backstretch{
width: auto !important;
right: 150px;
}
I tried this on the backstretch homepage and it worked as I would expect. As I am not totally familiar with this plugin please feel free to correct me.

jquery - get position problem in Firefox

I have the following code which gets the left and top position of the element you are hovered over. It produces the right results in safari and IE but fails to get the position of the img that you hover over in Firefox - it returns 0, 0. Can anyone see why this might be??
I think it might be something to do with setting it as the variable as it seems to work if I place it straight in the function. I need to set it as a variable though so it can return to its original state.
$.fn.hoverAnimationTwo = function () {
return $(this).each(function () {
var originalLeftTwo = parseInt($(this).css("left"));
var originalTopTwo = parseInt($(this).css("top"));
return $(this).hover(function () {
$(this).animate({
width: "17px",
height: "17px",
left: originalLeftTwo - 5,
top: originalTopTwo - 5
}, 100);
},function () {
$(this).animate({
width: "7px",
height: "7px",
left: originalLeftTwo,
top: originalTopTwo
}, 100);
});
});
}
$(".myImg").hoverAnimationTwo();
The other thing which is very odd is that I can copy all of my code into jsfiddle and it seems to work.
EDIT:
OK... so it turns out this isn't a javascript issue as such. It is because elsewhere in the page I had given an element a class beginning with a numeric character which is entirely my bad and I should know better!
Browsers seem to have some inconsistencies when relying on CSS properties. Have you tried using .position() or .offset() (whichever is applicable to your needs)?
http://api.jquery.com/offset/ or http://api.jquery.com/position/

Categories