I'm currently using ScrollReveal.js to make a bunch of tiny pixelated boxes do random things when scrolled upon, with the following code:
var index=0;
$(document).ready(function(){
jQuery('.pixel-box').each(function() { //each tiny box has class pixel-box
var directions =[ 'left', 'right', 'top', 'bottom']
index += 1
var currentElement = $(this);
var randEffect = getRandomInt(0,1);
var randTime = getRandomArbitrary(1, 3.5);
var randDirection = getRandomInt(0,3);
if(randEffect == 0){
var rand = getRandomInt(-360, 360);
$(this).attr('data-sr', 'wait .5s, enter ' + directions[randDirection] + ', flip ' + rand + 'deg, over '+ randTime +'s');
}
else if(randEffect == 1){
// move 24px
var rand = getRandomInt(10, 120);
$(this).attr('data-sr', 'wait .5s, enter ' + directions[randDirection] +', move '+ rand + 'px, over '+ randTime +'s');
}
if(index == 81){
window.sr = new scrollReveal();
}
});
});
It's working perfectly on Chrome, but on Safari, the behavior is extremely clunky and not what I want. Would you or anyone else have any insights as to why this is happening?
To illustrate, here's what it looks like on Chrome:
https://gyazo.com/4f51ff8279cf5a76ad3ab38a680ae2af
Here's what it looks like on Safari:
https://gyazo.com/8c30e489a2470ac415da3dde1d95d4ef
For reference, one of these boxes is being rendered using the HTML code:
<rect class="pixel-box" id="Rectangle-167-Copy-7" fill="#FDD93D" filter="url(#filter-35)" x="823.65422" y="188.994877" width="16.675" height="19.0983607"></rect>
I suspect that the problem may be due to inconsistencies with CSS transformations and SVG elements like <rect> and <path> across different browsers, but I haven't been coming up with much.
Looks like a browser issue with Safari animating opacity and transforms at the same time.
...we came across a particularly frustrating bug in Safari involving
animation of SVG elements using CSS3 transforms and opacity
simultaneously.
Safari will not animate both attributes at the same time, instead
choosing to animate the opacity with the correct timings and when that
animation is complete the transform jumps to its correct position, or
the translation is just ignored completely.
Reference: https://www.theparticlelab.com/safari-svg-animation-bug/
Looks like others have had similar problems in the past, but the browser bug appears fixed.
Related
EDIT : Added jsfiddle
(for) https://jsfiddle.net/x60bwgw7/4/
(each) https://jsfiddle.net/v3y2v8cf/3/
open in IE, output values of 30 are wrong (IE placeholder height)
I tried to return DOM naturalHeight and clientHeight, and while naturalHeight works properly in IE, clientHeight (the one I need) does not.
Here's an obvious workaround, but it kinda sucks https://jsfiddle.net/0rhjt0wn/1/
Seems like the problem is that IE renders image after it is loaded, while other browsers render it while it is being loaded, but Im just guessing here.
I've some images, that I want to load by assigning their "data-src" attribute value to theirs "src" attribute and vertically center them after.
It works without a problem in all browsers except IE (tested from 8 to edge).
In IE some images get centered without a problem, but some wont and it is because code in the .on("load") event gets executed (probably) after the image is loaded, but before it gets its size set.
Is there any way to always execute the code after the image is loaded and its size is set (in IE)?
for (i = 0; i < 100; i++)
{
targetSrc = $divElement.eq(i).children(imgClass).attr(dataSrc) + "?v=" + datetime;
$divElement.eq(i).find(imgClass).attr("src", targetSrc).on("load", function()
{
$holder.append($(this).attr("src") + " || height = " + $(this).height() + "<br>");
});
}
Initially thought requestAnimationFrame and a timeout fallback could easily solve this but it turned out to be a lot more complicated. Apparently the exact frame at which an image is rendered after onload is not very predictable in IE. But I eventually came up with this solution that checks the naturalHeight against the current height to see if an image has been rendered, looping through to the next display frame when it is not the case yet :
https://jsfiddle.net/r8m81ajk/
$(function() {
if (window.requestAnimationFrame) var modern = true;
var element = $('.divElement'),
reference = '.imgElement',
holder = $('.holder'),
datetime = Date.now(),
path, image;
for (var i = 0; i < 100; i++) {
var target = element.eq(i).children(reference),
path = target.data('src') + '?v=' + datetime;
target.one('load', function() {
image = this;
if (modern) requestAnimationFrame(function() {
nextFrame(image);
});
else setTimeout(renderImage, 50);
}).attr('src', path);
}
function nextFrame(picture) {
var dimension = $(picture).height();
if (dimension == picture.naturalHeight) {
holder.append('height = ' + dimension + '<br>');
}
else nextFrame(picture);
}
function renderImage() {
holder.append('height = ' + $(image).height() + '<br>');
}
});
The fallback will always check on the third frame (when there's no bottleneck). Don't mind I adapted the code a bit to my usual conventions, the external references should have remained the same.
From the question I realise the loop might not even be needed and getting naturalHeight when the image loads would be enough. Interesting exercise to detect the exact point of rendering in any case.
I'm currently using the following javascript as shown below.
It's working well when I place just text within the div .image_scroll_3 but as soon as I insert images the scroll glitches and won't move past the top of the image.
Any advice would be much appreciated
JS
<script>
(function($, undefined) {
$.fn.loopScroll = function(p_options) {
var options = $.extend({
direction: "upwards",
speed: 60
}, p_options);
return this.each(function() {
var obj = $(this).find(".image_scroll_2");
var text_height = obj.find(".image_scroll_3").height();
var start_y, end_y;
if (options.direction == "downwards") {
start_y = -text_height;
end_y = 0;
} else if (options.direction == "upwards") {
start_y = 0;
end_y = -text_height;
}
var animate = function() {
// setup animation of specified block "obj"
// calculate distance of animation
var distance = Math.abs(end_y - parseInt(obj.css("top")));
//alert("animate " + obj.css("top") + "-> " + end_y + " " + distance);
//duration will be distance / speed
obj.animate(
{ top: end_y }, //scroll upwards
1500 * distance / options.speed,
"linear",
function() {
// scroll to start position
obj.css("top", start_y);
animate();
}
);
};
obj.find(".image_scroll_3").clone().appendTo(obj);
$(this).on("mouseout", function() {
obj.stop();
}).on("mouseout", function() {
animate(); // resume animation
});
obj.css("top", start_y);
animate(); // start animation
});
};
}(jQuery));
$("#example4").loopScroll({ speed: 700 });
</script>
I think the problem is that your text_height is calculated before the images are actually loaded inside your .image_scroll_3 elements. So you'll need to wait for the images to load.
Put your loopScroll call inside a $(window).load like so:
$(window).load(function(){
$('#example4').loopScroll({speed:700});
});
That massive glitch should now be gone as the fix above should have helped mitigate it.
However, there is still some unwanted jank / stutter (don't want to use the word glitch again, lets keep it reserved for the initial problem) in movement of all images if you notice and I am guessing that is probably because we are animating the whole thing too fast. Passing in speed like 100 or 200 resolves that but this is not really a solution because, ideally, you should be able to put in any speed value and it should just produce smooth animations out of it.
I am working on exactly the same thing but before that, I want to know if the above fix for the glitch helps you and we are finally done with it? Let me know.
Update:
Here is my version that I spoke of earlier, for your perusal.
Because all you are trying to do is loop images in a very linear fashion, I, for one, do not see the need to rely on animate() function of jQuery. There is requestAnimationFrame API that I have leveraged instead. In fact, in my demonstration below I have completely abandoned jQuery in favour of vanilla JavaScript only because I kept finding alternatives to pretty much everything we needed to do in this demo. But of course, this is also a very subjective matter; a taste thing; so if you want to go with jQuery, then by all means.
Another fundamental change I brought is rather than updating top values, I have resorted to updating translateY values.
Take a look at this jsFiddle and let me know if it fits your needs.
JavaScript code of which is as belows:
// [http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/]
window.requestAnimFrame=(function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(callback){window.setTimeout(callback,1000/60);};})();
var main=null;
var imageScroll2=null;
var imageScroll3=null;
var totalHeight=null;
var initY=null;
var destY=null;
var currY=null;
var increment=null;
var direction=null;
var UP=null;
var DOWN=null;
var isPlaying=null;
function init(){
main=document.getElementById('example4');
imageScroll2=main.getElementsByClassName('image_scroll_2')[0];
imageScroll3=main.getElementsByClassName('image_scroll_3')[0];
totalHeight=imageScroll3.clientHeight;
UP='upwards';
DOWN='downwards';
isPlaying=true;
direction=UP;
increment=10;
if(direction===DOWN){
initY= -totalHeight;
destY=0;
}else{
initY=0;
destY= -totalHeight;
}
currY=initY;
imageScroll2.appendChild(imageScroll3.cloneNode(true));
if(imageScroll2.addEventListener){
imageScroll2.addEventListener('mouseover',function(){isPlaying=false;},false);
imageScroll2.addEventListener('mouseout',function(){isPlaying=true;},false);
}else{
imageScroll2.attachEvent('onmouseover',function(){isPlaying=false;});
imageScroll2.attachEvent('onmouseout',function(){isPlaying=true;});
}
requestAnimFrame(render);
}
function render(){
if(isPlaying){
imageScroll2.style.transform='translate(0px,'+currY+'px)';
if(direction===DOWN){
currY+=increment;
if(currY>=destY){currY=initY;}
}else{
currY-=increment;
if(currY<=destY){currY=initY;}
}
}
requestAnimFrame(render);
}
//
init();
I am trying to write a javascript app which sorts dynamically created divs on a webpage, everything works and it sorts it all as it should, however I want it to animate the divs as they change position due to being sorted, I have code to do this but it moves way too fast, the only way I can see the divs move is if I put an alert in the animation code which looks like this :
function moveAnimation(to,from){
mover1.style.backgroundColor = "rgba(255,100,175,0.8)";
mover2.style.backgroundColor = "rgba(255,100,175,0.8)";
mover1.style.top = parseInt(mover1.style.top) + 10 + 'px';
mover2.style.top = parseInt(mover2.style.top) - 10 + 'px';
from = parseInt(mover1.style.top);
if(from != to && from < to)
{
//alert("TO : " + to + " From : " + from); //This makes it pause so that I can see the divs move
animate = setTimeout(moveAnimation(to,from),1000)
}
else
{
//alert("RET");
return;
}
}
And i call it simply like this :
mover1 = document.getElementById(moving1.id);
mover2 = document.getElementById(moving2.id);
var from = parseInt(in1.style.top);
var to = parseInt(in2.style.top);
moveAnimation(to,from);
When the alert is in place I can see them move frame by frame and it's doing exactly what I want, however it all happens in the blink of an eye with the divs suddenly being sorted, I would like to see them slowly move, any ideas on why my code isn't doing that?
I am writing a script to allow a client to mouse drag table cell borders and resize columns in a table. So far I have a working model in Firefox but there is a flaw in width measurement that leaves the mouse out of sync when the change gets large. Worse, the script fails in other browsers (opera,safari) or even if I change the browser zoom in Firefox.
function doDrag() {document.body.style.cursor='crosshair';}
function noDrag() {document.body.style.cursor='auto';}
var xpos=0;
var sz=0;
var dragObj = {};
function resizeOn(el)
{
dragObj = document.getElementById(el);
document.addEventListener("mousemove",resize, true);
document.addEventListener("mouseup",resizeOff, true);
}
function resize(ev)
{
if(xpos == 0) {xpos=ev.clientX;}
if(xpos != ev.clientX)
{
sz = dragObj.offsetWidth + (ev.clientX - xpos);
dragObj.style.width = sz - 10 + "px";
alert("size="+sz+" offsetwidth="+dragObj.offsetWidth);
if(dragObj.offsetWidth != sz)
{
resizeOff();
return false;
}
xpos=ev.clientX;
}
}
function resizeOff()
{
xpos = 0;
document.removeEventListener("mousemove",resize, true);
document.removeEventListener("mouseup",resizeOff, true);
}
The HTML looks like:
<th id="col0" class="edit">client</th>
<th class="drag" onmouseover="doDrag()" onmouseout="noDrag()" onmousedown="resizeOn('col0')"></th>
The second cell is made to appear as the right edge of the first.
I assume the problem is dragObj.style.width = sz - 10. The -10 was derived purely by trial and error. I suspect this is the difference between the actual width of the cell including borders, padding etc and offsetwidth. It should really be, per my css, 10 for padding + 1 for the left border = 11px. Either my fixed padding/borders aren't staying fixed or there is some other css property between the offsetWidth and the actual with of the element. Is there some way to get the actual width of the element regardless of the browsers scaling?
Have a look at the documentation in www.quirksmode.org and/or http://help.dottoro.com. Confirm whether the properties are supported by your target browser. They also have comments on how zoom affects offsetX and similar.
Also, you should note that ev.clientX has been broken in IE by a recent patch (KB2846071). If the patch is installed, clientX returns a meaningless result.
Hopefully MS will release a patch for their patch!
PLEASE DO NOT RECOMMEND JQUERY - I AM DOING THIS EXERCISE FOR LEARNING PURPOSES.
I have implemented a JavaScript, which rotates images (_elementSlideChange) on a timer, using a set interval of 10 seconds. Also I have added a slide functionality to this, which is 7 milliseconds (_slideImage).
The image rotates automatically every 10 seconds on page load, and I have also provided next and previous buttons, which allow the user to change the images manually.
_elementSlideChange: function () {
var myString;
var myText;
for (var i = 0; i < this._imgArray.length; i++) {
var imageArr = "url(" + this._imgArray[i].src + ")";
var imageBg = this._imageHolder.style.background + "";
if (imageArr == imageBg) {
if (i == (this._imgArray.length - 1)) {
myString = "url(" + this._imgArray[0].src + ")";
myText = this._infoArray[0];
} else {
myString = "url(" + this._imgArray[(i + 1)].src + ")";
myText = this._infoArray[i + 1];
}
}
}
this._imageNextSlide.style.background = myString;
this._imageNextSlide.style.background);
this._infoElement.innerHTML = myText;
this._myTimer = setInterval(MyProject.Utils.createDelegate(this._slideImage, this), 7);
},
_slideImage: function () {
if (parseInt(this._imageHolder.style.width) >= 0 && parseInt(this._imageNextSlide.style.width) <= 450) {
this._imageHolder.style.backgroundPosition = "right";
this._imageHolder.style.width = (parseInt(this._imageHolder.style.width) - 1) + 'px';
console.log(this._imageNextSlide.style.background);
this._imageNextSlide.style.width = (parseInt(this._imageNextSlide.style.width) + 1) + 'px';
} else {
console.log("reached 0px");
if (parseInt(this._imageHolder.style.width) == 0) {
this._imageHolder.style.background = this._imageNextSlide.style.background;
this._imageHolder.style.width = 450 + 'px';
this._imageHolder === this._imageNextSlide;
this._imageHolder.className = "orginalImage";
this._imageNextSlide.style.width = 0 + "px";
this._imageNextSlide = this._dummyImageNextSlide;
this._imagesElement.appendChild(this._imageHolder);
this._imagesElement.appendChild(this._imageNextSlide);
clearInterval(this._myTimer);
}
clearInterval(this._myTimer);
clearInterval(this._elementSlideChange);
}
}
So when the user clicks on the Next arrow button, the event listener for "click" is triggered. This creates a div for the current image on display, and creates a new div, which will contain the next image. The image slide and rotation works correctly (whether it's onLoad or onClick). The issue I have is if I click the Next button, while the new div image is sliding into position, it causes it to run into an infinite loop, so the same div with the image to be displayed keeps sliding in, and the more you click the Next button, the faster the image starts to rotate.
I have tried putting a clear interval for the image rotation and slider, but I do understand my code is wrong, which causes the infinite loop of the sliding image. And I know I am close to finishing the functionality.
Can anyone please advise where I could be going wrong? Or should I try to implement the sliding DIV in another way?
Once again please don't recommend jQuery.
And thank you for your help in advance.
Kush
To solve the issue, I did re-write the entire code, where I had a next and previous button event listener.
myProject.Utils.addHandler(this._nextImageElement, "click", myProject.Utils.createDelegate(this._changeImage, this));
Both the buttons will call the same function :
_changeImage: function (e)
In this function I check to see if the function is Transition (changing images),
I declare a boolean var forward = e.target == this._nextImageElement;
Then check to see the current index if forward ? Add 1 else minus 1
this._currentImageIndex += forward ? 1 : -1;
If its at the end of the Array and forward is true, assign the this._currentImageIndex to reset to 0 or Array.length – 1 if it’s in reverse
Then call another function which gives the ‘div’ a sliding effect. In this case call it this._transitionImage(forward);
In this function, set the this._inTranstion to true. (Because the div’s are sliding in this case).
The following code solved the issue i was having.
this._slideImageElement.style.backgroundImage = "url(\"" + this._imgArray[this._currentImageIndex].src + "\")";
this._slideImageElement.style.backgroundPosition = forward ? "left" : "right";
this._slideImageElement.style.left = forward ? "auto" : "0px";
this._slideImageElement.style.right = forward ? "0px" : "auto";
The above code is very important as the object is to place the “sliding in div” Left or Right of the current Visible “div” to the user, and this is mainly dependent on if the forward variable is true or false.
var i = 0;
Then start the transition by
setInterval( function() {
this._currentImageElement.style.backgroundPosition = (forward ? -1 : 1) * (i + 1) + "px";
this._slideImageElement.style.width = (i + 1) + "px";
Notice the forward will determine if the bgPosition will go to the left if its forward as we multiple by -1 or +1,
So for example
If the user clicks NEXT BUTTON,
Forward = true
So the first thing we do is set the
this._slideImageElement.style.backgroundPosition = "left"
Then
this._slideImageElement.style.left = "auto"
this._slideImageElement.style.right = "0px"
This means when the sliding image moves in its background position is LEFT but the div is placed on the RIGHT to 0px;
then this._currentImageElement.style.backgroundPosition = -1 * (i + 1)
Which moves the position of the currentImageElement to the left by 1px,
Increase the width of the slideImage which in this case is right of the current div,
and as the current div moves to the left the sliding image starts to appear from the right. (By default set the width of slideImageElement to 0px so the div exists but isn’t visible to the user). This gives it the slide effect of moving forward new image coming from the right.
this._slideImageElement.style.width = (i + 1) + "px";
then declare it to stop when it it’s the image width. In this case it will be 500px.
if ((i = i + 2) == 500) {
In this if statement reset the currentImageElement background and the background position “right” or “left” don’t really matter as long it has been reset.
Clear the interval
Set the transition to false again
Then call a setTimeout for the function changeImage, which will continue until the slide is completed.
The following shows the reset code as this is very important to prevent repeating the same image (This solved my entire issue)
// set the current image to the "new" current image and reset it's background position
this._currentImageElement.style.backgroundImage = "url(\"" + this._imgArray[this._currentImageIndex].src + "\")";
this._currentImageElement.style.backgroundPosition = "right";
// reset the slide image width
this._slideImageElement.style.width = "0px";
// clear the transition interval and mark as not in transition
clearInterval(this._transitionInterval);
this._inTransition = false;
// setup the next image timer
this._nextImageTimeout = setTimeout(myProject.Utils.createDelegate(this._changeImage, this), 2500);
}
I have provided a thorough detail because then it easier to understand the logic of the problem, and even if your not having the same issue, this may help you fingure out any problem.
I couldn't provide a JSfiddle, as i have created my CSS using Javascript, there are different ways of doing this, but i wanted to understand the logic behind the forward and reverse, and having a timer which continuously goes forward.
It seems like you want to cancel the animation on the slide (perhaps have it fade out while the next slide animates in, cancel its animation abruptly or let it finish and ignore the button click)
What I usually do, personally, is check for the animated state (yes, I use jquery, but you should be able to test the CSS or positioning values you are using to animate in the same way) you could even add an "active" class or data type during animation to make testing easier. Global flags work, too. If there is animation, ignore the button. (For my work... Depends on your intention)
Like I said, the problem may be with button behaviour not with the animation routine. It would be useful to see how you are calling this from the button click, and what your intended results are going to be.
How about CSS3 transitions?
transition: all 1s ease 0.5s;
Simple example on JS Fiddle.
This takes care of the animation, so you just need to set the intended destination using JavaScript, i.e.
this.style.left = '100px';
Or
this.style.top = '30px';
And CSS3 transitions will smoothly slide the element.
Cross Browser Note!
The transition property may need a vendor prefix for some browsers, I am using the latest production Firefox and you don't need -moz for that. Same goes for Opera, no '-o' required. Internet Exporer 10 needs no prefix. You may need to use -webkit for Safari / Chrome, but test without first.