Using bootstrap can alter the positioning of elements that have margins relative to other elements

After exploring suggestions from my previous post on Stack Overflow, I have implemented a modified version to animate drag movements. While the HTML5 draggable attribute can achieve dragging, its limitations and side effects are something I aim to avoid.

(function() {
    let targets = document.querySelectorAll('.draggable');
    let offsetX;
    let offsetY;
    Array.prototype.map.call(targets, (target) => {
        target.isMouseDown = false;
        target.initialOffsetLeft = target.offsetLeft;
        target.initialOffsetTop = target.offsetTop;
        target.addEventListener('mousedown', (e) => {
            if (e.buttons === 1) {
                target.style.zIndex = 10000
                target.style.position = 'relative';
                target.isMouseDown = true;
                offsetX = target.initialOffsetLeft + e.offsetX;
                offsetY = target.initialOffsetTop + e.offsetY;
            }
        });
        document.addEventListener('mouseup', (e) => {
            e.preventDefault();
            target.style.zIndex = null
            target.isMouseDown = false;
            target.style.left = 0 + 'px';
            target.style.top = 0 + 'px';
        });
        document.addEventListener('mousemove', (e) => {
            e.preventDefault();
            if (target.isMouseDown) {
                target.style.left = e.pageX - offsetX + 'px';
                target.style.top = e.pageY - offsetY + 'px';
            }
        });
    });
})();
 

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Roboto', sans-serif
}

.draggable {
    display: flex;
    padding: 10px 12px;
    margin-bottom: 11px;
    border-radius: 5px;
    margin-right: 5px;
    background-color: #000000;
    cursor: grab;
    flex-grow:1;
    color: #ffffff;
    border: 1px solid #6c757d;
}

.group.card {
    margin-top: 30px;
    background-color: #000000;
    margin-right: 2%;
    margin-left: 2%;
    border: 1px solid #6c757d;
}
 

<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="22404d4d56515650435262170c100c11">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div class="group card">
    <div class="card-body">
        <div class="draggable">
            Lorem ipsum dolor sit amet 1
        </div>
        <div class="draggable">
            Lorem ipsum dolor sit amet 2
        </div>
        <div class="draggable">
            Lorem ipsum dolor sit amet 3
        </div>
    </div>
</div>

As observed in the code snippet above, when any of the .draggable elements are dragged, they shift downwards and rightwards. However, this behavior stops when either removing Bootstrap or eliminating all margins in the following:

.group.card {
    /*margin-top: 30px;*/
    background-color: #000000;
    /*margin-right: 2%;*/
    /*margin-left: 2%;*/
    border: 1px solid #6c757d;
}

By making these adjustments, the drag function works correctly. What could be causing this issue and how can it be resolved?

Answer №1

Give Your Class a Unique Name

To prevent conflicts with existing classes in Bootstrap, I suggest naming your class something distinct like "custom-card-group".

(function() {
  let targets = document.querySelectorAll('.draggable');
  let offsetX;
  let offsetY;
  targets.forEach ((target) => {
    target.isMouseDown = false;
    target.initialOffsetLeft = target.offsetLeft;
    target.initialOffsetTop = target.offsetTop;
    target.addEventListener('mousedown', (e) => {
      if (e.buttons === 1) {
        target.style.zIndex = 10000
        target.style.position = 'relative';
        target.isMouseDown = true;
        offsetX = target.initialOffsetLeft + e.offsetX;
        offsetY = target.initialOffsetTop + e.offsetY;
      }
    });
    document.addEventListener('mouseup', (e) => {
      e.preventDefault();
      target.style.zIndex = null
      target.isMouseDown = false;
      target.style.left = 0 + 'px';
      target.style.top = 0 + 'px';
    });
    document.addEventListener('mousemove', (e) => {
      e.preventDefault();
      if (target.isMouseDown) {
        target.style.left = e.pageX - offsetX + 'px';
        target.style.top = e.pageY - offsetY + 'px';
      }
    });
  });
})();
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Roboto', sans-serif
}

.draggable {
  display: flex;
  padding: 10px 12px;
  margin-top: 0px;
  margin-left: 0px;
  margin-bottom: 11px;
  border-radius: 5px;
  margin-right: 5px;
  background-color: #000000;
  cursor: grab;
  flex-grow: 1;
  color: #ffffff;
  border: 1px solid #6c757d;
}

.custom-card-group {
  margin-top: 30px;
  background-color: #000000;
  margin-right: 2%;
  margin-left: 2%;
  border: 1px solid #6c757d;
}
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d5f5252494e494f5c4d7d08130f130e">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" />
<div class="card group">
  <div class="custom-card-group">
    <div class="card-body">
      <div class="draggable">
        Lorem ipsum dolor sit amet 1
      </div>
      <div class="draggable">
        Lorem ipsum dolor sit amet 2
      </div>
      <div class="draggable">
        Lorem ipsum dolor sit amet 3
      </div>
    </div>
  </div>
</div>

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

Troubleshooting the issue of AngularJs location.path not successfully transferring parameters

My page has a Login section. Login.html <ion-view view-title="Login" name="login-view"> <ion-content class="padding"> <div class="list list-inset"> <label class="item item-input"> <input type="te ...

