Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery smooth change of innerHTML

I have the code below working like a charm:

var div = $('#div');
div.html('<div>one line</div><div>another line</div>');
div.slideDown('slow');

But the problem comes when I need to change the content (the number of lines):

div.html('<div>one line replacement</div><div>another line replacement</div><div>third line</div>')

This transition is too fast. How to animate this?

like image 949
Jader Dias Avatar asked Jul 17 '09 17:07

Jader Dias


People also ask

How to change innerHTML value in jQuery?

For replacing innerHTML of a div with jquery, html() function is used. After loading the web page, on clicking the button content inside the div will be replaced by the content given inside the html() function.

How to replace HTML element in jQuery?

We can replace HTML elements using the jQuery . replaceWith() method. With the jQuery replaceWith() method, we can replace each element in the set of matched elements with the provided new content and return the set of elements that were removed.

How to replace innerHTML of a div using js?

Projects In JavaScript & JQuery To replace innerHTML of a div tag, use the html() method. The dot notation calls the html() method to replace the inner html with the parameter placed between, i.e. Demo here. The html() here modifies the . innerhtml.

Can I use innerHTML in jQuery?

jQuery html() MethodThe html() method sets or returns the content (innerHTML) of the selected elements. When this method is used to return content, it returns the content of the FIRST matched element. When this method is used to set content, it overwrites the content of ALL matched elements.


2 Answers

You can add an invisible span to the html:

<span class="foo" style="display: none">some other lines</span>

And then fade them in:

$("span.foo").fadeIn('slow');


Going by your edit, you may also want to consider:

div.slideUp('slow'); // you may want this to be 'fast'
div.html('some other lines');
div.slideDown('slow');
like image 79
Daniel Sloof Avatar answered Oct 03 '22 17:10

Daniel Sloof


A wrinkle on Daniel Sloof's answer:

div.fadeOut('fast', function() {
  div.html(html);
  div.fadeIn('fast');
}

This will ensure your first animation is complete before proceeding. In my current case at least, fading makes a nicer experience than sliding.

like image 43
Tim Scott Avatar answered Oct 03 '22 18:10

Tim Scott