"Fixing the Vertical Order of Divs with Jquery: A Step-by-

Before I completely lose my mind, I need some help with a coding issue. Right now, I have two initial divs displayed. The user should be able to add these divs below the original ones as many times as they want, or remove them if needed. I've been attempting to allow for the reordering of these divs using drag and drop functionality, but nothing seems to be working. Additionally, once the user drags and drops the divs, they need to reindex themselves. Below is the code that I currently have. Keep in mind that I tried and failed with numerous other methods before arriving at this basic implementation. Your assistance is greatly appreciated.

Loading JQuery...

Displaying the first div to the end-user...


            <!--Div contains each answer step-->
            <div id = "answer_step" class = "answer_step">
                <!--This placeholder text is styled from CSS and will empty the div once the user starts typing-->
                <div id="answer_step_equation0" class="answer_step_equation" contenteditable="true" placeholder="Enter The Next Solution Step This Question"></div>
                <div id="answer_step_description0" class = "answer_step_description" contenteditable="true" placeholder="Enter A Description as to how this step was reached or how to solve the next step"></div>
            </div>
        </div>
<!-- Buttons to dynamically add and remove answer divs. The remove functionality is added in JQuery for the add button-->
        <button id="add_answer_step_button" class="add_answer_step_button">+ Add next Step</button>

This code appends the new divs within a parent div. However, I'm struggling to achieve proper functionality.

<!--Script to append/remove div when user clicks on add_answer_step_button-->
<script type = "text/javascript" language = "javascript">

    $(document).ready(function() {
        <!--This variable gives each new set of answer divs a unique id by appending a number to the end of the id-->
        <!--The first set of answer divs will have an id of zero-->
        var answer_identifier_number = 1;
        $("button.add_answer_step_button").click(function () {
            $("div.answer_steps").append('<div id="answer_step_equation' + answer_identifier_number + '" class="answer_step_equation" contenteditable="true" placeholder="Enter The Next Solution Step This Question"></div>');
            $("div.answer_steps").append('<div id="answer_step_description' + answer_identifier_number + '" class = "answer_step_description" contenteditable="true" placeholder="Enter A Description as to how this step was reached or how to solve the next step"></div>');
            $("div.answer_steps").append('<button id="remove_answer_step_button' + answer_identifier_number + '" class = "remove_answer_step_button">- Remove This Step</button>');

            answer_identifier_number++;
        });
    });

</script>

Enabling draggable functionality for the divs...


<script type = "text/javascript" language = "javascript">
$(function() {  
    $( "#answer_steps" ).sortable();
    $( "#answer_steps" ).disableSelection();
    cursor: move;
});
</script>

I still need to figure out how to reindex the names, but I believe I can handle that part. Thank you for your assistance so far.

Answer №1

If you're feeling frustrated and confused about drag and drop functionality, take a breather and check out this cool 'drag and drop' demonstration I created earlier. You can find it here: jsfiddle.net/RachGal/ahnx7kwc. It's a great way to understand how the whole drag and drop concept works - Rachel Gallen (@2 days ago)

Here's the HTML code snippet from the demonstration:

<div class="common">
<div class="container-fluid">
    <div class="row">
            <ul class="col-sm-3 col-md-2 sidebar nav nav-sidebar" >
            <li class="group" class="draggable" ><a href="#" class="list-group-item">
            <h4>
             dsad
             <br /><small>dsadsa</small>
             <br /><small>dsadsa</small>
            </h4>
          </a>
                </li>
                <li class="group" class="draggable"><h2>
                BAH
                </h2><br><small>hello</small>
            </ul>
         <div id="drophere" class="col-sm-9 col-md-9">MAIN PANEL</div>
    </div>
</div>

In addition, here is the Javascript code used in the demonstration:

$(".draggable").draggable();
var draggableArguments={
 revert: 'invalid',
 helper:'clone',
 appendTo: '#drophere',
 refreshPositions: true,
 containment: 'DOM',
 zIndex: 1500,
 addClasses: false
};

$('.group').draggable(draggableArguments);
$('.group').droppable();

$(".nav-sidebar").droppable({
 tolerance: "intersect",
 accept: ".group",
 activeClass: "ui-state-default",
 hoverClass: "ui-state-hover",
 drop: function(event, ui) {
    $(".nav-sidebar").append($(ui.draggable));
  }
});
$('#drophere').droppable({
 tolerance: "intersect",
 accept: ".group",
 activeClass: "ui-state-default",
 hoverClass: "ui-state-hover",
 drop: function(event, ui) {        
    $('#drophere').append($(ui.draggable));
  }
});
$('#drophere').sortable();

Last but not least, here is the CSS code from the demonstration:

.draggable {
  border: solid 2px gray;
}
.sidebar {
  position:fixed;
  width:200px;
  top: 51px;
  bottom: 0;
  left: 0;
  z-index: 1000;
  display: block;
  padding: 20px;
  overflow-y: auto;
  /* Scrollable contents if viewport is shorter than content. */
  overflow-x: visible;
  background-color: #f5f5f5;
  white-space: nowrap;
  border-right: 1px solid #eee;
  padding-left: 30px;
  padding-right: 30px;
}
/* Sidebar navigation */
.nav-sidebar {
  width:200px;
  height:100vh;
  margin-right: -21px;
  /* 20px padding + 1px border */
  margin-bottom: 20px;
  margin-left: -20px;
}
.group{width:150px;
  height:auto;
}

