Seif Eddine Slimene Seif Eddine Slimene - 1 month ago 6
Javascript Question

I have this code to modify but not understand the second statement in if block

the second statement in the block if which is

$next.addclass(type).offsetWidth
is neither a call to a function neither an assignment.

if (transition)
{
$next.addClass(type);
$next[0].offsetWidth;
}
else
{
$active.removeClass('active');
$next.addClass('active');
}


What's the logic here?

Answer

offsetWidth is a measurement property that must be calculated and accessing it will cause a DOM reflow. This would be the only possible use of reading an unused value. Otherwise it's just dead code.

The code should probably have been:

if (transition) { 
    $next.addClass(type);
    forceDomReflowFrom($next[0]);
} else {  
    $active.removeClass('active');
    $next.addClass('active');
}

function forceDomReflowFrom(el) {
    el.offsetWidth;
}

Here's another related question where this approach was used to force a browser reflow (otherwise CSS animations wouldn't work).

Comments