Ways to position divs without causing them to collapse or override existing divs

I am currently developing a demonstration in which users can select jQuery areas to create square blocks.

When a user selects an area and adds a comment with color, the entire block is displayed at a specific position. This feature is working perfectly as intended.

My main concern now is how to prevent someone from selecting an area that already contains existing blocks or selecting the same area again.

  1. Both blocks should exist.
  2. They should not be positioned at the same location.

Check out the demo here!

Answer №1

If you want to add multiple rectangles, the first step is either using a different id or setting up the newly created div directly:

    $('<div>')        
    .css({
      'position': 'absolute',
      'width': rectWidth,
      'height': rectHeight,
      'left': startX,
      'top': startY,
      'background': '#000000'
    })
    .appendTo(this);

Step 1.1 involves changing the position to absolute so that the next elements are not positioned relative to the previously added elements.

Step 2 focuses on preventing overlap. By utilizing the selectable feature, you can easily check if any elements are selected (any divs with the .ui-selected class) and avoid adding a new rectangle if any elements are currently selected within the stop event callback:

if($(".ui-selected", this).length) return;

Here is an example implementation that introduces a Rect object to manage positions and demonstrates the use of the demo class:

$(function() {

    var startingPosition;

    function getPosition(e){return {X:e.pageX, Y:e.pageY};}

    function Rect(start,stop){
        this.left = Math.min(start.X,stop.X);
        this.top = Math.min(start.Y,stop.Y);
        this.width = Math.abs(stop.X - start.X);
        this.height = Math.abs(stop.Y - start.Y);
    }   

    $('#target').selectable({
      start: function(e) {
          startingPosition = getPosition(e);
      },
      cancel: '.demo',
      stop: function(e) {        
          if($(".ui-selected", this).length) return;          
          var rectangle = new Rect(startingPosition,getPosition(e)); 
          $('<div>')        
              .css({
              'width': rectangle.width,
              'height': rectangle.height,
              'left': rectangle.left,
              'top': rectangle.top          
          })
          .addClass('demo')
          .appendTo(this);          
      }
    });
});

Check out the Demo fiddle here

As an extra tip, you can easily identify intersecting elements by coloring them red during selection:

.ui-selecting{
    background: red;
}

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

Obtaining targeted information from JSON using JavaScript

Extracting specific data from a JSON object can be challenging, especially if you are new to JavaScript. Below is an example of JSON data containing various fields: {"Date":"2021-01-31........ to ....10.9,"windDir":"SSE"} ...

VSCode is indicating a CSS error, requesting an at-rule or selector

I tried to implement a piece of CSS code I found on a website, but I'm encountering an error in this particular section .pricing-table:hover{ box-shadow: 0px 0px 19px -3px rgba(0,0,0,0.36); /*issue starts from this line*/ .pricing-table__button ...

Monitoring and recording the current line number during evaluation

Recently, I've been experimenting with eval to modify a $scope object named variables. This is the watcher I'm using: $scope.$watch(function () { return $scope.variables; }, function (variables) { console.log('changed!'); }, true) ...

A collaborative effort on Facebook, Twitter, and GooglePlus involves generating SCRIPT tags collectively

If you're familiar with the javascripts used by platforms like Facebook, Twitter, and Google Plus, you'll recognize them below. Here, I've simply organized them neatly together. How can I utilize jQuery to create the script tags and optimiz ...

"Create a notification pop-up in CSS that appears when a link is clicked, similar to

I am looking to create a model page that functions similarly to the inbox popup on Stack Overflow. When we click on the inbox icon, a small box appears with a tiny loader indicating messages or comments. The box then expands depending on the content inside ...

What is the reason for the vertex shader failing to compile?

Recently diving into the world of WebGl, I decided to experiment with a simple example. Here is how I set up my script: Here's my setup script import testVertexShader from './shaders/test/vertex.glsl' import testFragmentShader from './ ...

Are your user choices disappearing within jQuery duplication?

The context in which the issue arises is not crucial to understanding, but to give a brief overview: I am working on a form that has expandable sections where users can edit information and then collapse them. The form fields retain their state each time. ...

Issues with Angular HTML failing to load correctly

Greetings, I am seeking assistance with an issue that has been challenging me for quite some time. As a newcomer to Angular JS, I may be overlooking something obvious. Here is the scenario: I am utilizing ng-repeat on a directive in the following manner: ...

Changing ch to Px in CSS

Important Notes: I have exhaustively explored all the questions and answers related to this particular topic. The question I have is very straightforward: How many pixels are equivalent to 1 character? Here's a sample of my code - code Related Sear ...

What are the steps for implementing CSS in Markdown?

How can I incorporate a CSS class into a Markdown file? For example, using <i class="icon-renren"></i> (from the fontawesome library) should display an icon when its CSS file is imported in HTML. Is there a way to achieve this in Markdown? ...

"Enhance your online shopping experience with a React.js popup modal for

In the midst of developing a shopping cart, I find myself facing a challenge in making the modal pop up when clicking on the shopping cart icon. The semantic-ui documentation for modals has not provided clear instructions on achieving this functionality, s ...

Troubleshooting the Angular 7 mat-select issue caused by the "ellipsis" CSS property with three dots

I am facing an issue with a mat-select property called "ellipsis". The three points appear in a different color than the text itself. I attempted to change it to white using the following code, but the dots still remain black. ::ngdeep .example{ ...

How to fetch files using URL in JavaScript

I need a solution for automatically downloading multiple PDF files from Google Drive and Docs using their URLs with JavaScript code. I don't want to manually go to each link to download the files. Although I've researched various answers on Stac ...

The Datetimepicker component outputs the date in datetime format rather than a timestamp

Currently, I am utilizing the datetimepicker JavaScript script with specific implemented logic: <script> var today = new Date(); var dd = today.getDate(); var mm = today.getMonth(); var yy = today.getF ...

What troubleshooting steps should I take to address MQTT issues affecting the rendering of my website while using React and Raspberry Pi?

I am facing an issue where I cannot integrate mqtt with my react application on a Raspberry Pi 4. I am seeking assistance to resolve this problem. My setup includes: Distributor ID: Raspbian Description: Raspbian GNU/Linux 11 (bullseye) Release: 11 ...

How do I alter the post title font size with a child theme?

After updating my theme, I noticed that the H1 for my Posts titles in the "Next Posts" section changed to H4 unexpectedly. How can I revert it back to how it was before? I've attempted fixing it without success. If you need a visual reference, you ca ...

How can PHP be used to display a varying number of items in a slider depending on the size of the screen?

I am currently utilizing media queries to adjust the layout of my website. My query is: How can I display a different number of items in a slider based on the screen size? For small screens, I have included the following code: <?php if($i == 4) {echo ...

Constructing a table using an array in React

I need assistance with creating a table based on salary data for different sectors. I have an array with example data that includes currencies and sectors. const data=[ ['Euro','Tech'], ['USD','Tech'], ['GBX&apo ...

There seems to be a problem retrieving the JSON file

My JavaScript file is designed to fetch a JSON file and execute a function if successful. If there's an error, it should display an alert window with the message "error". However, despite checking the syntax, I keep receiving an error alert every time ...

Struggling to grasp the concept of PHP LZW decompression function within JSend framework

I am currently working on converting the LZW decompressor from PHP to JavaScript and I have encountered a function that is giving me some trouble. function decompressLZW(aCodes) { var sData = ''; var oDictionary = []; for (var i = 0; i &l ...