How to make draggable element to remaim in the same place - javascript

How can make a draggable element to remain displayed on its source box after being dragged?
Below the script to illustrate it:
function dragStart(ev) {
ev.dataTransfer.setData('text1', ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData('text1');
ev.target.appendChild(document.getElementById(data));
}
function allowDrop(ev) {
ev.preventDefault();
}
.boxarticle {
width: 200px;
height: 150px;
border: 1px solid blue;
margin: 0 0 10px 20
}
div#panier {
width: 150px;
height: 150px;
background-color: ;
border: 1px solid blue;
}
<!-- I want that image to remain here after I dragged it -->
<div class='boxarticle'>
<img src="https://cdn-images-1.medium.com/max/1200/1*QQvzwKk7rdC1JkY0XiPVUQ.png" draggable="true" id='image' data-price='9200' ondragstart="dragStart(event)" width=80 height=80>
</div>
<!-- where draggable element go in -->
<div id="panier" ondrop='drop(event)' ondragover="allowDrop(event)"> Drag and drop image here..but leave it in the source place </div>

You need to clone it and give it a new id, otherwise it will assume "drag".
HTML5 drag and copy?
function dragStart(ev)
{
ev.dataTransfer.setData('text1',ev.target.id);
}
function drop(ev)
{
ev.preventDefault();
var data=ev.dataTransfer.getData("text1");
var nodeCopy = document.getElementById(data).cloneNode(true);
nodeCopy.id = "randomId";
ev.target.appendChild(nodeCopy);
}
function allowDrop(ev)
{
ev.preventDefault();
}
.boxarticle {
width:200px;height: 150px; border:1px solid blue;margin: 0 0 10px 20
}
div#panier {
width:150px;height: 150px;background-color: ; border: 1px solid blue;
}
<!-- I want that image to remain here after I dragged it -->
<div class='boxarticle'>
<img src="https://cdn-images-1.medium.com/max/1200/1*QQvzwKk7rdC1JkY0XiPVUQ.png" draggable="true" id='image' data-price='9200' ondragstart="dragStart(event)" width=80 height=80>
</div>
<!-- where draggable element go in -->
<div id="panier" ondrop='drop(event)' ondragover="allowDrop(event)"> Drag and drop image here..but leave it in the source place </div>

Related

Drag and drop change image with switch

i am working on my game but i have some problems...
1. if the image is in the class .room it has a another src but if you drop it in the class .items it should change to a icon. And if you drag it again to .room it will turn back.
2. There are many different image so i want to have a switch. if the draged objekt is dragging to .items the image should change. so the id of the image should go to the switch and check if the id and case is the same. the scr should be from the icon.
3. if it is possible i want to safe the id of the image in local.storage so i can use the objekt in the next page
<html>
<head>
<style>
.room {
width: 500px;
height: 150px;
margin: 10px;
padding: 10px;
border: 1px solid black;
}
.items {
width: 500px;
height: 150px;
margin: 10px;
padding: 10px;
border: 1px solid black;
}
</style>
<script>
function allowDrop(ev) {
if (ev.target.className === "items") {
ev.target.style.border = "3px dashed black";
}
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("img", ev.target.id);
}
function dragleave(ev) {
if (ev.target.className === "items") {
ev.target.style.border = "0px dashed transparent";
}
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("img");
ev.target.style.border = "0px dashed transparent";
if (ev.target=="[object HTMLImageElement]"){
ev.target = ev.target.parentNode;
}
else {
ev.target.appendChild(document.getElementById(data));
}
if (ev.target.id === ev.dataTransfer.getData("ori")) {
return;
}
var image = document.createElement("img");
image.id =
image.draggable = true;
image.addEventListener('dragstart', drag);
if (ev.target.className === 'items') {
icon();
} else if (ev.target.className === 'room') {
room();
}
var originEle = document.getElementById(ev.dataTransfer.getData("ori"));
originEle.outerHTML = '';
delete originEle;
ev.target.appendChild(image);
}
function icon(){
switch(image.id) {
case "teddy": image.src="pic/Icons/teddy.png";break;
case "book": image.src="pic/Icons/Buch.png";break;
}
}
function room(){
switch(image.id) {
case "teddy": image.src= "pic/Home/HomeRoom_booksL.png";break;
case "booksR": image.src= "pic/Home/HomeRoom_buch.png";break;}
}
function reset(){
var container = document.getElementById("field");
container.innerHTML= html;
}
var html;
window.onload = function(){
html = document.getElementById('field').innerHTML;
};
</script>
</head>
<body>
<h2>Drag and Drop</h2>
<div>
<div class="room" ondrop="drop(event)" ondragover="allowDrop(event)">
</div>
<h2>items</h2>
<div class="items" ondrop="drop(event)" ondragover="allowDrop(event)">
<img id="book" src="pic/Icons/Buch.png" draggable="true" ondragstart="drag(event)" id="drag1">
<img id="teddy" alt="booksL"src="pic/Home/HomeRoom_teddy.png" id="drag2" draggable="true" ondragstart="drag(event)" >
</div>
</div>
</body>
</html>
About the 3rd question - saving to localStorage:
add the code below to your drop function.
localStorage.setItem("name", data);

