Generating numerous div elements with jQuery's zIndex property

While attempting to create a function that runs on the $(document).ready() event and is supposed to generate a new div, I encountered an issue. Whenever I try to create another div with the same DOM and Class attributes but in a different position, a problem arises...


//Adjusting z-index in css for multiple notes
var zIndex = 10000;
function updateIndex(element){
zIndex = zIndex+1; //Counter, '++' = +1
$(element).css('z-index', zIndex);
}


$("div .makeNew").on("click", function(e) {
updateIndex(this);
});
$(".note input textarea").on("click", function(e) {
updateIndex(this);
});



function MakeNewNote(){
zIndex = zIndex + 1;
$('#content').css('z-index', zIndex).append("<div class="note" ><div id="controlsTop"><div class="deleteNote">X</div><div class="makeNew">+</div></div><input value="My Note" /><textarea value="I Have something to save" cols="20" name="S1" rows="1"></textarea><div id="controlsExtra hidden"><div class="controlBold"></div><div class="controlItalic"></div><div class="controlUnderlined"></div><div class="controlLeft"></div><div class="controlCenter"></div><div class="controlRight"></div><div class="controlBigFont"></div><div class="controlSmallFont"></div></div> <!-- controlsExtra --></div> <!-- note -->");
$('.note').draggable();
}

function DeleteThisNote(){
$('.note').remove();
}

$(document).ready(MakeNewNote); // Creates a note just at startup

$(document).ready(function(){
$('div .makeNew').on('click', MakeNewNote); // Creates a new note, enables button press inside the note 

$('div .deleteNote').one('click', DeleteThisNote); // Removes current note

});
/* CSS DOCUMENT */
/* Author: John Doe */
/* Description: Main style for Sticky Notes */
/* Licensed to Example Company All rights reserverd 2022 */

.note {
width: 200px; height: 200px;
background:#FFFFCC;
margin:15px;


}

.note .controlsTop {
background:#FFFF66;
padding-top:50px;
margin-left:10px;
}

.note .controlsTop .deleteNote {
width:10px;
display:block;
float:left;
margin-left:5px;

}

