Any way other than setTimeout to force a browser repaint? - javascript

I'm using (and contributing to) a jQuery table sorting plugin that includes an event for extra processing before the table is sorted. Originally the browser didn't do a repaint before sorting, so I added a setTimeout call to the plugin code that should force a repaint. So the code is now like this:
$table.trigger("beforetablesort", {column: th_index, direction: sort_dir});
setTimeout(function() {
// do the hard work
}, 10);
My beforetablesort callback is like this:
table.bind('beforetablesort', function (event, data) {
$("table").css({opacity: 0.5});
});
The above all works fine. However, if I use addClass instead of inline styles, the changes from that class do not show until the table is fully sorted:
table.bind('beforetablesort', function (event, data) {
$("table").addClass('disabled');
});
If I increase the timeout to over 500ms, the opacity does change. It seems like it takes a tiny bit longer for a class change to be visible as opposed to an inline style change. But by the time the browser is ready to repaint it's already doing the table sorting.
Is there a way to force the repaint earlier? Or wait until the repaint for the table sorting code to run? Increasing the timeout arbitrarily doesn't seem like a good solution as it forces all tables to take at least half a second to sort. (Full code of the plugin is here on Github if it helps.)

Maybe you have already considered using $.deferred() http://api.jquery.com/jQuery.Deferred/.
The code in timeout should go in the callback handler when deferred object is resolved

The comment by Jan Dvorak above works.
Reading some computed property will wait for reflow. Hopefully it will ensure a repaint as well.
I just added the line $table.css("display"); and the browser repaints the table before the sorting starts.

Related

Event Listener when a browser finishes updating the DOM

There is a huge HTML table and JS code that sorts it.
I want to show some loading icon or an overlay when the sorting code is executed.
All works fine, but there is a time gap between end of code and the actual appearance of the updated table.
My guess it that it takes some time until the browser finishes redrawing the page.
I have tried using Observer, but it fires only after the DOM modification, there is still a delay before I can see the actual updated table.
Is there any JS event that happens after the browser finishes drawing the page?
You can use the trigger to fire off events at the start and end of your processing.
If you're using jQuery it would look something like this:
function processTable(){
$(document).trigger('startProcessing', {
description: 'Enable Loader'
});
... //Processing done here
$(document).trigger('endProcessing', {
description: 'Disable Loader'
});
}
jQuery(document).on('startProcessing',enableLoaderFunction);
jQuery(document).on('endProcessing',disableLoaderFunction);
This can also be done in just JS by making sure that you use the proper event handler for the browser that is being used.
Here is the documentation for handling without jQuery:
https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events

'transitionend' event does not fire consistently

The following code works inconsistently with Chrome but also Firefox (with 'transitionend'). The function slogan_fade_next is just console.log('end');. I always get the classname applied to the first span element but anything after that is hit-and-miss when I click the refresh button, reload, or anything else.
The class of slogan-fadein applied to slogan[] changes the opacity of the element from zero to one but the callback function fade_setup isn't called consistently.
function fade_setup(){
var el = document.getElementsByClassName('slogan')[0];
el = el.getElementsByTagName('span');
for(var i=0;el[i];i++){
el[i].addEventListener('webkitTransitionEnd',slogan_fade_next,false);
}
el[0].className='slogan-fadein';
}
document.addEventListener('DOMContentLoaded', fade_setup);
instead of
document.addEventListener('DOMContentLoaded', fade_setup);
can you use
document.addEventListener('load', fade_setup)
With your current implementation, the JavaScript may be running before the browser has finished applying styles and, therefore, before any transitions are defined.
The problem is caused by a timing issue with applying the styles and anything else as mentioned by Stephen. The problem is, things aren't settled by the time I try to fire the first fade in so I triggered that with window.onload=slogan_fade_next;. Everything has settled in by the time my first element has done its thing.
I've given absolutely no more thought to this other than "it works" and I'm sure I'll come up with a better way to do this.

Add events in the background with jquery

