Click on the paint app to change colors using JavaScript

Trying to create a Paint feature in JS, here's the code snippet. I am looking to change the color of the trail from black to red by clicking on the "red" div, but I'm running out of ideas (without jQuery).


let active = false;
const draw = function(e) {
  if (active == false) {
    return;
  }

  const x = e.clientX;
  const y = e.clientY;
  let div = document.createElement("div");
  div.style.top = y + "px";
  div.style.left = x + "px";
  document.body.appendChild(div);
}

const drawActive = function() {
  active = !active
}

function changeColor() {
  // Add logic to change color
}

document.getElementById("red").onclick = changeColor;
document.body.addEventListener("mousemove", draw);
document.body.addEventListener("mousedown", drawActive);
document.body.addEventListener("mouseup", drawActive);

body {
  height: 100vh;
  margin: 0;
}

#containter {
  width: 200px;
  height: 200px;
  border-radius: 0;
  background-color: #fff;
  position: fixed;
}

div {
  width: 5px;
  height: 5px;
  border-radius: 50%;
  background-color: #000;
  position: absolute;
}

#red {
  width: 25px;
  height: 25px;
  background-color: red;
  border-radius: 0;
  margin-top: 18%;
}

.blue {
  width: 25px;
  height: 25px;
  background-color: blue;
  border-radius: 0;
  margin-top: 6%;
  margin-left: 12%;
}
.
.
.
<!DOCTYPE html>
<html lang="en>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Paint</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <div id="container">
    <div id="red"></div>
    <div class="green"></div>
    <div class="blue"></div>
    <div class="yellow"></div>
  </div>
  <script src="script.js"></script>
</body>

</html>

Attempted using setAttribute method with some errors encountered.
Unsure about the required details for implementation.
Still figuring out which specifics are essential.

@Edit from review: resolved repetitions...

Answer №1

Using the querySelectorAll method, I searched for all div elements and implemented a condition

if (!document.getElementById("containter").contains(item)) 

to exclude content inside the div with the id container.

document.querySelectorAll('div').forEach(function (item) {
if (!document.getElementById("containter").contains(item))
    item.setAttribute('class', 'mainColor');
})    

let active = false;
const draw = function(e) {
  if (active == false || document.getElementById("containter").contains(e.target)) {
    return;
  }
  const x = e.clientX;
  const y = e.clientY;
  let div = document.createElement("div");
  div.style.top = y + "px";
  div.style.left = x + "px";
  document.body.appendChild(div);
}
const drawActive = function() {
  active = !active
}

function changeColor() {
  document.querySelectorAll('div').forEach(function(item) {
    if (!document.getElementById("containter").contains(item))
      item.setAttribute('class', 'mainColor');
  })
}
document.getElementById("red").onclick = changeColor;
document.body.addEventListener("mousemove", draw);
document.body.addEventListener("mousedown", drawActive);
document.body.addEventListener("mouseup", drawActive);
body {
  height: 100vh;
  margin: 0;
}

#containter {
  width: 200px;
  height: 200px;
  border-radius: 0;
  background-color: #fff;
  position: fixed;
}

div {
  width: 5px;
  height: 5px;
  border-radius: 50%;
  background-color: #000;
  position: absolute;
}

#red {
  width: 25px;
  height: 25px;
  background-color: red;
  border-radius: 0;
  margin-top: 18%;
}

.blue {
  width: 25px;
  height: 25px;
  background-color: blue;
  border-radius: 0;
  margin-top: 6%;
  margin-left: 12%;
}

.yellow {
  width: 25px;
  height: 25px;
  background-color: yellow;
  border-radius: 0;
  margin-top: 18%;
  margin-left: 12%;
}

.green {
  width: 25px;
  height: 25px;
  background-color: green;
  border-radius: 0;
  margin-top: 6%;
}

.first {
  background-color: red !important;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  position: absolute;
}

