zizther
zizther

Reputation: 854

How to get data- atrribute value from content loaded in via jQuery .load()

I am loading content in using jQuery .load(), within the content that is added are some data- attributes which i want to get the value from to pass into another function.

The .load() code is:

url += ' #post';    

$("#modal_base #modal_inner").load(url , function(response, status, xhr) {
    if (status == "error") {
        var msg = "Sorry but there was an error: ";
        $('#error').appendTo( '#modal_inner' );
        $("#error").html(msg + xhr.status + " " + xhr.statusText);
    }
});

The data- attributes are in #modal_base #modal_inner #post once the content is loaded in. I presume there is no event for this element i need to somehow attach delegated event handlers to the document element.

What is the best way for me to do get the data-pag-next and data-pag-next values?

Upvotes: 1

Views: 713

Answers (1)

The complete callback will fire once the elements of the retrieved page has been loaded in the destination element and DOM updated, so you just need to look for it:

$("#modal_base #modal_inner").load(url , function(response, status, xhr) {
    if (status == "error") {
        var msg = "Sorry but there was an error: ";
        $('#error').appendTo( '#modal_inner' );
        $("#error").html(msg + xhr.status + " " + xhr.statusText);
    } else {
        alert( $(this).find('#post').attr('data-pag-next');
        alert( $(this).find('#post').data('pag-next') ); //If using jQuery 1.4.3+
        //examples of getting the data out
        window.yourvar = $(this).find('#post').data('pag-next'); //you can access window.yourvar anywhere in your code outside .load()
        some_function_of_your( $(this).find('#post').data('pag-next') );//pass the value to some function defined by you in the global scope
    }
});

Upvotes: 3

Related Questions