-1

We have code that loads html to div with class content. We have div element with link class which has data-href and some other data-* properties. The code looks like:

$(document).on('click', '.link', linkClick);
linkClick: function (event) {
            event.stopPropagation();
            $('.content').load($(this).data('href'), function (response, status) {
                if (status == 'error') {
                    $('.content').html("Something went wrong. Please try again later");
                }
            });
        }

I want to access $(this) inside this callback of load function to get values of all other data-* properties of link clicked, how can i do that?

Sahil Sharma
  • 3,847
  • 6
  • 48
  • 98

3 Answers3

2

Create a scoped reference to it before the load call:

function (event) {
    event.stopPropagation();

    var $that = $(this); // <- Like this

    $('.content').load($(this).data('href'), function (response, status) {

        // You can use $that here

        if (status == 'error') {
            $('.content').html("Something went wrong. Please try again later");
        }
    });
}
Lennholm
  • 7,205
  • 1
  • 21
  • 30
0
$(document).on('click', '.link', linkClick);
var href = $(this).data('href');
linkClick: function (event) {
    event.stopPropagation();
    $('.content').load(href, function (response, status) {
        if (status == 'error') {
            $('.content').html("Something went wrong. Please try again later");
        }
    });
}
Jurij Jazdanov
  • 1,248
  • 8
  • 11
0

You can use event.target to access clicked element. Most common way is to store it under that or self variable.

$(document).on('click', '.link', linkClick);
linkClick = function (event) {
    event.stopPropagation();
    var that = event.target;
    $('.content').load($(that).data('href'), function (response, status) {
        if (status == 'error') {
            $('.content').html("Something went wrong. Please try again later");
        }
    });
}
Marcin Pevik
  • 163
  • 1
  • 14