.mainColor {
  background-color: red !important;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  position: absolute;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Paint</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div id="containter">
    <div id="red"></div>
    <div class="green"></div>
    <div class="blue"></div>
    <div class="yellow"></div>
  </div>
  <script src="script.js"></script>
</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

Guide on showcasing an avatar or thumbnail image in Vue.js using Element UI after uploading

I'm currently working on a project that involves uploading pictures and displaying them as thumbnails or avatars after they have been uploaded. I've written the code below, which successfully uploads the picture, but I'm struggling to displa ...

How can I use Chart.js to assign a unique color to each x-axis label?

I'm currently using Chart Js to create a chart and I want each label to have a different color instead of all labels having the same color. Is there a way to achieve this using the ticks callback function? scales: { xAxes: [{ ...

Is there a way to assign a Ref to a button within a React component that I did not create myself? I need to be able to focus on it

Currently, I am developing a React application and collaborating with another team that provides us with a component containing a button. This component is a necessary dependency for our project. My goal is to have this button focused when a specific actio ...

Presenting a 24-column data table fetched from MySQL and integrated into a webpage through JavaScript DataTables

Greetings everyone! I have a query regarding Javascript DataTables and how it displays data from a MySQL table. Here's the MySQL query in question: select LOT_LOCATION, `Zone Attribute`, a.LOTID, Design_ID, ifnul(Board_ID,'') as Board_ID1, ...

javascript horizontal text scroll

I am trying to implement horizontal scroll on my app. I have come across several examples, but none of them seem to fit my specific needs. The code snippet below is one that I thought would work, but it's not functioning as expected. Can someone pleas ...

Object experiencing failure due to unsuccessful JSON call. Reference error: 'data' is not defined

Whenever I create a new object, it is supposed to retrieve data using jQuery's getJSON method and populate the object's properties with that data. However, instead of success, I encounter an error message saying: Uncaught Reference: data is not d ...

Looking to automatically populate input fields using AJAX?

Need help auto filling input bars with AJAX, encountering a small issue Below is the HTML code: <input type="text" name="url" id="url"> <input type="text" name="name" id="name"> <input type="text" name="catagory" id="catagory> When t ...

Ways to implement material-ui button design on an HTML-native button

I am using pure-react-carousel which provides me an unstyled HTML button (ButtonBack). I would like to customize its style using material-ui. Trying to nest buttons within buttons is considered not allowed. An approach that works is manually assigning th ...

Unable to successfully upload file using AJAX & PHP - the $_FILES array remains empty

I have scoured numerous online forums and Stack Overflow threads in search of a solution to my problem, but I am still unable to make it work. Despite having 5 years of experience working with jQuery and PHP, this is my first time delving into AJAX. Curre ...

Encountering a problem with scrolling the modal to the top

I am currently working on a code snippet that involves scrolling the modal to the top position. The purpose of this is to display form validation messages within the modal popup. Below are the jQuery code snippets that I have attempted: //Click event t ...

Angular directives enable the addition of DOM elements using ng functions

I'm currently working on creating a custom directive for a small input field that only accepts text. The goal is to dynamically change an icon from a search glass to an X if there is text in the input field, and clear the text when it is clicked on. I ...

How can I begin the process of developing a node command line script for duplicating a base website in the style of express?

Looking for advice on customizing the command line and node.js setup. Typically, when using express app, a folder named app is generated with all necessary files, then npm install and node app.js to run. However, I prefer using handlebars for templating ov ...

Combine an array of objects into a regular object

Imagine having an array structure as shown below: const student = [ { firstName: 'Partho', Lastname: 'Das' }, { firstName: 'Bapon', Lastname: 'Sarkar' } ]; const profile = [ { education: 'SWE', profe ...

CKEditor displays the return value of an object as `[object Object]

After enabling CKEditor for my textarea, I have encountered an issue where instead of displaying the typed text, CKEditor returns [object Object]. Can anyone assist me in troubleshooting this problem? I appreciate any guidance provided. I have utilized th ...

"Encountering an issue where the route function in Passport and ExpressJS is not being

When using passport for admin authentication, I am facing an issue where the redirect is not calling my function. Consequently, all that gets printed on login is [object Object] Here is my code: app.get('/admin', isLoggedIn, Routes.admin); ...

Getter and Setter Implementation in Typescript without Using Classes

Check out these various SO questions discussing Typescript getters/setters: from 2015, Jan 2018, Sept 2018, and more. Now, the question arises - what is the best approach to define Typescript types for getters/setters in a plain JavaScript object without ...

Preventing PHP Form Resubmission and Addressing Unusual Problems

Let's keep this brief. This is the code I've been working on: <?php if ($_POST['title'] != 'Title' && $_POST['date'] != 'Date') { $fileName = 'blog.txt'; $fp = fopen('blog.txt', &ap ...

What is the reason behind asp:Textbox occasionally appending "text" to the CSS class in the final HTML output?

Here's the code snippet: <asp:TextBox ID="txtAddress" CssClass="s175" runat="server" MaxLength="30" placeholder="Street"></asp:TextBox> After rendering, it looks like this: <input name="ctl00$LeftColumnContent$txtAddress" type="text" ...

Update the background of cell colors in Fullcalendar version 2.0.2

Currently, I am on a quest to find a solution that would allow me to alter cell backgrounds in fullcalendar based on availability or holidays. I have come across a few potential solutions: - elhigu/fullcalendar on github (+) - lcrodriguez/fullcalendar ...

Is it possible to assign a specific value to a row within a table?

For each row (tr) generated from my database, I would like to assign a unique row value. Let's consider the table being created: while ($row = $database->fetch_array($result)) { $i=1-$i; $class = "row".$i; echo "<tr class='{$class} produ ...