Link to home
Start Free TrialLog in
Avatar of codelevel
codelevel

asked on

drag elements

i want to drag and drop the elements based on the class.
please help.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
function allowDrop(ev) {
    ev.preventDefault();
}
function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>
<div style="float:left;width:200px;border:1px solid blue;margin:0 0 20px 0"> 
<img src="" alt="1" class="male" draggable="true" ondragstart="drag(event)"/>
<img src="" alt="2" class="male" draggable="true" ondragstart="drag(event)" /> 
<img src="" alt="3" class="female" draggable="true" ondragstart="drag(event)"/> 
<img src="" alt="4" class="female" draggable="true" ondragstart="drag(event)" /> 
<img src="" alt="5" class="male" draggable="true" ondragstart="drag(event)" /> 
<img src="" alt="6" class="female" draggable="true" ondragstart="drag(event)"/> 
</div>
<div style="float:left;width:200px;border:1px solid blue;margin:0 10px 0 0;clear:both" ondrop="drop(event)" ondragover="allowDrop(event)">
  <p>female</p>
</div>
<div style="float:left;width:200px;border:1px solid red" ondrop="drop(event)" ondragover="allowDrop(event)">
  <p>male</p>
</div>
</body>
</html>

Open in new window

Avatar of Montoya
Montoya

you can just go draggable based on the class $(".myclass").draggable();
The only problem with your code is that you have not given your <img> element's id's.

Your ondragstart handler defined like so
function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
}

Open in new window

References evt.target.id - but in your code the element has no id - so is undefined / empty. By giving your <img> elements unique id's the code should work.

Sidebar: any particular reason you are using the transitional Doctype and not the HTML5 Doctype?
Avatar of codelevel

ASKER

i cannot use unique ids for each img.
need to use 2 classes only as there are only 2 types.
please correct it based on that logic.
female images should be allowed to drop in female box only and same with male images.
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
very nice. sorry for the confusion.
You are welcome.