The purpose of this code is to create a customizable container that allows us to choose elements and adjust their properties. Unfortunately, the code is not functioning as intended

I am trying to create an editable container that allows us to easily select boxes for editing.

let SeconddivBox = document.getElementById("SeconddivBox");
let setCont = document.getElementById("setCont");

count = 0;
setCont.addEventListener("click",
    function () {
        count += 1;
        let containerBox = document.getElementById("containerBox").value;

        if (containerBox == "DivBoxS") {

            SeconddivBox.innerHTML += `<div class="DivClass" id="DivId${count}"></div>`

        }
    })

SeconddivBox.addEventListener("click",
    function (e) {
        let TargetedElement = e.target;
        let TargetedId = JSON.stringify(TargetedElement.id);
        if (TargetedId.includes('DivId')) {
            //  for set width of element which you are selected 
            let setW = document.getElementById("setW");
            setW.addEventListener("click",
                function () {
                    let widthValue = document.getElementById("widthValue").value;
                    console.log(widthValue);
                    TargetedElement.style.width = `${widthValue}px`;
                })
            return;
        }

    })
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

#FirstdivBox {
    border: 2px solid blue;
    width: 100vw;
    height: 20vh;
}

#SeconddivBox {
    border: 2px solid red;
    width: 100vw;
    height: 80vh;
    display: flex;
    justify-content: center;
    align-items: center;
}

#widthValue {
    border: 4px solid red;
}

.DivClass {
    width: 150px;
    height: 150px;
    border: 3px solid black;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0>
    <title>Editable Container</title>
    <link rel="stylesheet" href="custom-style.css">
</head>

<body>

    <div id="mainContainer">
        <!-- This is the editable container -->
        <div id="FirstdivBox">

            <select name="containerBox" id="containerBox">
                <option value="DivBoxS" id="DivBoxValue">Div</option>
            </select>
            <button id="setCont">
                Set-Container
            </button>

            <input type="text" id="widthValue">
            <button id="setW">
                Set Width
            </button>

        </div>
        
        <div id="SeconddivBox">
        </div>
    </div>
    <script src="main-script.js"></script>
</body>

</html>

However, I encountered a problem while coding - when selecting and editing one box, the properties apply to both instead of just the selected box. Any help would be appreciated!

Answer №1

Hopefully, this is the intended functionality of your code.

Please refer to the inline comments for detailed explanations.

// Variable initialization
let count = 0;
let setW = document.getElementById('setW');
let setCont = document.getElementById('setCont');
let SeconddivBox = document.getElementById('SeconddivBox');

// Event listener for container setting button click
setCont.addEventListener('click', function() {
  ++count; // Increment count by 1
  let containerBox = document.getElementById('containerBox').value;

  if (containerBox == 'DivBoxS') SeconddivBox.innerHTML += `<div class="DivClass" id="DivId${count}"></div>`;
});

// Event listener for second div box element click
SeconddivBox.addEventListener('click', e => {
  let TargetedElement = e.target; 
  // No need for JSON.stringify on id since it's not an object
  if (TargetedElement.id.includes('DivId')) {
    let selected = document.querySelector('.Selected'); // Flag for selected element

    if (selected) selected.classList.remove('Selected'); // Remove previously selected element
    TargetedElement.classList.add('Selected'); // Add a class to mark targeted element as selected
  }
});

// Event listener for set width button click
setW.addEventListener('click', () => {
  let widthValue = document.getElementById('widthValue').value;
  document.querySelector('.Selected').style.width = `${widthValue}px`; // Set width of selected element
});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

#FirstdivBox {
  border: 2px solid blue;
  width: 100vw;
  height: 20vh;
}

#SeconddivBox {
  border: 2px solid red;
  width: 100vw;
  height: 80vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

#widthValue {
  border: 4px solid red;
}

.DivClass {
  width: 150px;
  height: 150px;
  border: 3px solid black;
}

.DivClass.Selected {
  border: 3px solid red; /* Style for selected element */
}
<div id="amindivBox">
  <div id="FirstdivBox">
    <select name="containerBox" id="containerBox">
      <option value="DivBoxS" id="DivBoxValue">Div</option>
    </select>
    <button id="setCont">Set-Container</button>
    <input type="text" id="widthValue">
    <button id="setW">Set Width</button>
  </div>
  <div id="SeconddivBox"></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

Executing $(this).parent().remove() triggers a full page reload

A unique feature of my webpage is that with just a simple click of a button, users have the ability to dynamically add an endless number of forms. Each form contains fields for user input and also includes a convenient delete button. var form = " Name ...

What is the method in JavaScript to retrieve the current date with millisecond precision?

Is there a way in JavaScript to obtain the current date and time down to milliseconds? When using the new Date() method, it returns the time up to seconds like this: console.log(new Date()) LOGS - Thu Sep 07 2017 14:47:37 GMT+0530 (India Standard Time) W ...