images from array to img src of class in javascript

I have some code which tries to display temporary images from tempimages[] to img src with id=slide of box002, according to the random number selected from arrayVariable to ptag[i].
I want to display tempimages[0] first on img src of class box002, after dropping that image it gets deleted by the function Drop(ev), after that tempimages[i] should display img src of box002 for dropping likewise.
How to display images from an image array tempimages to class box img src?
I have used the function displayAllImages() to allocate images to img src id=slide, but it failed to display images.
box002 can be dragged and dropped to any box.
I want to display each image one by one from tempimages[] to img src of the box after each drop. How to change the code to achieve this property?
var tempimages = [];
function rvalue() {
var array = [];
var arrayVariable = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
var ArrayOfImages = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg', '7.jpg', '8.jpg', '9.jpg', '10.jpg'];
arrayLength = arrayVariable.length;
ptags = document.getElementsByName("values");
for (i = 0; i < ptags.length; i++) {
ptags[i].innerHTML = arrayVariable[Math.floor(Math.random() * arrayLength)];
array.push(ptags[i].textContent);
tempimages.push(`${ptags[i].textContent}.jpg`); // want to display array to box002 to imgtag
}
}
function displayAllImages() {
var
i = 0,
len = tempimages.length;
for (; i < tempimages.length; i++) {
var img = new Image();
img.src = tempimages[i];
img.style.width = '100px';
img.style.height = '100px';
document.getElementById('slide').appendChild(img);
}
};
$(function() {
displayAllImages();
});
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");
var el = document.getElementById(data);
el.parentNode.removeChild; // deleting drag item
ev.target.style.backgroundColor = 'initial'; //[value indicate which box element] bgcoclor none
var pParagraph = ev.target.firstElementChild;
ev.target.removeChild(pParagraph);
alert(el);
}
#container {
margin-top:-2%;
white-space:nowrap;
text-align:center;
margin-left:20%;
margin-right:30%;
}
.box {
background-color: coral;
width: 60px;
height:60px;
margin-top:10px;
display:inline-block;
border-radius:5px;
border:2px solid #333;
border-color: #e6e600;
border-radius: 10%;
background-color: #ffcc00;
}
.box002 {
float: left;
width: 50px;
height: 50px;
float: left;
margin-left:30%;
padding-top:2%;
background-color:#ffff00 2px;
border:2px solid #000066;
}
.text {
padding: 20px;
margin:7 px;
margin-top:10px;
color:white;
font-weight:bold;
text-align:center;
}
#container {
white-space:nowrap;
text-align:center;
margin-left:20%;
margin-right:30%;
}
.text {
padding: 20px;
margin:7 px;
margin-top:10px;
color:white;
font-weight:bold;
text-align:center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onload="rvalue()">
<div id="container">
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="10">
<p name="values"></p>
</div>
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="11">
<p name="values"></p>
</div>
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="12">
<p name="values"></p>
</div>
</div>
<div class="box002" draggable="true" ondragstart="drag(event)" id="2">
<img src="" draggable="true" id="slide" style="width:30px; height:30px; border-radius: 50%;" border="rounded"/>
</div>
</body>
I'm not a 100% sure what it is you're trying achieve but here is something which might get you to the where you want to get. It picks three items at random and updates the image in the slide element after each time the slide is dropped on one of the boxes.
I've made a couple of changes, see the comments in the code as to why I've made the changes. When I saw this code first I didn't understand the need for two separate arrays so I've merged them into a single array.
var tempimages = [];
function rvalue() {
const
items = [
{ label: '1', url: 'https://via.placeholder.com/75x75?text=1' },
{ label: '2', url: 'https://via.placeholder.com/75x75?text=2' },
{ label: '3', url: 'https://via.placeholder.com/75x75?text=3' },
{ label: '4', url: 'https://via.placeholder.com/75x75?text=4' },
{ label: '5', url: 'https://via.placeholder.com/75x75?text=5' },
{ label: '6', url: 'https://via.placeholder.com/75x75?text=6' },
{ label: '7', url: 'https://via.placeholder.com/75x75?text=7' },
{ label: '8', url: 'https://via.placeholder.com/75x75?text=8' },
{ label: '9', url: 'https://via.placeholder.com/75x75?text=9' },
{ label: '10', url: 'https://via.placeholder.com/75x75?text=10' }
],
ptags = Array.from(document.querySelectorAll('[name="values"]'));
ptags.forEach(ptag => {
const
// Generate a random index.
randomIndex = Math.floor(Math.random() * items.length),
// Get the at item from the random index (it is possible the same item
// gets picked multiple times as there is no check for duplicates).
item = items[randomIndex];
// Update the label
ptag.textContent = item.label;
// Push the item into the array.
tempimages.push(item);
});
}
function displayAllImages() {
// Check if there are still images in the array, if not exit.
if (tempimages.length === 0) {
return;
}
const
// Remove the item at index 0 from the array.
item = tempimages.shift(),
// Get the image element.
image = document.getElementById('slide');
// Update src attribute so it points to the new URL.
image.src = item.url;
};
$(function() {
// On start, do rvalue first. This is taken from the onload in the body
// as that fired later than this method which meant displayAllImages was
// called before rvalue.
rvalue();
displayAllImages();
});
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");
var el = document.getElementById(data);
el.parentNode.removeChild; // deleting drag item
// ev.currentTarget is a div with class box whereas target can
// be either the div or the p element. Using currentTarget ensures
// you know which element you're working with.
ev.currentTarget.style.backgroundColor = 'initial'; //[value indicate which box element] bgcoclor none
var pParagraph = ev.currentTarget.firstElementChild;
ev.currentTarget.removeChild(pParagraph);
// Show the next image in the slider..
displayAllImages();
}
#container {
margin-top:-2%;
white-space:nowrap;
text-align:center;
margin-left:20%;
margin-right:30%;
}
.box {
background-color: coral;
width: 60px;
height:60px;
margin-top:10px;
display:inline-block;
border-radius:5px;
border:2px solid #333;
border-color: #e6e600;
border-radius: 10%;
background-color: #ffcc00;
}
.box002 {
float: left;
width: 50px;
height: 50px;
float: left;
margin-left:30%;
padding-top:2%;
background-color:#ffff00 2px;
border:2px solid #000066;
}
.text {
padding: 20px;
margin:7 px;
margin-top:10px;
color:white;
font-weight:bold;
text-align:center;
}
#container {
white-space:nowrap;
text-align:center;
margin-left:20%;
margin-right:30%;
}
.text {
padding: 20px;
margin:7 px;
margin-top:10px;
color:white;
font-weight:bold;
text-align:center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="container">
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="10">
<p name="values"></p>
</div>
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="11">
<p name="values"></p>
</div>
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="12">
<p name="values"></p>
</div>
</div>
<div class="box002" draggable="true" ondragstart="drag(event)" id="2">
<img src="" draggable="true" id="slide" style="width:30px; height:30px; border-radius: 50%;" border="rounded"/>
</div>
</body>

How to check is cell filled?JS

I have simple table with two cells. I change w3 school code(for drag and drop) to one image, when drag over second, take second image place and second image disappears. But problem come when there is no image in cell, then cell is gone. How to check is there image in cell?
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");
var el = ev.target.parentNode;
ev.target.appendChild(document.getElementById(data));
el.appendChild(document.getElementById(data).cloneNode(true));
var x = el.classList.contains('dropzone');
if (!x) {
ev.target.remove();
}
}
th, td{
border: solid black;
width: 100px;
height: 100px;
padding: 0px;
}
table{
width: 300px;
}
img{
width: 100px;
}
<table>
<tr>
<td ondrop="drop(event)" ondragover="allowDrop(event)"><img ondragstart="drag(event)" draggable="true" id="a8" src="http://images5.fanpop.com/image/photos/27700000/desert-windows-7-vista-and-xp-picks-27752343-500-375.jpg"></td>
<td ondrop="drop(event)" ondragover="allowDrop(event)"><img ondragstart="drag(event)" draggable="true" id="b8" src="http://images5.fanpop.com/image/photos/27700000/jellyfish-windows-7-vista-and-xp-picks-27753183-500-375.jpg"></td>
</tr>
</table>
you can loop throught td elements and add ondrop event in you javascript code, So you can know which element has fired the event.
Then check if this element has a child inside.
If not => don't perform action (no image elements inside), else => perform action (there is an image elements inside).
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
var td=document.getElementsByTagName("td");
for(var i=0; i < td.length;i++){ //bind ondrop event to all td, so it will be easier to get the element which fired the event
td[i].ondrop=function(ev){
ev.preventDefault();
if (this.hasChildNodes()) { //check if got children nodes (if got img inside)
var data = ev.dataTransfer.getData("text");
var el = ev.target.parentNode;
ev.target.appendChild(document.getElementById(data));
el.appendChild(document.getElementById(data).cloneNode(true));
var x = el.classList.contains('dropzone');
if (!x) {
ev.target.remove();
}
}
}
}
th, td{
border: solid black;
width: 100px;
height: 100px;
padding: 0px;
}
table{
width: 300px;
}
img{
width: 100px;
}
<table>
<tr>
<td ondragover="allowDrop(event)"><img ondragstart="drag(event)" draggable="true" id="a8" src="http://images5.fanpop.com/image/photos/27700000/desert-windows-7-vista-and-xp-picks-27752343-500-375.jpg"></td>
<td ondragover="allowDrop(event)"><img ondragstart="drag(event)" draggable="true" id="b8" src="http://images5.fanpop.com/image/photos/27700000/jellyfish-windows-7-vista-and-xp-picks-27753183-500-375.jpg"></td>
</tr>
</table>
For more details how to check if element has any children, check answers here

