Panos Paschalis
Panos Paschalis

Reputation: 171

jQuery draggable doesn't work after certain parts of page have loaded

I'm building this page: http://codediaries.club/team.php?id=126

And I have a specific issue with jQuery draggable function.

As you can see, I've used jQuery and bootstrap for certain elements. My problem is, after the window has loaded, I try to run a jQuery code to make some div elements in the third tab ("Formation") draggable within a certain area. This is my code:

<script>
$(window).load(function() {

           $(".ui-draggable").each(function(i, obj) {
                var self = this;
                var stringID = self.id.replace("man", "");
                var formationID = self.id.replace("formation", "map");
                formationID = formationID.replace("man", "formation");
                formationID = formationID.substring(0, 14);
                var coordXString = "coordX"+stringID;
                var coordYString = "coordY"+stringID;
                var positionRoleString = "positionRole"+stringID;
                this.start_x = $("[name='"+coordXString+"']").val();
                this.start_y = $("[name='"+coordYString+"']").val();
                this.start_role = $("[name='"+positionRoleString+"']").val();

                obj.draggable({
                    containment: "."+formationID,
                }).css("position", "absolute");

            });

        });

The console shows error in the line "obj.draggable", saying that "draggable is not a function".

However, I have tested that if I put this line of code in the beginning of the document,

$( function() {
          $(".draggable").draggable();
  } );

it doesn't show this error, so I guess, that something loads after a specific amount of time, and breaks jQuery functions.

Thanks to anyone that watches and wants to help, in advance.

Upvotes: 0

Views: 169

Answers (1)

user1189882
user1189882

Reputation:

Looks like the value in your loop (obj) is an HTML element instead of a jQuery element, and draggable must be called on a jQuery element. Try surrounding your obj with jQuery wrapper.

So change this:

obj.draggable({
  containment: "."+formationID,
}).css("position", "absolute");

To:

$(obj).draggable({
  containment: "."+formationID,
}).css("position", "absolute");

Upvotes: 1

Related Questions