Creating dynamic div elements using jQuery

I used a foreach loop in jQuery to create some divs. Everything seems to be working fine, but for some reason, my divs are missing SOME class properties. Here is the code snippet I am using:

$("#item-container").append("<div class=\"panel col-md-2 col-xs-4 item\" style=\"height:170px;  border-bottom-color: red;\"></div>")

So basically, just simple divs. I added some styling like this:

.item {
margin: 10;
 border-style: solid;
   cursor: pointer;
   border-bottom-width: 2px;
}

The styling works perfectly fine. However, I have another JavaScript function that changes the color of the selected div with the class item. This function was working without any issues when I generated the divs with PHP, but now it's not working. Additionally, the above styling is not being applied for some unknown reason.

item h5,h6,img{
  -webkit-touch-callout: none; /* iOS Safari */
  -webkit-user-select: none; /* Chrome/Safari/Opera */
   -khtml-user-select: none; /* Konqueror */
     -moz-user-select: none; /* Firefox */
      -ms-user-select: none; /* Internet Explorer/Edge */
          user-select: none;
          -webkit-user-drag: none;
 -khtml-user-drag: none;
 -moz-user-drag: none;
 -o-user-drag: none;
 user-drag: none;

If you have any insights on what might be causing this issue, please let me know

EDIT: I figured out why the CSS is not working. The problem lies within this particular function:

$('.item').click(function () {
    var currentprice
    var itemprice
    itemprice = parseFloat($(this).find('.item-price').html());
    currenptice = $('#currentprice').text();
    if ($(this).hasClass( "selected-item" )) {
      $('#currentprice').text(parseFloat(currenptice) - itemprice);
      $(this).removeClass("selected-item");
    } else {
        $('#currentprice').text(parseFloat(currenptice) + itemprice);
      $(this).addClass("selected-item");
    }
  });

This function worked perfectly when I was generating divs with PHP, but now it's not functioning properly.

Answer №1

Explore the concept of event delegation. A key point mentioned on that page is:

Direct events are only attached to elements at the time the .on() method is called.

This could potentially be the reason why your click handler isn't being triggered when a user interacts with an element (especially if more elements with the same class are added after attaching the click handler). Refer to the example below where a click handler is assigned to the entire document, and different actions are taken based on the id or class of the item.

Another adjustment made was using single quotes to delimit the string for the new div element instead of double quotes, eliminating the need for escape characters when using double quotes within it.

$("#item-container").append('<div class="panel ....'); 

$(document).ready(function(readyEvent) {
  $(document).click(function(clickEvent) {
    var element = $(clickEvent.target);
    if (element.attr('id') == 'add') {
      AddItem();
    }
    if (element.is('.item')) {
      ItemClickHandler(element);
    }
  });
});

function AddItem() {
  $("#item-container").append('<div class="panel col-md-2 col-xs-4 item" style="height:20px;  border-bottom-color: red;"><span class="item-price">2</span></div>');
}

function ItemClickHandler(element) {
  var currentprice;
  var itemprice;
  itemprice = parseFloat(element.find('.item-price').html());
  currentprice = $('#currentprice').text();
  if (element.hasClass("selected-item")) {
    $('#currentprice').text(parseFloat(currentprice) - itemprice);
    element.removeClass("selected-item");
  } else {
    $('#currentprice').text(parseFloat(currentprice) + itemprice);
    element.addClass("selected-item");
  }
}
.item {
  margin: 10;
  border-style: solid;
  cursor: pointer;
  border-bottom-width: 2px;
}
item h5,
h6,
img {
  -webkit-touch-callout: none;
  /* iOS Safari */
  -webkit-user-select: none;
  /* Chrome/Safari/Opera */
  -khtml-user-select: none;
  /* Konqueror */
  -moz-user-select: none;
  /* Firefox */
  -ms-user-select: none;
  /* Internet Explorer/Edge */
  user-select: none;
  -webkit-user-drag: none;
  -khtml-user-drag: none;
  -moz-user-drag: none;
  -o-user-drag: none;
  user-drag: none;
}
.selected-item {
  background-color: #0f0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="currentprice">3.50</div>
<button id="add">add item</button>
<div id="item-container"></div>

Answer №2

When calling the append() method, ensure you are passing a string correctly. Use a dollar sign ($) to create a new div element:

$("#item-container").append($('&lt;div class="panel col-md-2 col-xs-4 item" style="height: 170px;  border-bottom-color: red;"&gt;&lt;/div&gt;'));

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

Creating dynamic ng-options in AngularJS

Below is an array: $scope.age = 2; $scope.people = [{name:"Sam",age:2},{name:"Pam",age:3},{name:"Ham",age:4}] The requirement is to make the ng-options dynamic. When age is 2, display all people objects in ng-options. If age is 1, show only the object wi ...

Tips for validating html:options collection in Struts 1.3?

A Treemap is populated with values from a database using the following Java code: Map<String, String> treeMap = new TreeMap<String, String>(map); Iterator mapIterator = mapSet.iterator(); while (mapIterator.hasNext()) { Map.Entry mapEntry = ...

JavaScript Game Timer

I am working on a countdown timer where I have set the variable seconds to 10. If the seconds reach zero, I want to add 2 seconds to it and stop the program from looping. Can someone please assist me with this? var isWaiting = false; var isRunning = fal ...

Issues with the HTML5 progress bar malfunctioning due to alterations made by Angular

Using the html5 progress bar <progress value="5" max="100"></progress> in angular can lead to it being replaced by angular classes. Angular also has its own progress bar that uses similar tags. However, elements like the html5 slider do not get ...

Having trouble retrieving coordinates from AJAX request to Google Maps API?

I am currently developing a weather application and one of the initial steps is to retrieve the longitude and latitude coordinates for a specific city based on its name. To achieve this, I am utilizing Google Maps API to gather the necessary information. ...

Am I on the right track with my code?

Is the code I've written sufficient to position text above an image? It resembles the orange "Ask Question" button on StackOverflow, but without being a clickable button or link. The text is surrounded by an orange color and it works fine, but I' ...

Alert when every ajax call is completed

Here is some code I have written: var chapterNameArr = ['firstchapter','secondchapter','thirdchapter','fourthchapter','fifthchapter','sixthchapter','seventhchapter']; $.each(chapterN ...

The Next JS build process exclusively creates server-side pages

I have noticed that some of my pages like /contact, /about, and /rules are server-side generated even though I am not using getServerSideProps(). Since these pages only contain static images and text without any API requests, I want them to be treated as s ...

Use Javascript to create commands and variables specific to the domain or site of a webpage

Currently, I have implemented the code below to fetch the latest tweet. However, I am looking for a way to customize the TWITTERUSERNAME based on the domain where the template is being used. This template is shared across multiple domains. <script type ...

What is the best way to apply styles to a particular ul element without impacting the appearance of other lists on

I am facing an issue with the styling of ul elements on my web page. The latest ul I added is affecting the appearance of other lists on the page. How can I ensure that the styling for this ul only affects this specific one? I have attempted multiple solut ...

Troubulation with AngularJS: Why aren't my directives loading?

After working on my webpage Danieboy.github.io for some time, I took a 2-month break and returned to optimize it with the assistance of Dareboost. Making small changes like optimizing images and switching raw.github.com to rawgit.com, I thought everything ...

I have a vision of creating a unique Countdown Stopwatch that meets all my

I'm looking to create a custom countdown stopwatch where I can set the time and watch it count down to 0:00. The stopwatch should have three buttons: Start, Stop, and Reset. I've searched multiple websites for what I need but haven't found ...

Is it possible to make the background of the HTML Embed object transparent instead of grey?

I am currently utilizing Firefox along with an open-source plugin for video playback. The video is adjusted to fit the available space as defined by the width and height of the embed object, but occasionally a slight grey border appears on the right or bot ...

Reversing text in mongodb

https://i.sstatic.net/Y61ML.png In my node.js and MongoDB 5 project, I am attempting to retrieve data where the field "TOTAL DUE" has a value other than '$0.00'. I have successfully selected records where "TOTAL DUE" equals '$0.00' usi ...

Setting up SKPM (Sketch Plugin Manager) using npm

I've been trying to install a specific npm package, but I keep encountering numerous errors that are unfamiliar to me. It's important to note that these errors occur after running the command sudo npm install -g skpm: gyp ERR! configure error g ...

Run the function after the onclick function has finished executing

I'm currently working on diagnosing an issue with this application. There is an anchor tag that contains the following code: onclick="javascript: return ShowItemDiscussion();" This code is located in a separate JavaScript file. I am attempting to ...

Using JQuery to monitor the loading of a newly selected image src attribute

As a newcomer to JavaScript and JQuery, I am facing a challenge that I couldn't find a solution for in other discussions: I have a function that retrieves the path to an image (/API/currentImage) using a GET request and needs to update the src attrib ...

Internet Explorer 11 has a problem with excessive shrinking of flex items

I have a flexbox setup with a left and right section, each of equal width. The left side displays an image and the right side contains text. While this layout works fine in Google Chrome, it does not wrap properly in Internet Explorer 11 when the width is ...

Enhancing Security: Implementing Node.js API Authentication

Looking for guidance on setting up multiple authentications with different roles in Next.js development. Can anyone help me navigate this aspect of website building? Using Next.js for the frontend Utilizing Node.js and JWT (JSON web token) for the backend ...

Navigating Paths in Real-time with Javascript - Node.js

When working with PHP, dynamic routing can be achieved by defining classes and methods like: class Route { public function homePage () { echo 'You are on the home page' } public function otherPage () { echo 'You are on so ...