I have an html ul list of 10,000+ elements and want to add custom hover tooltip events and do some other processing to each one. To do this on document.ready takes 2-3 seconds and freezes the browser. How can I do this asynchronously so that the browser doesn't freeze?
I've been reading about setTimeout, jQuery queue and deferred, but maybe I'm too dense to understand it all. This guy had interesting stuff http://erickrdch.com/2012/05/asynchronous-loop-with-jquery-deferred.html
Here's my each() loop that adds the hover.
$('#biglist li').each(function(index) {
$(this).hover(function(e){
...do stuff...
});
});
Thanks for your help.
why do you have it encased in a loop? try just applying hover to #biglist with .on(), and then delegating to each li:
$('#biglist').on('hover','li', function(){
// do crap
});
The .each() loop is likely wreaking havoc by doing processing on each item. As a side note, if you need to have different functions performed for mouseenter vs mouseleave, u need to use the XML format (using the .on() method is slightly different than the traditional .hover() method):
$('#biglist').on({
mouseenter: function(){
// do mouseenter crap
},
mouseleave: function(){
// do mouseleave crap
}
},'li');
Either way this should greatly reduce CPU consumption from processing.
You should bind it to #bigList using .on(), instead of on 10,000+ elements:
$('#bigList').on('hover', 'li', function(e) {
// ...
});
Browser JavaScript does not support true concurrency (apart from cutting-edge HTML5 features, that is) so you can't have one process run in the background while the page continue to work normally.
The best you can do AFAIK is to cut your processing code into chunks as small as possible, then execute them with setTimeout or setInterval, using a low value for delay (but preferably non-zero, so the rest of the page won't freeze).
Setting aside the fact that you don't need a different hover handler for each element, as others pointed out, if you need to do heavy processing of your received data (and such processing can't be done by the server) one way would be using a queue:
var queue = [];
setInterval(function() {
var next = queue.shift();
if ( next ) next();
},50);
...
$.each(lotsOfData, function(index, value) {
queue.push(function() {
// Code for processing the value
});
});

YUI: Stop event handlers from triggering while an animation is running

So I'm using YUI to add some animations in my application triggered when a user clicks certain elements. However, I'm running into a common problem that is easily fixed with some poor coding, but I'm looking for a more elegant solution that's less error-prone.
Often, when the user clicks something, a DOM element is animated (using Y.Anim) and I subscribe to that animation's 'end' event to remove the element from the document after its animation has completed. Pretty standard stuff.
However, problems arise when the user decides to spam-click the element that triggers this event. If the element is going to be removed from the DOM when the animation ends, and the user triggers an event handler that fires off ANOTHER animation on the same element, this 2nd animation will eventually cause YUI to spit really nasty errors because the node it was animating on suddenly disappeared from the document. The quickest solution I've found for this is to just set some module/class-level boolean state like 'this.postAnimating' or something, and inside the event handler that triggers the animation, check if this is set to true, and if so, don't do anything. In the 'end' handler for the animation, set this state to false.
This solution is really, really not ideal for many reasons. Another possible solution is to detach the event handler for duration of the animation and re-attach it once the animation is complete. This is definitely a little better, but I still don't like having to do extra bookkeeping that I could easily forget to do if forgetting to do so leads to incomprehensible YUI errors.
What's an elegant and robust way to solve this problem without mucking up a multi-thousand-line Javascript file with bits and pieces of state?
Here's some example code describing the issue and my solution to it.
var popupShowing = false,
someElement = Y.one('...');
someElement.on("click", showPopUp)
var showPopup = function(e) {
if(!popupShowing) {
popupShowing = true;
var a = new Y.Anim({
node: someElement,
duration: 0.2,
...
});
a.on('end', function() {
someElement.remove(true);
popupShowing = false;
});
a.run();
}
}
So if the user clicks "someElement" many times, only one animation will fire. If I didn't use popupShowing as a guard, many animations on the same node would be fired if the user clicked quickly enough, but the subsequent ones would error out because someElement was removed when the first completed.
Have a look at the Transition API. It's more concise, and may very well do what you want out of the box.
someElement.transition({ opacity: 0, duration: 0.2 }, function () { this.remove(); });
// OR
someElement.on('click', function () { this.hide(true, { duration: 0.2 }); });
// OR
someElement.on('click', someElement.hide);
Personally, I haven't used Anim since Transition was added in 3.2.0. Transition uses CSS3 where supported (with hardware acceleration), and falls back to a JS timer for older browsers.
http://developer.yahoo.com/yui/3/examples/transition/transition-view.html
Edit: By popular demand, a YUI way:
myAnim.get('running')
tells you whether an animation is running. To use this you might have to restructure the way you call the event so the animation is in the right scope, for example:
YUI().use('anim', function (Y) {
var someElement = Y.one('...');
var a = new Y.Anim({
node: someElement,
duration: 0.2,
...
});
a.on('end', function() {
someElement.remove(true);
});
someElement.on('click', function() {
if (!a.get('running')) {
a.run();
}
});
});
jsFiddle Example
Previously I had said: I personally like the way jQuery handles this. In jQuery, each element has a queue for animation functions. During animations an "in progress" sentinel is pushed to the front for the duration of the animation so anything that doesn't want to step on an animation peeks at the front of the queue for "in progress" and decides what to do from there, e.g. do nothing, get in line, preempt the current animation, etc.
I don't know enough about YUI to tell you how to implement this, but I find it to be a very elegant solution.
Quick & dirty solution to this particular issue?
Attach your handlers using .once() instead
someElement.once("click", showPopUp)
Also suitable if you need the handler re-attached later, just call that line again when the animation is done. You could also store your state information on the node itself using setData/getData but that is just a panacea to the real problem of state tracking.
Also, +1 to Luke's suggestion to use Transition for DOM property animation, it's grand.