Steps to resolve the white-dot border problem plaguing your dropdown menu

On my website, I've designed a drop-down menu with borders set to gray on the top, left, and right sides, while the bottom border is white. This creates a smooth, continuous border that looks great in FF3 and Chrome. However, after upgrading to FF4 o ...

Tips for enhancing the efficiency of your Node.js and Express.js code while steering clear of callback hell

One of the controllers in my application contains a method that is responsible for printing an array of URLs using the webshot package. Below is the code snippet in question: router.post('/capture', function (req, res, next) { //Check params ...

The parent div contains only non-div elements arranged in a single line

Here is the HTML code: <div style="background-color:rgb(81, 205, 50); display:inline-table; width:700px; height:150px; border: 2px solid black; padding: 2px;"> <img src="../rail_logo.png" width="150" height="150" style=" ...

Upgrading CSS sprite sheets for retina displays boosts image size by two-fold

I'm currently incorporating CSS sprite sheets into a mobile-friendly page design. The layout appears as intended, and below is the CSS I have implemented (which displays correctly on Chrome Canary's iPhone 3GS emulator): div#logo { backgroun ...

Utilizing the color input type to dynamically alter text color

Is there a way to create a script where changing the color in an input type=color would automatically change the text color as well? Appreciate any insight! ...

Is it truly necessary for Ajax actions to have their own unique URLs?

Occasionally, I come across the opinion that using the same URL for both non-Ajax and Ajax actions is not ideal. In my application, I have forms that are submitted with Ajax to enhance the user experience. However, these forms still function for users who ...

Trouble parsing a long JSON string with JSON.parse and angular.fromJson

I am attempting to replace the angularjs POST request with a standalone JSON response string. Previously, the angular GET / POST requests would automatically convert the response to JSON which worked perfectly. Now, I am trying to store the JSON response ...

Tips for implementing a multi-layered accumulation system with the reduce function

Consider the following scenario: const elements = [ { fieldA: true }, { fieldB: true }, { fieldA: true, fieldB: true }, { fieldB: true }, { fieldB: true }, ]; const [withFieldA, withoutFieldA] = elements.reduce( (acc, entry) => ...

The best approach for setting a select value and managing state in React using TypeScript

Currently, I am in the process of familiarizing myself with TypeScript within my React projects. I have defined a type for the expected data structure (consisting of name and url). type PokedexType = { name: string; url: string; } The API respon ...

I want to use flexbox to center three divs on my webpage

I am trying to align 3 divs inside a flex container in the center of the page with equal distance between them and also from the edge of the page. .container { display : flex; width : 60%; } .para { width : 33%; padding : 1em; borde ...

Using jQuery or JavaScript to adjust the bottom margin

Looking to Add Bottom Margin for Selection Box I have attempted the following CSS: #Selection { margin-bottom:23px; } Unfortunately, this method did not work for me. Is there a way to achieve this using JavaScript or jQuery? View Example on JsFiddle S ...

Tips for creating various instances of a single type within mock data

In my Schema.js, I have a simple schema and server setup: const typeDefs = gql` type Query { people: [Person!]! } type Person { name: String! age: Int! job: String } `; And here is my server configuration: const mocks = { Person ...

Why aren't NavBar Image Links Functional, even though the code seems flawless? What could be the issue?

Looking at the current HTML code snippet I have within the <head> section, it includes: <ul class="nav"> <li> <a href="http://www.greg-holmes.com/#/title" target="_blank"> <img src="img/home.png"> ...

Using PHP to create dynamic text within email messages

I'm currently working on creating dynamic email content, and I have successfully implemented a solution for images. However, I am facing difficulty when it comes to displaying text dynamically. The PHP code snippet below retrieves location data and r ...

What could be causing Rails 5.0.1 to add an iframe to my HTML, causing disruption to the links in the header navigation bar?

Currently, I am exploring the new features in Rails 5 by following Michael Hartl's tutorial for this version. Upon reaching the end of chapter 7, I observed that the links in the navigation bar only function when clicked below them. After inspecting t ...

Styling with CSS: Making a div's height fit within another div, including padding

Looking at the image, there seems to be a div with a width of 100% and no defined height. Instead, the height adjusts based on the content, with top and bottom padding in percentages. The issue arises when trying to place navigation buttons on the right si ...

Is there a CSS3 Selector With Similar Functionality to jQuery's .click()?

For a few years now, I have been utilizing a pure CSS navigation system. However, with the recent increase in mobile site projects at my workplace, I am encountering issues with drop-down menus not functioning properly on mobile devices. Despite this chall ...

Utilizing jQuery and html5 for manipulating the DOM with append()/appendTo() functions while taking

Instructions on Replicating: Begin by creating an html5 page. Ensure that you have included the script from remysharp.com/2009/01/07/html5-enabling-script/ so that Internet Explorer can recognize the tags. Add a hardcoded <section id='anyt ...