Skip to content Skip to sidebar Skip to footer

Ajax Div Toggle Avoiding Reloading Content

I had a question regarding Ajax loading of html into a DIV. Ideally what I want is this: A toggle div with close button, which I have the code for here: http://jsfiddle.net/tymeJV/

Solution 1:

I edited the fiddle you posted adding the call to slideToogle() where appropriate. Also added a div element to hold the loaded html code.

<divid="country_slide"><ahref="#"id="close">Close</a><divclass=".content"></div><!-- This is the div I added --></div>

You can check the log messages in the console to verify that the code is doing what you expect. The URL for the Ajax call you were doing always returned an error so I changed to the URL that jsfiddle provides for testing: /echo/html/.

Here's the modified JS code:

$(function () {
    $('#close').click(function (e) {
        e.preventDefault();
        $('#country_slide').slideToggle();
    });

    $('#country_link').on('click', function (e) {
        e.preventDefault();
        var $link = $(this);
        // Exit if the data is loaded alreadyif ($link.data('loaded') === true) {
            console.log('Not using Ajax.');
            $("#country_slide").slideToggle();
            returnfalse;
        }

        $.ajax({
            type: 'GET',
            dataType: 'html',
            url: '/echo/html/',
            timeout: 5000,
            beforeSend: function () {
                $("#country_slide .content").html('<p>Loading</p>')
            },
            success: function (data, textStatus) {
                console.log('Fecthed with Ajax.');
                $("#country_slide .content").html(data);
                $("#country_slide").slideToggle();
                // If successful, bind 'loaded' in the data
                $link.data('loaded', true)
            },
            error: function (xhr, textStatus, errorThrown) {
                alert('request failed');
            },
            complete: function () {
            },
        });
    });
});

Post a Comment for "Ajax Div Toggle Avoiding Reloading Content"