James
James

Reputation: 546

JavaScript make AJAX content fade in

How would I make the content fade into the div with the id viewRoul every time the script runs to load new content?

function list_roul(){
    var hr = new XMLHttpRequest();
    hr.onreadystatechange = function(){
        if (hr.readyState==4 && hr.status==200){
            document.getElementById("viewRoul").innerHTML = hr.responseText;
        }
    }
    hr.open("GET", "listRoul.php?t=" + Math.random(), true);
    hr.send();
}

I tried using

$('#viewRoul').html(html).fadeIn() 

but it didn't work!

Upvotes: 3

Views: 3899

Answers (4)

zzzzBov
zzzzBov

Reputation: 179284

If the content's already visible (which it would be by default), you'll need to hide it before it can fade in:

$('#viewRoul').html(html).hide().fadeIn();

Example:

$('#b1').click(function () {
    $('#one').html($(this).data('text')).fadeIn();
});
$('#b2').click(function () {
    $('#two').html($(this).data('text')).hide().fadeIn();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="b1" type="button" data-text="lorem ipsum">One</button>
<div id="one"></div>
<button id="b2" type="button" data-text="lorem ipsum">Two</button>
<div id="two"></div>

Upvotes: 4

Andrew Ice
Andrew Ice

Reputation: 841

Set your #viewroul div to display hidden, if it's supposed to be hidden initially. And on Ajax success. Just make #viewroul fade In. or also #viewroul.show('slow');

Upvotes: 0

user762330
user762330

Reputation:

The "viewRoul" element is visible, you need to hide it first.

Demo

$('#viewRoul').hide().html(html).fadeIn('slow');

You can read more about jQuery ui here fadeIn

Upvotes: 0

mayabelle
mayabelle

Reputation: 10014

Try this:

$('#MyDiv').hide().html(content).fadeIn({ duration: 2000 });

JSFiddle: http://jsfiddle.net/nYbHs/

You can adjust the speed by changing duration. Here is more documentation on fadeIn: http://api.jquery.com/fadeIn/

Clarification update: This code needs to go in your ajax callback function. The content would be either the response itself (if it's already in the HTML format you want) or the response parsed into a content string in the HTML format that you want.

Like this:

$.ajax(
{
    url: yourUrl,
    type: 'get',
    data: yourData,
    async: true,
    success: function(response) 
    {
        $('#MyDiv').hide().html(response).fadeIn({ duration: 2000 });
    }
});

Upvotes: 0

Related Questions