Tips for incorporating choices into a newly created dynamically generated div

In the process of creating a website builder, I encountered an issue. I need to allow users to add boxes dynamically to the main section and have related options appear when a box is clicked. The problem arises when multiple boxes are added: clicking on the first box causes the click function to execute twice, making the menu box fail to show up due to the toggle option. It seems like there might be an issue with the jQuery-ui libraries. Here's the code snippet that illustrates the problem:

var x_axis = 0; y_axis = 0;
$("#menubutton").mouseover(function(){
$("#menubutton").css("cursor","pointer");
});

// Create a new div in the main section
$("#menubutton").click(function(){
var totalChildren = $("#mainSection").children().length;
var id = totalChildren+1;
$("#mainSection").append("<div id='"+id+"' class='newDiv' style='background-color:white; border:2px solid black; width:100px; height:100px; position:absolute; left:"+x_axis+"px; top:"+y_axis+"px; z-index:1;'></div>");

  $(".newDiv").draggable({
      containment : 'parent',
      opacity: 0.5
  });

  // Click function for editing options of the div
  $(".newDiv").click(function(){
      divId = $(this).attr("id");

      $("#optionsMenu").toggle();
      alert(divId);
  });
});
#optionsMenu{
border: 1px solid black;
width: inline-block;
height: 500px;
position:absolute;
right: 10px;
top:50px;
z-index: 2;
padding: 10px;
display: none;
background-color: #14C4E4;
}

.buttonStyle{
border:1px solid green; 
color: white; 
background-color:5BDD45; 
text-align:center; 
border-radius:3px 3px 3px 3px;
position: relative;
left:0px;
padding: 5px;
display: inline-block;
}
<body>
<div class="button" >
<span id="menubutton" class="buttonStyle">Add Box</span>
</div>
<div class="col-md-10" id="mainSection">
<div style="border:1px solid black; height:400px; position:relative;">
</div>
</div>

<div id="optionsMenu">
<div id="boxOptions" style="z-index:2">
The options for the box will be shown here!
</div>
</div>
</body>

https://jsfiddle.net/44uyxLrh/7/

Answer №1

To improve the functionality of your code, make the following modifications:

var x_axis = 0;
y_axis = 0;
$("#menubutton").mouseover(function() {
    $("#menubutton").css("cursor", "pointer");
});

function toggleOption() {
    divId = $(this).attr("id");
    $("#optionsMenu").toggle();
    alert(divId);
}

// Creating a new div in the main section
$("#menubutton").click(function() {
    var totalChildren = $("#mainSection").children().length;
    var id = totalChildren + 1;
    $("#mainSection").append("<div id='" + id + "' class='newDiv' style='background-color:white; border:2px solid black; width:100px; height:100px; position:absolute; left:" + x_axis + "px; top:" + y_axis + "px; z-index:1;'></div>");

    $(".newDiv").draggable({
        containment: 'parent',
        opacity: 0.5
    });

    // For editing options of the div
    $('.newDiv').off('click', toggleOption);
    $('.newDiv').on('click', toggleOption);

});

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 text values with a colored background is a feature of the TextInput component in React Native

