0

I am trying to create a slideshow plugin, however, when I try to navigate to the left and right the listener's that are attached to the controls aren't updating

$.fn.imageOverlay = function () {
    return this.each(function () {
        var $this = $(this);

        $this.click(function () {
            //load paramters and stuff

            $.ajax({
                //stuff
                success: function(data) {
                    loadOverlay(data);
                }
            });
        });

        var loadOverlay = function() {
            jQuery(document).on('click', '.rightCtrl', function () {
                var id = $(this).data('id');

                console.log(id);

                $.ajax({
                    type: "POST",
                    url: domain + "loadajax/get_photo_overlay",
                    data: { id: id, type: params.type, criteria: params.criteria },
                    dataType: 'json',
                    success: function (data) {
                        setData(data);
                    }
                });
            });
        };

        var setData = function (data) {
            $('.rightCtrl').attr('data-id', data.controls.right);
        };
    });
})(jQuery);

When I click on the div "rightCtrl" it fires but an old data-id is being used. While inspecting the html markup the attribute is updating, but the new values aren't being passed. The issues lies within the function loadOverlay:

jQuery(document).on('click', '.rightCtrl', function () {
    var id = $(this).data('id'); //this is an outdated value
}
user3023421
  • 333
  • 1
  • 7
  • 16

1 Answers1

1

There is difference between properties and attributes. jQuery's .data() method caches the values behind the scenes. It only reads the data-* attribute when there is no cached value for the specified property. For understanding the issue you can check this question: jQuery Data vs Attr?

You should be consistent, either use .attr() or .data() method.

Community
  • 1
  • 1
Ram
  • 143,282
  • 16
  • 168
  • 197