0

I am making a drag and drop tool in javascript. I have a collection of images that I can drag and drop into a grid. This grid has 3 rows and 20 columns.

When an image is dragged onto the grid I want to save this data. For example I drag image and drop it on row 1, column 2. How can I save this data in javascript ?

In php this would be:

<?php
// row 1, column 2
$savedItems[1][2] = array("image" => "testimage.jpg", "extra" => 1);

?>

This way I can check if there is already an image on that spot or not. Or if I want to change the options of the spot I can search in the $savedItems array.

But how could I save this data in javascript? So it is easy to add and search data in the array.

3 Answers 3

1

Whenever you are performing a drag drop , you must be knowing the index of row and column into which you are dropping. When you perform a drag Drop , call a function like saveValues(rowIndex, columnIndex , value) to save your values at that location into array. Before saving , check whether the location already has some data other than your default values. If yes do not save values and break so that drag drop will not be performed , else save the values and and then perform drag drop.

Let us assume your array is named as : dragDropGrid

    function saveValues(rowIndex, columnIndex , value) {

    // value here is something related to that image .

    var valueAtIndex = dragDropGrid[rowIndex][columnIndex] ;

      if(valueAtIndex != null || valueAtIndex != "" || valueAtIndex != undefined ) {

         // If there already exists a value

         return false; // something to break the drag drop


     }else{ // if array location is empty

       dragDropGrid[rowIndex][columnIndex] = value;  //saved value at that index.

     return true; // now call drag drop.
    }

  }

You can either directly call this function on some event after performing dragDrop . Make sure function returns properly so as to continue or break the drag drop.

Thanks

Sign up to request clarification or add additional context in comments.

Comments

0

Almost exactly the same in JavaScript.

var cells = [ [ ], [ ], [ ] ];

function insertImage(row, column, image) {
  if (cells[row][column]) {
    console.info('Already exists!');
    return false;
  } else {
    cells[row][column] = image;
    return true;
  }
}

Comments

0

You can print the $savedItems as a javascript global variable.

<?php
echo '<script>';
echo 'var saved_items = ' . json_encode($savedItems); . ';';
echo '</script>';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.