Seeking assistance with creating a login screen using React Native, featuring semi-transparent text input. Encountering a peculiar issue where typed text appears highlighted, even though it is not. Please see the screenshot below: (Unable to upload to img ...

Take a sequence of multiple words and combine them into a single string with hyphens in between

I've been working on a WordPress website and I created a JavaScript function that adds a class to the body tag, allowing for different backgrounds based on the category. It works perfectly fine when the category is a single word, but encounters issues ...

Slightly skewed 'outline' containing an odd number of dividers

I encountered a challenge while trying to create side-by-side elements with borders. I found that using the border property without adding some margin-hack made it difficult to achieve the desired look. Even when experimenting with outline or box-shadow, I ...

Angular version 1.6 with ES6, no errors in the application

Can you help me understand this? Note: I am using ui-router, and I suspect that is the issue. $stateProvider .state('login',{ url:'/', /*controller:'loginController',*/ controller: function(){aler ...

Tips for creating the ultimate footer section on your webpage

I'm trying to position the footer div (id="Footer") 10px from the bottom of the screen. Regardless of whether the page content fills the entire height of the screen or creates a scroll area, I want the div to always be at the very bottom with a 10px m ...

Refresh the view in AngularJS following a successful $http.get request

I have a <ul> in my HTML view that is populated based on a $http.get request. HTML: <div id="recentlyReleased" ng-controller="sampleRecordController as recCtrl"> <h1>Sample Records</h1> <ul> <li class= ...

Incorporate an onclick event to the elements within the array

I'm currently working on iterating over an array and adding an onclick event to each element. My goal is to be able to click on each div and have them log their values in the console. However, I am facing a challenge in applying the onclick event to e ...

Switching images with jQuery on a click event

Can anyone provide suggestions on how to swap images with the header image when icons in the footer are clicked? Here is a demonstration on Jsfiddle <ul> <li> <a href="#"> <img src="img/q.jpg&quo ...

What is the best way to access data from a static config.json file in TypeScript within a Vue component following the execution of a build:electron command in Vue CLI 3?

Hey there! I've been considering whether it's feasible to include a config.json file in a Vue CLI 3 project that can be dynamically read at runtime, both during development and production stages. This config.json file will hold key strings that ...

Display a division upon choosing an option

I am working on a project that involves a selection menu in the form of a drop-down list. <select> <option id="one" value="something">Car</option> <option id="two" value="anything">Plane</option> </select> Also, I ...

What are some ways to make the search bar on my website smaller in both length and width?

I have a WordPress website with the ivory search plugin installed for the search functionality. You can check out my website at www.osdoc.in. I am looking to make the search bar shorter and narrower as it is currently causing the menu icons to encroach on ...

Exploring table iteration in Angular 7

I am looking to create a table with one property per cell, but I want each row to contain 4 cells before moving on to the next row... This is what I want: <table> <tr> <td> <mat-checkbox>1</mat-checkbox& ...

Exploring the Contrast between Application and Local State Management in Redux

When looking at various examples of Redux, actions like SOME_ASYNC_ACTION_ERROR and SOME_ASYNC_PENDING are commonly used to manipulate the global state. However, it is hard to imagine a scenario where it would be logical for a component to be initially ren ...

The HTML slideshow is not automatically showing up as intended

I need to make a few adjustments to the picture slideshow on my website. Currently, all the pictures are displayed at once when you first visit the site, and it only turns into a slideshow when you click the scroll arrows. I want it to start as a slideshow ...

Node.js is much more than just wrong

Hey there, I have a Node.js issue that's giving me some trouble. Take a look at my code and the output below to see if you can help: if (currentPrice > variableData[i].stopLossHard) { console.log('if') console.log(currentPrice) ...

Are there methods to create a link that will open an application if it is already installed, or a website if it is not?

Similar Question: How can I check if a URL scheme is supported in JavaScript on iPhone Safari? Let's say my application is called "exapp" and I want to create a link on a website that can open the application if it is installed. If the user agen ...

My website appears distorted when the browser is zoomed out. What could be causing this issue?

Whenever I try to zoom out using Internet Explorer, the page doesn't zoom uniformly and ends up looking messy. Can someone please help me understand why this is happening? Here's how the page looks after zooming out (take a look at the three box ...

navigating a pointer graphic within a container

I've been working on creating a sniper game, but I've run into an issue with moving the sniper image inside the div. My main objective is to change the image to the sniper image when the mouse hovers over the div. Here's what I have tried so ...

Angular 6 and the intricacies of nested ternary conditions

I need help with a ternary condition in an HTML template file: <div *ngFor="let $m of $layer.child; let $childIndex=index" [Latitude]="$m.latitude" [Longitude]="$m.longitude" [IconInfo]="$childIndex== 0 ? _iconInfo1:$c ...

Connect a word in one QMD file to a word in another QMD file with a hyperlink

As I work on creating a Quarto book, I am looking to link key terms in the book to corresponding definitions in a glossary. The challenge is to ensure that these links function properly in both HTML and PDF formats. Below are some methods I have explored s ...