Switching the selection with the div

My goal was to create a selection of divs that could be clicked and then manipulated collectively by moving the mouse over them.

Starting with just one div for testing, I encountered an issue when clicking and moving the mouse too quickly. The cursor changed to no-drop, and the function wouldn't execute unless I clicked again.

Below is the code snippet:

boxes = document.querySelectorAll('.box');
let itemList = [];
let selectedList = []; 
//I created selectedList to allow for multiple selections in the future.

for (let box of boxes) {
  itemList.push(box);
  box.addEventListener("mousedown", mousedown);
};
//Each box listens for mousedown events and is added to itemList.

function mousedown(e) {
  item = e.target;
  deselectAll(); //Deselect all divs if one is clicked
  
  item.selected = true; //Select the clicked div
  selectedListUpdate(); 

  window.addEventListener('mousemove', mousemove);

  function mousemove(e) {
    for (let item of selectedList) {
      item.style.background = getRandomColor();
      //This function changes the background color of all selected items as the mouse moves.
      //In the future, this will be updated to allow for dragging functionality.
    };
  };

  window.addEventListener('mouseup', mouseup);

  function mouseup(e) {
    window.removeEventListener('mouseup', mouseup);
    window.removeEventListener('mousemove', mousemove);
  }; //Stopping the effects of mouse movement after releasing the click while keeping items selected
};

function selectedListUpdate() {
  selectedList = itemList.filter(x => x.selected == true);
  for (let x of selectedList) {
    x.style.outline = "white solid 2px";
  };
  unselectedList = itemList.filter(x => x.selected == false)
  for (let x of unselectedList) {
    x.style.outline = "0";
  };
}; //Outline every item in selectedList

function deselectAll(e) {
  for (x of itemList) {
    x.selected = false;
  };
  selectedList = [];
}; //Reset selectedList


function getRandomColor() {
  let r = Math.floor((Math.random() * 155) + 100);
  let g = Math.floor((Math.random() * 155) + 100);
  let b = Math.floor((Math.random() * 155) + 100);
  return `rgb(${r} ${g} ${b})`;
}; //Example of function executed while mouse is moving
body {
  margin: 0px;
  background: #333;
}

