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>