Glenn Dayton
Glenn Dayton

Reputation: 1430

Allow objects with same id to be draggable with jQuery

I have created the following jQuery code to allow for an object to be draggable:

JavaScript:

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

HTML:

<div id="drag-item">One</div>
<div id="drag-item">Two</div>
<div id="drag-item">Three</div>

Only the first div with id "drag-item" is draggable, but the others are not. I want all of them to be draggable. I understand that this can be done by assigning each one a different id, but I would rather just declare one id that allows all object with that id the functionality of draggable. How would I be able to do this?

Upvotes: 1

Views: 170

Answers (3)

Peter-Paul van Gemerden
Peter-Paul van Gemerden

Reputation: 7011

If you are free to change the HTML, you can use a class instead of an id.

$(function(){
    $(".drag-item").draggable();
});
<div class="drag-item">One</div>
<div class="drag-item">Two</div>
<div class="drag-item">Three</div>

If, however, you're not free to change the HTML, you can use the following:

$(function(){
    $("[id=drag-item]").draggable();
});

Unlike the #drag-item, the attribute selector will return all matching elements, instead of just the first. Keep in mind, though, that having multiple elements with the same id means you have invalid HTML.

Upvotes: 5

Kyle
Kyle

Reputation: 22278

$(function(){
    $(".drag-item").draggable();
});

HTML:

<div class="drag-item">One</div>
<div class="drag-item">Two</div>
<div class="drag-item">Three</div>

Use class instead of id.

It is not valid html to have duplicate id's.

Upvotes: 6

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79850

You cannot duplicate ID's like that.. ID's should be unique. Use a class selector

HTML:

<div class="drag-item">One</div>
<div class="drag-item">Two</div>
<div class="drag-item">Three</div>

JS:

$(function(){
    $(".drag-item").draggable(); //Edit: as MrOBrian pointed out
});

Upvotes: 5

Related Questions