.box {
  margin: 10px;
  background: white;
  width: 100px;
  height: 100px;
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>TEST</title>
</head>

<body>

  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>

</body>

</html>

Answer №1

Perhaps preventing the drag event on the boxes could be a solution?

boxes = document.querySelectorAll('.box');
let itemList = [];
let selectedList = []; 
//I created selectedList to handle multiple selections in the future.

for (let box of boxes) {
  itemList.push(box);
  box.addEventListener("mousedown", mousedown);
  box.addEventListener("dragstart", dragStart);
};
//Each box listens for mousedown and is added to itemList.

function mousedown(e) {
  item = e.target;
  deselectAll(); //First, deselect all divs if one of them is clicked
  
  item.selected = true; //Then, select the clicked div
  selectedListUpdate(); //Update selectedList to track selected items

  window.addEventListener('mousemove', mousemove);

  function mousemove(e) {
    for (let item of selectedList) {
      item.style.background = getRandomColor();
      //This function will modify all items in selectedList when the mouse moves.
      //Later, I plan to update this function to enable dragging the div.
    };
  };

  window.addEventListener('mouseup', mouseup);

  function mouseup(e) {
    window.removeEventListener('mouseup', mouseup);
    window.removeEventListener('mousemove', mousemove);
  }; //When releasing the mouse, further mouse movement should not have any effect but selected items remain selected
};

function dragStart(e) {
  e.preventDefault();
  return false;
}

function selectedListUpdate() {
  selectedList = itemList.filter(x => x.selected == true);
  for (let x of selectedList) {
    x.style.outline = "white solid 2px";
  };
  unselectedList = itemList.filter(x => x.selected == false)
  for (let x of unselectedList) {
    x.style.outline = "0";
  };
}; //Outline every item in selectedList

function deselectAll(e) {
  for (x of itemList) {
    x.selected = false;
  };
  selectedList = [];
}; //Reset selectedList


function getRandomColor() {
  let r = Math.floor((Math.random() * 155) + 100);
  let g = Math.floor((Math.random() * 155) + 100);
  let b = Math.floor((Math.random() * 155) + 100);
  return `rgb(${r} ${g} ${b})`;
}; //Example of function to execute when mouse is moving
body {
  margin: 0px;
  background: #333;
}

.box {
  margin: 10px;
  background: white;
  width: 100px;
  height: 100px;
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>TEST</title>
</head>

<body>

  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>

</body>

</html>

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

Displaying HTML with the code represented as text rather than executing the function

I'm a beginner at website development, with only basic knowledge of C++. I have some code in HTML that I've been experimenting with: <html> <body> <script type="text/javascript" src="http://localhost/Coin/wp-content/uploads/custom ...

Steps for automatically returning to the home page after using the browser back button while on a specific page

Currently in the process of developing a flight reservation website using the MERN stack. Upon reaching the final confirmation page, users are presented with a receipt and their flight ticket. I am searching for a way to redirect users back to the homepa ...

The JQuery event listener is functioning properly when triggered from the console, but not when called from a

Here is the function I am working with: () => { console.log('before'); $('#scope_limit_toggle').change((e) => { console.log('from event'); }); } The element that the event is ...

What is the best method for selectively removing elements within an <a> tag?

Is there a way to selectively remove elements within an <a> tag without removing the entire tag itself (similar to how unwrap() works)? For example, I have the following code: <a href="#page1" class="link" id="page1link" onclick="return false"> ...

What is the best way to transfer a variable from an iframe to its parent window?

My colorbox parent page includes a TabContainer with various iFrames, and in the case of the second tab, a change is made to the database that requires updating a textbox on the parent window. ...

Struggle to link a string together effectively for proper concatenation

I'm currently working on a project that involves utilizing the Wikipedia API. My goal is to create a link for each list item, but I'm encountering difficulty with proper concatenation. Here's the code snippet I'm using: for (var j=0 ...

Tips for showing and modifying value in SelectField component in React Native

At the moment, I have two select fields for Language and Currency. Both of these fields are populated dynamically with values, but now I need to update the selected value upon changing it and pressing a button that triggers an onClick function to update th ...

Struggling with incorporating a lightbox within an accordion feature in an .html file

I'm currently attempting to integrate this lightbox into this accordion feature. Individually, I've managed to get both elements up and running smoothly. However, when trying to combine them on the same page (regardless of nesting one inside the ...

What is the process for converting a canvas to an image and uploading it to Flask?

Hey there, I have a question regarding uploading a resized canvas image as a file to Flask. Initially, I attempted to use the canvas.toDataURL() method to convert it into a base64 string and then uploaded it as an image using formdata with AJAX, but unfor ...

Is jQuery automatically loaded in laravel 6? I keep encountering an uncaught type error

Everything was going smoothly with my project until I added authentication. Following the documentation here, I used composer to require laravel/ui and then did php artisan ui vue --auth. Prior to implementing authentication, the scripts were loading corr ...

Repeating promises resolutions yields stagnant outcomes

Within my Angular project, I am working with two distinct components. parent.component.ts mypromise = this.httpClient.get<any>('http://localhost').toPromise() parent.component.html <app-children #child [promise]="mypromise"></a ...

What is the best way to send data back to a separate JavaScript file in ExtJS when working with records in a

I'm currently working on implementing a pop-up editing feature on a grid in extjs4. Progress so far includes successfully transferring the grid record to a popup panel located in a separate JavaScript file using the following code: handler: function( ...

Tips for creating a jquery modal form that can be reused

I currently have the following files : *vehicule_parc.php :* <script language=javascript src="../js/vehicule_parc.js"></script> <h3 class="headInfoBox" id="cch">Fuel Consumption >></h3> <hr /> <div id="cc"> ...

Using Jquery to toggle the visibility of div elements with the same structure, but ensuring only one is

Many people have posed this question. I am attempting to create a functionality where a div can expand and collapse using a +/- button. I have 5 divs with class=="expanderContent". When the function below is triggered by a click, all 5 items expand or coll ...

JSON Collaborator Tool

I really enjoy using the online json viewer at jsonviewer.stack.hu Does anyone know of a website that allows for sharing parsed json similar to sites like jsbin.com or jsfiddle.net ...

Collaborating on interconnected documents: population dynamics and sophisticated modeling techniques

As someone who is fairly new to these technologies, I'm unsure if I am doing this correctly. I am attempting to display the name of the category in the table instead of the id (which is from the ObjectId schema field) for all the Category documents r ...

Encountered an issue when trying to retrieve data for row 0 - requested parameter '0' is missing from the data source

I keep receiving the above warning message every time I run the following code. Javascript $(document).ready(function () { var $lmTable = $("#information").dataTable({ "sPaginationType": "full_numbers", "sSc ...

verified firebase/firestore requests

I've been struggling with the process of sending authenticated firebase/firestore calls. I set up firestore in my web app using Next.js as shown below: import { initializeApp } from "firebase/app"; import { getFirestore } from 'firebase ...

Can someone explain the significance of this error message in Redux - Toolkit?

Encountered this error message while working with Redux-Toolkit, could someone explain its meaning? name:"ConditionError" message:"Aborted due to condition callback returning false." ...

What is the technique for showcasing a collection of <v-img> elements with the v-for directive?

Hey there, hope you're all doing well. I'm curious about how to use the v-for method in Vue js to display a list of images. For example, if I have code that looks like this: <v-flex> <h4>{{$translate('bz_doc_path') ...