Image as check box

I have 2 images.
What i want to do is to make it clickable and selectable.
If i select the first one the other should not be selected.
and if i click a button it should print the vaalue of the selected image on <p> tag
This is the code which i got after searching a lot :
$('#img1').click(function() {
var a = $('#img1');
//A if else condition should be here to know wheather it already contain the class
a.addClass('clicked')
})
$('#img2').click(function() {
var a = $('#img2');
//A if else condition should be here to know wheather it already contain the class
a.addClass('clicked')
})
$('button').click(function() {
var a = $('#img1').val();
var b = $('#img2').val();
$('p').html(/*The value of the selected image*/)
})
.clicked {
box-shadow: 0 0 10px 2px grey;
}
img:hover {
cursor: pointer;
box-shadow: 0 0 10px 2px grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<img src="http://www.w3schools.com/howto/img_avatar.png" width="100px" height="100px" id="img1" value="noo">
<img src="http://www.w3schools.com/howto/img_avatar2.png" width="100px" height="100px" id="img2" value="yes"><br>
<button>
Copy
</button>
<p>
</p>
Jsfiddle
Thanks
I have updated your js use $('#img1').removeClass('clicked'); on click functions
$('#img1').click(function() {
var a = $('#img1');
$('#img2').removeClass('clicked');
//A if else condition should be here to know wheather it already contain the class
a.addClass('clicked')
})
$('#img2').click(function() {
var a = $('#img2');
$('#img1').removeClass('clicked');
//A if else condition should be here to know wheather it already contain the class
a.addClass('clicked')
})
Please use this code.
$(document).ready(function(){
$('img').click(function() {
$('img').removeClass('clicked');
$(this).addClass('clicked');
})
$('button').click(function() {
var value = $('.clicked').attr("value");
$('p').html(value);
})
});
$('img').click(function() {
$('img').removeClass('clicked')
$(this).addClass('clicked');
console.log($(this).attr('data-value'))
})
$('button').click(function() {
$('p').html($('img.clicked').attr('data-value'))
})
.clicked {
box-shadow: 0 0 10px 2px grey;
}
img:hover {
cursor: pointer;
box-shadow: 0 0 10px 2px grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<img src="http://www.w3schools.com/howto/img_avatar.png" width="100px" height="100px" id="img1" data-value="noo">
<img src="http://www.w3schools.com/howto/img_avatar2.png" width="100px" height="100px" id="img2" data-value="yes"><br>
<button>
Copy
</button>
<p>
</p>
change attr value to data-attr since it is not a valid attr
use img tag then detect the click element with this context
the use the data-attr to show the value
Try this
$('#img1').click(function() {
resetClick();
var a = $('#img1');
//A if else condition should be here to know wheather it already contain the class
a.addClass('clicked')
})
$('#img2').click(function() {
resetClick();
var a = $('#img2');
//A if else condition should be here to know wheather it already contain the class
a.addClass('clicked')
})
function resetClick(){
$('#img1').removeClass('clicked');
$('#img2').removeClass('clicked');
}
$('button').click(function() {
$('p').html( $('img.clicked').attr('value'));
})
.clicked {
box-shadow: 0 0 10px 2px grey;
}
img:hover {
cursor: pointer;
box-shadow: 0 0 10px 2px grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<img src="http://www.w3schools.com/howto/img_avatar.png" width="100px" height="100px" id="img1" value="noo">
<img src="http://www.w3schools.com/howto/img_avatar2.png" width="100px" height="100px" id="img2" value="yes"><br>
<button>
Copy
</button>
<p>
</p>
$('#img1').click(function() {
var a = $('#img1');
$('#img2').removeClass('clicked');
//A if else condition should be here to know wheather it already contain the class
a.addClass('clicked')
})
$('#img2').click(function() {
var a = $('#img2');
$('#img1').removeClass('clicked');
//A if else condition should be here to know wheather it already contain the class
a.addClass('clicked')
})
$('button').click(function() {
$('p').html($('.clicked').attr('value'))
})
.clicked {
box-shadow: 0 0 10px 2px grey;
}
img:hover {
cursor: pointer;
box-shadow: 0 0 10px 2px grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<img src="http://www.w3schools.com/howto/img_avatar.png" width="100px" height="100px" id="img1" value="noo">
<img src="http://www.w3schools.com/howto/img_avatar2.png" width="100px" height="100px" id="img2" value="yes"><br>
<button>
Copy
</button>
<p>
</p>

Adding JQuery functionality

I am trying to add JQuery functionality to my Rails application; however, it is not working. I am using JQuery draggable to move images around the screen. I have it working in a stand alone html file but I'm having a lot of difficulty adding it to my Rails application. This is the stand alone file:
<!DOCTYPE html>
<html>
<head>
<title>City</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="js/jquery-ui-1.10.4/themes/base/jquery-ui.css">
<script type="text/javascript" src="js/jquery-ui-1.10.4/jquery-1.10.2.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.10.4/ui/jquery-ui.js"></script>
<style type="text/css">
h1, h3
{
text-align: center;
margin: 0px;
}
/* style the list to maximize the droppable hitarea */
#canvas
{
width: 600px;
height: 600px;
border: 1px solid black;
margin: 0px auto;
overflow: hidden;
}
/*#canvas ol { margin: 0; padding: 1em 0 1em 3em; }*/
/*li { list-style: none;}*/
.canvas-area
{
width: 600px;
height: 600px;
}
/* map background */
/* img {
position: relative;
left: 50%;
top: 50%;
}*/
/* draggable icons */
.draggable
{
background: transparent url('images/transparent.png') repeat center top;
width: 40px;
height: 40px;
padding: 5px;
float: left;
margin: 0 10px 10px 0;
font-size: .9em;
border: hidden;
/*position: absolute;*/
}
#draggable
{
width: 40px;
height: 40px;
}
div img
{
margin: 0px auto;
position: relative;
top: 0px;
left: 0px;
width: 40px;
height: 40px;
}
.arrow img
{
width: 200px;
height: 200px;
}
.arrow
{
width: 200px;
height: 200px;
border: 1px solid black;
}
.commercial100 img
{
width: 100px;
height: 100px;
}
.commercial100
{
width: 100px;
height: 100px;
}
#building img
{
height: 150px;
}
</style>
<script>
// jquery ui script for snapping to grid
$(function() {
$( ".draggable" ).draggable({ grid: [10,10] });
$( "#draggable4" ).draggable({ grid: [ 20, 20 ], snap: true });
});
</script>
</head>
<body>
<div class="content">
<!-- Canvas for building the city -->
<h1>Mock view of my city</h1>
<h3>600 x 600</h3>
<div id="canvas">
<div id="ignoreThis" class="ui-widget-content canvas-area">
<p class="placeholder">Add your items here</p>
<div id="arrowSvg" class="draggable ui-widget-content arrow">
<img src="images/arrow.svg" alt="house" type="image/svg+xml" /> SVG (200px x 200px)
</div>
<div id="arrowPng" class="draggable ui-widget-content arrow">
<img src="images/arrow.png" alt="house"> PNG (200px x 200px)
</div>
<div id="building" class="draggable ui-widget-content commercial100">
<img src="images/building.png" alt="building" />
</div>
<div id="factory" class="draggable ui-widget-content commercial100" >
<img src="images/factory.png" alt="factory" />
</div>
<div id="ferry" class="draggable ui-widget-content commercial100" >
<img src="images/ferry.png" alt="ferry" />
</div>
<div id="house2l" class="draggable ui-widget-content" >
<img src="images/house2l.png" alt="two level house" />
</div>
<div id="houseSvg" class="draggable ui-widget-content">
<img src="images/house.svg" alt="house" type="image/svg+xml" /> SVG
</div>
<div id="housePng" class="draggable ui-widget-content">
<img src="images/house.png" alt="house" />
</div>
<div id="houseSF" class="draggable ui-widget-content" >
<img src="images/housesf.png" alt="SF house" />
</div>
<div id="street1" class="draggable ui-widget-content street" >
<img src="images/street.png" alt="street">
</div>
<div id="street2" class="draggable ui-widget-content street" >
<img src="images/street.png" alt="street">
</div>
<div id="street3" class="draggable ui-widget-content street" >
<img src="images/street.png" alt="street">
</div>
<div id="street4" class="draggable ui-widget-content street" >
<img src="images/street.png" alt="street">
</div>
</div>
<script>
// code to make the active div move to the front
// code from http://www.codingforums.com/javascript-programming/260289-bring-div-element-front-click.html
// create an array to hold the (buildings, streets, landmarks) element's id
var ids=[],
// grab all the divs (each icon) and put it into thedivs
thedivs = document.getElementById("canvas").getElementsByTagName("div");
for (var i = 0; i < thedivs.length; i++) {
// add the id of each div to the ids array
//alert(thedivs[i].id);
ids.push(thedivs[i].id);
thedivs[i].onclick = function() {
for (var a = 0; a < ids.length; a++) {
if (this.id == ids[a]) {
// take current id that matches the selected id and move it to the end
ids.push(ids.splice(a,1));
}
document.getElementById(ids[a]).style.zIndex=a;
}
}
}
</script>
</div>
<input type="button" value="save" onclick="saveAction()">
<script>
//Cycle through images and grab their x/y positions
var saveAction = function(){
elementNames = document.getElementById("canvas").getElementsByTagName("div");
for(var i = 0; i < elementNames.length; i++)
{
var idName = $( "#" + elementNames[i].id);
var offset = idName.offset();
alert("Left pos: " + offset.left + " Top pos: " + offset.top);
}
};
</script>
</div>
</body>
</html>
I have placed the Javascript in assets/javascripts/custom_map.js and I have placed the html / css in my new_map.html.erb view. The images are showing up fine in the Rails app but they are not draggable. How can I fix this? Thanks!
Perhaps your load order is incorrect or your assets path is wrong. Try linking your script as the last thing on your page and wrap everything in it inside a jquery ready function:
$(function() {
// all your scripts here
});
Also try viewing your source and making sure that your .js file is serving correctly
It should be /assets/yourjs.js rather than /assets/javascripts/yourjs.js
Also, I think you may be able to use the jquery ui stack function to make items settle on top (not sure, you might want to try it):
$( ".draggable" ).draggable({ stack: ".draggable" });
Without knowing the specific errors you're receiving, I can only detail why you're having a problem, and how to resolve it generally:
Unobtrusive
You should never put javascript in your HTML code (known as inline JS). Problems being that it's messy & can be easily tampered with... hence making it relatively insecure, and generally seen as amateurish
A better way is to use unobtrusive JS (where the JS is stored in files loaded outside the scope of HTML). Rails uses the asset pipeline for this:
#app/assets/javascripts/application.js
var ready = function() { // -> you said JQuery :)
$( ".draggable" ).draggable({ grid: [10,10] });
$( "#draggable4" ).draggable({ grid: [ 20, 20 ], snap: true });
/////////////////////////////////
var ids=[],
// grab all the divs (each icon) and put it into thedivs
thedivs = document.getElementById("canvas").getElementsByTagName("div");
for (var i = 0; i < thedivs.length; i++) {
// add the id of each div to the ids array
//alert(thedivs[i].id);
ids.push(thedivs[i].id);
thedivs[i].onclick = function() {
for (var a = 0; a < ids.length; a++) {
if (this.id == ids[a]) {
// take current id that matches the selected id and move it to the end
ids.push(ids.splice(a,1));
}
document.getElementById(ids[a]).style.zIndex=a;
}
}
}
};
$(document).on("page:load ready", ready);
If you migrate your JS from your views and put into your asset files, you'll be in a much better position to give us feedback, which we can then use to help fix your problem further

Categories