#drophere{width:700px;left:200px; height:100vh;}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"What is the best way to display a flash message upon successful completion of an AJAX request in Laravel

Is there a way to display a flash message after an ajax request redirects to a view? I'm having trouble getting the message to show up. Below is my code: Controller Code: \Session::flash('success', __('Password change successf ...

The Soundcloud ajax response failed to be delivered

I'm attempting to retrieve user data from SoundCloud using this query. Although I can see the successful call in the Chrome network tab after clicking, the JSON response is not reaching the javascript alert as expected. This is preventing me from addi ...

Show the name of the current user in a WordPress form using a readonly input field

How can I display the logged-in WordPress username (display name) in a form input field that is set to readonly? I have already checked out the Function Reference/wp get current user, but haven't had any success with it. Take a look at the code snip ...

What is the standard text displayed in a textarea using jQuery by default

My goal is to display default text in a textarea upon page load. When the user clicks on the textarea, I want the default text to disappear. If the user clicks into the textarea without typing anything and then clicks out of it, I'd like the default t ...

Refreshing a single div with a variety of potential hyperlinks

My knowledge of jQuery is limited, but I recently discovered a code snippet that should allow me to refresh only a specific div on my webpage: <script> $(document).ready(function(){ $(".reload").click(function(){ $("#day").load("/some_url #da ...

Displaying HTML content via Java Proxy Servlet

I have been using the code snippet below public class ProxyServlet extends HttpServlet { private static final long serialVersionUID = 1L; private final String USER_AGENT = "Mozilla/5.0"; public ProxyServlet() { super(); } ...

Guide to showing a preview of an image prior to submitting a form using vue.js

I created a Vue form but I'm having trouble making the image preview function work when users try to submit an image to the form. After refreshing the page, I can see the image, but when uploading it, the preview link is broken. There is an option to ...

Issue with binding background images to DIV elements in Angular 4 CSS

Here is a template example: <div [style.background-image]="profileImage" ></div> In the TypeScript file: We declare private profileImage: any; and use DomSanitizer for security. Fetching photo from service: We set this.profileImage using b ...

React not functioning properly when packaged with Webpack

I tried implementing React in the simplest way possible, but I am facing some issues. After bundling React and opening the index.html page, it shows up completely blank with no console errors to indicate any mistakes. Below is my webpack.config.js: const ...

Using Eloquent, you can easily fetch all row data and retrieve it using jQuery

I am currently working on a case study where I need to retrieve a row when an option is selected using jQuery. I also need to set the value of a textfield based on the ID of the selected option. However, I am facing difficulties in fetching all rows using ...

Does SCSS have a specific 'self' identifier?

I am looking to incorporate SCSS styles on the body by default, and then reapply them specifically to the P and LI tags (since I do not have complete control over the site and want to prevent plugins from interfering with my p's and li's). To ac ...

Evaluating the layout of a webpage with each new code update

I'm currently in search of a testing framework to evaluate the frontend and design aspects of my application. We are developing an Angular application and utilizing Protractor for end-to-end tests, but I am curious about how to test the visual design ...

Is it possible to assign a name attribute to the <img> tag in HTML?

Can the "name" attribute be used in an "img" tag in HTML? If you have this knowledge, please do share and thank you in advance. ...

Offspring containers fail to adjust in size relative to their parent container

I am working with a parent div that contains 5 child divs. The parent div does not fill the entire width of the window, but the 5 children share the same space and properly fill their parent. <div class="parent"> <div class="child ...

Accessing a file url with Firefox using protractor

I am currently facing a challenge with Protractor as I try to access an HTML file as a website using it. Whenever I attempt to do so, I encounter an error from Protractor stating: Failed: Access to 'file:///C:/filelocation/index.html' from s ...

Exploring the wonders of Vue.js and Laravel's type casting techniques

I have implemented DB2-style IDs for my database records in my Laravel 5.7 application, like this example: 201402241121000000000000. When trying to use it in my Vue component, I used the following syntax: <mycomponent v-bind:listing-key="{{ $listing-&g ...

How can I ensure the keyboard does not cover the text input in React Native?

I am trying to figure out how to keep the keyboard from covering the text input field and instead have it appear below. Every time I type something, the keyboard obstructs my view of the text box content. Any help in solving this issue would be greatly a ...

The browser is throwing errors because TypeScript is attempting to convert imports to requires during compilation

A dilemma I encountered: <script src="./Snake.js" type="text/javascript"></script> was added to my HTML file. I have a file named Snake.ts which I am compiling to JS using the below configuration: {target: "es6", module: "commonjs"} Howeve ...

Manipulate objects in three.js to always face the mouse pointer

It seems that despite my efforts, I am struggling with this task as I am relatively new to it. Surprisingly, I am not getting any errors in Dreamweaver. I've started fresh by integrating the look at function with the OBJ loader, camera, and lights in ...

Extending a type by adding properties from separate files using TypeScript

I am faced with a situation where I have a file containing either a type or interface variable (all of which are exported), and I need to add new properties to this variable from different files without using extends. Essentially, making changes to the sam ...