.note .controlsTop .makeNew {
width:10px;
display:block;
float:left;
margin-left:5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
  // Should output here
  </div>

Answer №1

Here are a couple of adjustments that can resolve the problem:

Firstly, only apply the draggable() function to the newly added div.note, not all existing ones: Update from $('.note').draggable(); to:

$('.note').last().draggable();

Secondly, remove the specific div.note element as needed: Adjust from $('.note').remove(); to:

$(this).closest('.note').remove();

Additional Information

For elements created after the initial DOM ready event, use delegated events for proper functionality:

$('#content').on('click', 'div .makeNew', MakeNewNote);

$('#content').one('click', 'div .deleteNote', DeleteThisNote);

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

What could be causing my js.erb file to not function properly?

Here is the code snippet I am working with: file.js.erb alert("Alert"); main.js jQuery.ajaxSetup({ 'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")} }) jQuery.fn.submitWithAjax = function() { this.submit( ...

Improve the way you manage return statements

Here is the function in question: const checkifHaveBomb = (column, row) => { let isBomb = false activeBombContainer.forEach(element => { if (element.column === column && element.row === row) { ...

The spinal cord of design inquiry

I am currently working on a Backbone view called MainMenuView. Within this, the MainMenuModel consists of an array of sub-models known as ItemModel. The main menu is divided into two pages and includes next and previous buttons for navigation. The first pa ...

populate 3 input fields using the dropdown menu with the help of AJAX

Hello, I am new to PHP and Ajax. I have a select box where users can choose an option, upon which information should automatically fill in four text boxes. Someone recommended using jQuery my initial code. Here is my PHP code: if(isset($_GET['userna ...

What is the correct way to include viewport width in pixels using CSS?

My div is set to a width of 50vw with padding of 25px on all sides. I am looking to add a fixed element to the right of it by increasing its width by 50vw and adding 25px. Can this be achieved using only CSS, or should I consider using Less? If so, how c ...

Is there a way to detect when the browser's back button is clicked?

As I work on supporting an e-commerce app that deals with creating and submitting orders, a user recently discovered a loophole wherein they could trigger an error condition by quickly pressing the back button after submitting their order. To address this ...

Tips for testing nested subscribe methods in Angular unit testing

FunctionToTest() { this.someService.method1().subscribe((response) => { if (response.Success) { this.someService.method2().subscribe((res) => { this.anotherService.method3(); }) } }); } Consider the following scenario. ...

Sending a piece of state information to a different component

Hey, I'm a new React developer and I'm struggling with a particular issue. I've included only the relevant code snippets from my app. Basically, I want to retrieve the data from the clicked Datagrid row, send it to a Dialog form, and then p ...

The email message content is not displaying correctly

I'm in the process of merging multiple HTML tables into a single $message, which will then be passed to the email body as shown below. // Sending the email if(smtp_mail($To,$cc, $Subject, $message, $headers)) { echo "Email Sent"; } else { echo "An ...

Error: React Component not rendering correctly - Element Type Invalid

React Uncaught Error: Element type is invalid Encountering a problem in my React application where the following error message appears: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite compone ...

Exploring the intricacies of debugging async/await in Node.js with the help of

Having trouble debugging an "await" instruction in my async function. Every time I try, a promise is returned instead of the expected value. I've noticed there's supposed to be an "Async" button where the red square is located in this picture but ...

Is it possible to change a particular data attribute value?

Is there a way to change the value of "foo" in this specific element? <div id="my-element" data-request-data="bar: 1, foo: 2"> I attempted: $('#my-element').attr('data-request-data.foo', 5); However, this me ...

Setting up the react-ultimate-pagination component

I've been experimenting with the react-ultimate-pagination package available at: https://github.com/ultimate-pagination/react-ultimate-pagination My goal is to configure it in a way similar to their basic demo showcased here: https://codepen.io/dmytr ...

Node.js population process

Hello, I am currently exploring Node.js and facing an issue with the populate() method. My goal is to populate the user model with forms. Here is the structure of the model: const UserSchema = new Schema({ firstName: { type: 'string&a ...

Looping Issue in WordPress

Here is the code snippet I am currently working with: <?php query_posts("order=ASC&cat=4"); ?> <?php if(have_posts()): while(have_posts()): the_post(); ?> <?php if(get_post_custom_values("show") != NULL): ?> ...

Preventing parent requests from being triggered when a child element is clicked in Angular 2

I have a similar code structure as shown below and I am trying to achieve the behavior where clicking on the Child Div does not trigger the Parent Div click event. <div class="parentDiv" (click)="parentDiv()"> <div class="childDiv" (click)="ch ...

How can a callback be properly passed in programming?

My coding approach is outlined below: var CustomLibrary = (function (window, $, undefined) { return { URI: 'http://testpage/API/', OnSuccess: function (data, status) { }, OnError: function (request, status, error) { } ...

Sending data using formData across multiple levels of a model in Angular

I have a model that I need to fill with data and send it to the server : export interface AddAlbumeModel { name: string; gener: string; signer: string; albumeProfile:any; albumPoster:any; tracks:TrackMode ...

Adjusting the value of a user form with multidata in PHP and Javascript

I am looking for guidance on how to modify the value of an input in a form that contains multiple data entries. Here is my form: <form method="post" action="pax-flight.php#pax-flight" class="paxform"> <input type="hidden" value="{"data":{"us ...

Does React trigger a re-render when setState is called even if the state value remains unchanged?

Imagine I create a React component with an initial state of {random: 1}. Now, if I were to execute the following code: this.setState({random: 1}) Would this action result in triggering a re-render of the component? Furthermore, is there a method to avoid ...