user1023110 user1023110 - 1 month ago 12
Javascript Question

How to get access the div element referred to by a jquery dialog?

I have a some javascript code whcih creates a dialog, that looks something like this:

$( function () {
$('.hoverList').dialog({
autoOpen: false,
hide: {
effect: "fade",
duration: 400
},
title: $(this).data("title"),
modal: false
});};


In this case there may be multiple hoverlist class elements on the page. The problem I am having is with this line in the above:

title: $(this).data("title")


On my pag, the div that contains my dialog looks like this:

<div class='hoverlist' data-title='My Dialog Title'>...</div>


When the javascript runs though, $(this) returned in the 'title:' key of the dialog refers tot he document itself, not to the element to which this dialog directive applies, so data("title") of the element is not accessible here.

Note that there may several hoverlists on the same page, so I can't just select it by an id instead of a class without recreating the same code repeatedly. Trying to figure out how I can construct the dialog with the title referred to in the data element of the which I am turning into a dialog. How might this be possible?

Dan Dan
Answer

If you want to do this, then you'll need to loop through the jQuery selector object, so that '$(this)' refers to the current node.

$( function () {

    $('.hoverList').each(function(){
        $(this).dialog({
            autoOpen: false,
            hide: {
                effect: "fade",
                duration: 400
            },
            title: $(this).data("title"),
            modal: false
        });
    });
});