inserted DOM object dynamically and transition not applied Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of inserted DOM object dynamically and transition not applied without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I add a DIV to my object this way

    //add the slide to module
    self.activeSlideDom = $("<div id='module_"+self.moduleId+"-slide_"+self.activeSlide+"' class='slide'></div>").appendTo("div#module_"+self.moduleId);

The style rule for a DIV with class “slide” looks like this:

.slide {
padding:0px;
position:absolute;
left:0px;
top:0px;

width:100%;
height:100%;
background:transparent;
/* display:none; */
opacity:0;

-webkit-transform: translateZ(0);    
transition: opacity 2s;
-moz-transition: opacity 2s; /* Firefox 4 */
-webkit-transition: opacity 2s; /* Safari and Chrome */
-o-transition: opacity 2s; /* Opera */
}

And then I set it’s opacity to 1, thinking that that will make it fade in…

$(self.activeSlideDom).css("opacity","1");

But it doesn’t. If I however open the chrome “inspect element” and uncheck/check the opacity rule, the div fades nicely just as expected.

So is there a problem in how I set the opacity value, is that why the div just pops up instead of the smooth transition i’d expected?

Answer

To maintain browser performance, browser do reflow or redraw after all the changes are made to an element or say after having a change on style of any element it waits for a fraction of time to check if any other changes occur, to minimize the number of reflow and redraw.

So in your case after the element is created and opacity is applied reflow and redraw occurs causing no transition.

To solve this you can either follow two approach .

i) Force browser to call reflow/ repaint.

self.activeSlideDom = $("<div id='module_"+self.moduleId+"-slide_"+self.activeSlide+"' class='slide'></div>").appendTo("div#module_"+self.moduleId);

var offset = self.activeSlideDom.offset();
    
$(self.activeSlideDom).css("opacity","1");

Any css property which need to be computed by browser calls the reflow/ repaint. like .height(), .position(), .offset() etc.

ii) Do css change after reflow/redraw is completed, by adding it on asynchronous queue.

setTimeout(function(){
  $(self.activeSlideDom).css("opacity","1");
},0);
We are here to answer your question about inserted DOM object dynamically and transition not applied - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji