Create a custom div by clicking a button

I have been working on a fun web project where users can click a button to add sticky notes to a page. Here is the HTML code for a single sticky note:

<div class="sticky_note">
    <div class="title">
      <input type="text" name="title" placeholder="My Title"><span class="close">x</span>
    </div>
    <div class="content">
      <textarea name="note" placeholder="Type here..."></textarea>
    </div>
</div>

I am facing some challenges in adding multiple sticky notes whenever the user clicks the add button. Any advice or suggestions would be greatly appreciated. Thank you!

Answer №1

If you want to create an html element using a button, you can follow this example:

var newDiv = document.createElement('div');
newDiv.id = 'box'; //you have the option to set properties for the element.

var headerDiv = document.createElement('div');
headerDiv.id = 'boxHeader';
newDiv.appendChild(headerDiv);
document.body.appendChild(newDiv);

This piece of code adds a new div inside another main container. Feel free to try it out!

Answer №2

let createStickyNote = $('.sticky_note')[0].outerHTML;
$('#addBtn').on('click', function(){
  let $stickyNote = $(createStickyNote);
  $stickyNote.appendTo($('.sticky_notes_container'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sticky_notes_container">
<div class="sticky_note">
    <div class="title">
      <input type="text" name="title" placeholder="My Title"><span class="close">x</span>
    </div>
    <div class="content">
      <textarea name="note" placeholder="Type here..."></textarea>
    </div>
</div>
</div>
<button id=addBtn>Add</button>

Answer №3

If you have all of this content within a main container, simply ensure that the

var code=<div class="sticky_note">...</div>
code is stored as a string and then utilize

$("container").append(code);

Answer №4

If you want to create a new div, simply use the code below:

document.createElement("div")

You can then customize your new div by adding text and classes. For more details, check out w3school.

Based on your requirement, it seems that clicking on a button will generate a sticky note.

Consider using Element.cloneNode() for efficiency. This method allows you to duplicate a pre-designed div structure multiple times.

Check out this link for more information: http://www.w3schools.com/jsref/met_node_clonenode.asp

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

Retrieve a list of records from the database using jQuery and AJAX

I recently designed a webpage using Bootstrap. On this page, I have a section where records (titles) are fetched from a MySQL database using PHP, not jQuery or Ajax. I want to be able to select one of these records and have the related sub-records automati ...

Choose an Option that Does Not Allow PHP as a Value

Currently, I am retrieving a value from the database where interval days are set to 5. However, when I display it, it always shows '0' within my option form. <?php $interval_day = $this->crud_model->auto_order_interval_day(); ?> ...

Cypress test never finishes when an unforeseen alert is triggered in the system during the test

When a web application unexpectedly throws an error using an alert box, the Cypress test becomes stuck indefinitely. The test will not complete or fail until the user manually closes the browser or clicks on the OK button within the alert box. https://i.s ...

Generate the hyperlinks with JavaScript

I have successfully implemented a boostrap 4 navbar, and I have a function that creates links. Is there a more efficient method to accomplish this using JavaScript? I currently have three functions that create links for each hyperlink. Would it be possib ...

I'm curious to know where in the CSS specifications it is specified how multiple properties with the same name should be handled

While debugging an unrelated issue, I want to make sure I understand how a browser is supposed to handle a declaration like background-image: url(image0.jpg); background-image: image-set(url(image1.jpg) 1x, url(image2.jpg) 2x); I tried looking in the CSS ...

Receiving a "Maximum call exceeded" error when using Vue.js router guards for the beforeEach hook

As I work on my Firebase-VueJS app, I am implementing basic security rules with router guards. In my main.js file, I have added the following code to handle permissions based on the user's authentication status. However, I encounter an error 'vue ...

When the div is clicked, it changes color and then reverts back to its original color when another

I have encountered an issue where I need to differentiate the div I clicked on in order to avoid confusion, as the pop-up menu on my website will be identical with different links but the same buttons. I have been struggling to find a solution for quite so ...

I am encountering an error when attempting to import the app from the server.js file in Express

In my server.js file, I have set up an express server and exported the app from it. //server.js require("dotenv").config(); const express = require("express"); const app = express(); const connectToDb = require("./connectToDb ...

ngOptions - Undefined Value

Currently, I am utilizing AngularJS and have created an object that contains a size property storing an array of objects. var product = [ // .. sizes: [ {choice: 'one', order: 1}, {choice: 'two', order: 2}, {choice: &ap ...

The insecure connection to http://bs-local.com:3000 has prevented access to geolocation

Hi everyone, I hope your day is going well. I could really use some assistance with an issue I've run into. I'm currently trying to test my React web app on BrowserStack's mobile screens, but I am doing the testing locally using localhost. ...

The ideal caret position while utilizing flexbox for centering within a contenteditable element

After testing on OSX Chrome 45, it appears that align-items: center; works for content alignment, but there is an issue with caret positioning in an empty editable field until text is typed. Is there a solution to this problem that doesn't involve ad ...

What is the method for inserting a new <p> tag whenever a user sends a new message in ReactJS?

Whenever I press the Enter key, the content is updated in the same tag. First I sent Hello World! The second time I tried to send Hello as a new message, it was updated within the same tag. I have shared code snippets related to the messaging function ...

Encountering a CORS issue when attempting to establish a connection with S3 from a Rails application utilizing TextureLoader

I've been struggling with this issue for a while now. Despite searching on various search engines, I haven't made much progress. I have a script that loads a texture onto a sphere. var loader = new THREE.TextureLoader(); //allow cross origin ...

Ways to incorporate additional values into an array object with Vuex

I'm new to using vuex and I am attempting to save objects into an array called orders within the store.js file. My goal is to extract values from an object (such as me.title) and save them into an array within the store file by clicking on a button t ...

What is the best way to automatically calculate fields in Django?

This is my model: class Stockdata(models.Model): quantity = models.PositiveIntegerField(null=True,blank=True) rate = models.DecimalField(max_digits=10,decimal_places=2,default=0.00) opening = models.DecimalField(max_digits=10,dec ...

Tips for avoiding variable overwriting while utilizing it in a for loop to color objects

I am looking to enhance the efficiency of my function in creating HTML objects using native JS script. The current function paints text, but I want it to optimize. When running the function, I expect different iterations of text to be written in HTML thro ...

only displaying the months on the calendar widget

There is a specific condition in my code where, depending on the value entered, the jQueryUI datepicker will either display days or months. function setdate(q){ var d=new Date(); if (q==1){ var type={ ...

Using React/Vite with createBrowserRouter in a subdirectory will not function properly unless a trailing slash is included

My current project involves using React/Vite/Express to create an app that is hosted within a subdirectory. For example, let's say the app is hosted at: https://example.com/my/app/ In my Vite configuration, I have specified base as ./ export default ...

Django not rendering view correctly when jQuery event button shows the correct response

I am facing an issue with displaying incorrect login errors using jQuery click function. While my code seems to be functioning properly and the jQuery event(button click) is showing the correct response, the Django views are not rendering the response accu ...

best way to transform a string array containing objects into an array filled with objects

I am unsure of the process to convert an array that I have Is there a way to successfully transform this particular array? const a = ['{/run:true}', '{/sleep:false}']; into the following revised array? const b = [{'/run':tru ...