javascriptjqueryjquery-ui-tooltip

jQuery get id of element that triggered event from nested function


How do I get the id of the ".item" element from inside the getJSON function?

jQuery(document).ready(function() {

    $(".item").tooltip({
        items: "div",
        content: function(callback) {

            $.getJSON('mydata.json', function(data) {

                var country = event.target.id;

                console.log(country);

            });

        }

    });

});

I've seen an explanation here, but I'm not sure how to pass the event(s) in my case.


Solution

  • In your content callback, this refers to the element whose tooltip is being invoked, so you could use this.id to get the id of the current element

    jQuery(function ($) {
        $(".item").tooltip({
            items: "div",
            content: function (callback) {
                var el = this;
                $.getJSON('mydata.json', function (data) {
                    var country = el.id;
                    console.log(country);
                });
            }
        });
    });