Javascript mootools delay hide/show multilevel menu

I've made a javascript menu with css and javascript. I've used some mootools (1.11 , the only version i can use).
The script runs on domready, it fetches a dom element, and adds functions (showmenu, hidemenu) on the mouseenter and mouseleave events. The dom element is three levels of nested ul/li`s.
Now I want to add a delay on the menu of 500 ms when one hovers over the menu for the first time, and again when the users leaves the menu (so that the user has half a second time to get back to the menu).
I dont know how to keep track of the events, and cancel them. My knowledge of javascript is not good enough to know where to start. Can anyone give me an example how i should create this? Not really looking for cut and paste code, more pointers in the working of javascript, which native functions i could use, and what is the best way to set something like this up.
Thanx in advance
p.s. Maybe i want to also have a delay (100 ms or so) when the user is already using the menu for the items to show up. Will this be a lot more complex?
perhaps this can give you an idea: http://www.jsfiddle.net/dimitar/stthk/ (extracted it from another menu class I am working on and modded for delay for you as an example)
basically several interesting bits:
options: {
showDelay: 500,
hideDelay: 500
},
defines your delays on mouseover and out.
and then the bind for mouseenter deferred via .delay():
mouseenter: function() {
$clear(_this.timer);
_this.timer = (function() {
this.retrieve("fold").setStyle("display", "block");
}).delay(_this.options.showDelay, this);
},
mouseleave: function() {
$clear(_this.timer);
_this.timer = (function() {
this.retrieve("fold").setStyle("display", "none");
}).delay(_this.options.hideDelay, this);
}
_this.timer is a shared var that handles the deferred function - it gets cleared up on either mouseout or mouseover. if no event that matters takes place within the allotted time period, it will change the display accordingly, else, it will cancel the function.
this is for mootools 1.2.5 btw (storage system + elment delegation) but the principle remains the same for the bits that matter.
The stylish/anal way of doing it would be to fade in/out the menu. You do that with Fx.Morph where you morph the opacity css property and set the complete property to actually remove the div - notice that it's different to make this work in IE5-7.
The more basic/sensible way is to use setTimeout().

Categories