Enhancing the Appearance of Legends in Chartjs

I'm attempting to customize the legend in my Chartjs chart, but I'm facing an issue where I can't seem to change the font color. What I want to achieve is having the font color in white while keeping the individual item colors intact in the ...

What is the connection between importing and using destructuring in ES6 syntax?

Bring in: import React, { Component } from 'react'; Unpacking: let z, { b } = {a: 1, b: 2, c: 3} Both of these examples seem to have similar syntax. However, in the second example, z will be undefined instead of {a: 1, b: 2, c: 3}. Does this ...

Emphasizing specific lines using an array

There is a block of text containing multiple lines, each wrapped within a span with an incremented value at the end (like line-1, line-2, line-3, and so on) to distinguish between them. <div id="textbody"> <span id="line-1">what is love< ...

Is it better to overwrite past values in CSS or to duplicate rules?

Which one of these CSS code practices is considered better? A - concise and rewritten: @media only screen and (min-width: 480px) and (max-width: 960px) { h1, h2, .header, .widget, .copyright { position: static; width: 100%; height: auto; ...

Steps to create a fixed navigation bar at the top of the page

Is it possible to create a navigation bar that remains fixed at the top of the page? I'm not referring to using the "position: fixed;" property... The issue with my current navbar is that when zooming out, it loses its position at the top... How ca ...

Determine the percentage between two different dates

I am looking to calculate the percentage difference between two dates, considering only hours for scaling. For example: 22-08-2017 09:00 as the start date, 30.09.2017 22:00 as the finish date, Today's date is 01.09.2017. When I check the system toda ...

Could you display the picture prior to the function commencing?

This is the image that needs to be loaded before the loop begins. <div id="attendenceGridDivLoader" style="display:none"> <img src="<?php echo base_url() . 'images/loader.gif'; ?>" /> </div> <select onchange=checkAll ...

The issue of footer overlapping the login form is observed on iOS devices while using Safari and Chrome

Unique ImageI am currently working on an Angular 8 project with Angular Material. I have successfully designed a fully functional login page. However, I am encountering a problem specifically on iOS devices such as iPhones and iPads, whether it is Safari o ...

Modifying JavaScript Objects

After referring to the discussion at , I encountered a challenge with my javascript ajax function that retrieves JSON data. My goal is to trigger different js events based on the key-value pairs of the JSON response, but unfortunately, I am facing diffic ...

Transferring information from MySQL to Vue.js data attribute

I have retrieved some data from MySQL and I am looking to integrate it into a vue.js data property for seamless iteration using v-for. What is the ideal format to use (JSON or array) and how can I ensure that the data is properly accessible in vue.js? &l ...

Guide on including the angular value (id) in conjunction with repeating data-target for executing a function

I have the following code snippet. Now, I am trying to pass a dynamic AngularJS variable, specifically the id of a repeating list. The button in question is used for deactivation purposes, and upon clicking it, a confirmation box pops up. Upon confirming ...

Unable to remove unnecessary shapes in a three.js project

In this simple example, I am adding a THREE.SphereGeometry to a THREE.Group and then including the group in the scene. After rendering the scene, my goal is to eliminate the group from the scene and dispose of the geometry. <html> <head> < ...

invoking both componentDidMount and componentDidUpdate within the identical code block

componentLifeCycleMethod() { let data ; axios.get('http://localhost:8000/wel/') .then(res => { data = res.data; this.setState( { details: data }); }) .catch(err => {}) } I am looking to opt ...

Error: The lambda response was not defined. Please review your function code. The response returned with a status of 500 in 583 milliseconds

https://i.sstatic.net/GUHr9.png I'm experimenting with Netlify and its Lambda function feature to execute a Node.js function. Following the guide at https://css-tricks.com/using-netlify-forms-and-netlify-functions-to-build-an-email-sign-up-widget/. ...

How can I troubleshoot the 'mdDialog console error' that says 'cannot read property element of null'?

Two of my templates are named Left_template_view_html and center_template_view_html When I click on a md-button in the Left_template_view_html I am attempting to display an mdDialog on the document.body What should I pass into the parent parameter: angu ...

Retrieve the background color using code-behind

Despite its humorous appearance, I am having trouble with the Syntax :( I have a background color in my code behind file and need to correct the syntax here so that my Table displays the correct background color: <Table style="background-color:" &apos ...

Choose an input element from an iframe using jQuery

Can anyone assist me with selecting an input field from an iframe using jQuery? The structure of the iframe is as follows: <iframe src="https://checkout.klarna.com" id="klarna-checkout-iframe" name="klarna-checkout-iframe" class="kloading" scrolling="n ...

What steps might one take to address the undefined property error in node.js?

Facing an error message that says: Cannot read property 'title' of undefined Everything was functioning properly when using posts.forEach for traversal. However, encountered issues when switching to a for loop. Can anyone provide assistance? H ...

Create spinning wheel - canvas

Hey there! I'm trying to create a cool spinning wheel using a canvas and JS. My wheel is supposed to have 10 segments, each saved as a .png file. https://i.sstatic.net/glN1p.jpg In order to achieve a "full circle", I want to draw these 10 segments i ...