The click event does not seem to be functioning properly within a contenteditable div

Incorporating a delete button within the div would allow users to delete it upon clicking. However, there are currently two issues:

(1) The alignment of the delete button with the text in the div is not accurate.

(2) The click event for the button is not functioning properly.

Below is the HTML code for your reference:

$("#slider").on("change",function(){
       var v=$(this).val();
       $('.text.active').css('font-size', v + 'px');
    });
                     
    $('.text').on('focus',function(){
        $('.close-icon').addClass('active');
    $('.text').removeClass('active');
    $(this).addClass('active');
    });
    
    $(".close-icon.active").on("click",function(){
    alert('hiii');
    
    });
.close-icon {
    border:1px solid transparent;
    background-color: transparent;
    display: inline-block;
    vertical-align: middle;
      outline: 0;
      cursor: pointer;
    }
    .close-icon:after {
    content: "X";
    display: block;
    width: 15px;
    height: 15px;
    position: absolute;
    background-color: #FA9595;
    z-index:1;
    right: 35px;
    top: 0;
    bottom: 0;
    margin: auto;
    padding: 2px;
    border-radius: 50%;
    text-align: center;
    color: white;
    font-weight: normal;
    font-size: 12px;
    box-shadow: 0 0 2px #E50F0F;
    cursor: pointer;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="range" min="12" max="120" id="slider" />
    <div class="text"  contenteditable="true"  style="cursor:grab;">hello<button class="close-icon dbutton" type="reset"></div>
    <div class="text text1"  contenteditable="true" style="cursor:grab;">hello<button class="close-icon dbutton1" type="reset"></div>
    <div class="text text2"  contenteditable="true"  style="cursor:grab;">hello<button class="close-icon dbutton2" type="reset"></div>
    <div class="text text3"  contenteditable="true"  style="cursor:grab;">hello<button class="close-icon dbutton3" type="reset"></div>

Please assist in resolving these issues.

Answer №1

Just a few updates needed in your code to make it right.

CSS:

Replace position with float

/*position: absolute;*/
float:right;

Script:

Your element is dynamic, which is why the event isn't binding correctly. Try this instead.

$(document).on("click",".close-icon",function(){

$(this).closest('div').remove();
//alert('hiii');

});

Check out the working Fiddle

Answer №2

If I understand correctly, this is the code you need for your task

<input type="range" min="12" max="120" id="slider" />
    <div class="text"  contenteditable="true"  style="cursor:grab;">hello<button class="close-icon dbutton" type="reset"></button></div>
    <div class="text text1"  contenteditable="true" style="cursor:grab;">hello<button class="close-icon dbutton1" type="reset"></button></div>
    <div class="text text2"  contenteditable="true"  style="cursor:grab;">hello<button class="close-icon dbutton2" type="reset"></button></div>
    <div class="text text3"  contenteditable="true"  style="cursor:grab;">hello<button class="close-icon dbutton3" type="reset"></button></div>

Absolute positioning of the icon is not necessary

.close-icon {
        border:1px solid transparent;
        background-color: transparent;
        display: inline-block;
        vertical-align: middle;
      outline: 0;
      cursor: pointer;
      position: relative;
    }
    .close-icon:before {
        content: "X";
        display: block;
        width: 15px;
        height: 15px;
        background-color: #FA9595;
        margin: auto;
        padding: 2px;
        border-radius: 50%;
        text-align: center;
        color: white;
        font-weight: normal;
        font-size: 12px;
        box-shadow: 0 0 2px #E50F0F;
        cursor: pointer;
    }

The "click" event worked well for me - I simply inserted the final code into a function

$("#slider").on("change",function(){
       var v=$(this).val();
       $('.text.active').css('font-size', v + 'px');
    });

    $('.text').on('focus',function(){
        $('.text').removeClass('active');
        $(this).addClass('active');
    });

    $(".close-icon").on("click",function(){
        $(this).parent().remove();
    });

See how it works here: https://jsfiddle.net/6ek8c0eq/

Answer №3

Make sure to wrap a position:relative element around a position:absolute element, otherwise it will be positioned relative to the window.

To remove an entire node, use the parent and remove methods on the button's parent element.

$("#slider").on("change", function() {
  var v = $(this).val();
  $('.text.active').css('font-size', v + 'px');
});

$('.text').on('focus', function() {
  $('.text').removeClass('active');
  $(this).addClass('active');
});

$(".close-icon").on("click", function() {
 $(this).parent().remove()

});
.close-icon {
  border: 1px solid transparent;
  background-color: transparent;
  display: inline-block;
  vertical-align: middle;
  outline: 0;
  cursor: pointer;
}
.text{
  position: relative;
  margin: 20px 0;
}
.close-icon:after {
  content: "X";
  display: block;
  width: 15px;
  height: 15px;
  position: absolute;
  background-color: #FA9595;
  z-index: 1;
  right: 35px;
  top: 0;
  bottom: 0;
  margin: auto;
  padding: 2px;
  border-radius: 50%;
  text-align: center;
  color: white;
  font-weight: normal;
  font-size: 12px;
  box-shadow: 0 0 2px #E50F0F;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="range" min="12" max="120" id="slider" />
<div class="text" contenteditable="true" style="cursor:grab;">hello
  <button class="close-icon dbutton" type="reset">
</div>
<div class="text text1" contenteditable="true" style="cursor:grab;">hello
  <button class="close-icon dbutton1" type="reset">
</div>
<div class="text text2" contenteditable="true" style="cursor:grab;">hello
  <button class="close-icon dbutton2" type="reset">
</div>
<div class="text text3" contenteditable="true" style="cursor:grab;">hello
  <button class="close-icon dbutton3" type="reset">
</div>

Answer №4

Whenever you make changes to a div after the page has loaded, those changes may not be reflected in the DOM. To ensure that your changes are registered, target the parent element that remains unchanged. It's often better to target the document or body tag.

<script>
$(document).on("click",".close-icon",function(){
alert('hiii');    
});

$("body").on("click",".close-icon",function(){
alert('hiii');    
});
</script>

Below is the finalized code snippet:

$("#slider").on("change",function(){
       var v=$(this).val();
       $('.text.active').css('font-size', v + 'px');
    });
                     
    $('.text').on('focus',function(){
        $('.close-icon').addClass('active');
    $('.text').removeClass('active');
    $(this).addClass('active');
    });
    
    $(document).on("click",".close-icon.active",function(){
    $(this).parent("div").remove();
    
    });
.close-icon {
    border:1px solid transparent;
    background-color: transparent;
    display: inline-block;
    vertical-align: middle;
      outline: 0;
      cursor: pointer;
    }
    .close-icon:after {
    content: "X";
    display: block;
    width: 15px;
    height: 15px;
    position: relative;
    background-color: #FA9595;
    z-index:1;
    left: 100%;
    top: 0;
    bottom: 0;
    margin: auto;
    padding: 2px;
    border-radius: 50%;
    text-align: center;
    color: white;
    font-weight: normal;
    font-size: 12px;
    box-shadow: 0 0 2px #E50F0F;
    cursor: pointer;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="range" min="12" max="120" id="slider" />
    <div class="text"  contenteditable="true"  style="cursor:grab;">hello<button class="close-icon dbutton" type="reset"></div>
    <div class="text text1"  contenteditable="true" style="cursor:grab;">hello<button class="close-icon dbutton1" type="reset"></div>
    <div class="text text2"  contenteditable="true"  style="cursor:grab;">hello<button class="close-icon dbutton2" type="reset"></div>
    <div class="text text3"  contenteditable="true"  style="cursor:grab;">hello<button class="close-icon dbutton3" type="reset"></div>

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

How can I differentiate between an unreachable server and a user navigating away in a $.ajax callback function?

Situation: You have a situation where several $.ajax requests to the server are still in progress. All of them end with xhr.status === 0 and xhr.readyState === 0. Possible reasons for this issue: The server might be down (EDIT: meaning it is unreachabl ...

Exporting stylesheets in React allows developers to separate

I am trying to figure out how to create an external stylesheet using MaterialUI's 'makeStyles' and 'createStyles', similar to what can be done in React Native. I'm not sure where to start with this. export const useStyles = m ...

Is there a way to reset or clear the queue using Jquery?

I've encountered an issue with my code that only triggers two functions once when a button is clicked. Subsequent clicks do not activate the functions. I'm looking for a way to reset the queue so that both functions are fired every time I click t ...

The date-picker element cannot be selected by html2canvas

I'm encountering an issue with Html2canvas while trying to capture a screenshot of my page. Specifically, the date shown in the date-picker on the page is not appearing in the screenshot. Do you have any insights into why this might be happening and h ...

alternative for in jQuery version 2

Having some issues with the "on" function in jQuery 2.0.2 when working with dynamically added elements. Below is an example where the second part seems to be failing to work: <button class="btn btn-danger btn-lg" id="hi">Danger</button> ...

Transform the string by eliminating any spaces and new lines before converting it into a JSON object

I need assistance with converting the given string into a JSON object. Here is the string: {\"Warranty\": [ \n { \n \"Name\": \"test\", \n \"Type\": \"test2\", \n \"Months\": ...

The d3 hierarchy possesses the capability to compute the average values of child nodes

Looking for a solution with d3 visualization that involves averaging up the value of score on the lowest nodes and dynamically adding that average to the parent node above. It seems like there isn't an easy method in d3 for this task. The desired outc ...

What could be causing my Angular application to go blank when I activate a rotation animation in my component.ts file?

<button [@trigger]="menuState" class="text-white font-bold cursor-pointer text-3xl leading-none px-3 py-1 border-transparent rounded bg-transparent block lg:hidden outline-none focus:outline-none ml-24 md:ml-96" type="button" id="menu" (click)="toggleMe ...

Make the table in a bootstrap design appear with a border when you hover over a cell using the table

Looking for a solution to make the border work as expected when hovering over each td in a table like this example: https://jsfiddle.net/nmw82od1/ Here is the CSS code: .table1 td:hover { border: 1px solid black; } .table2 td:hover { border: 1px do ...

Exploring cloud photos on an Android browser with the help of FileReader

This snippet of javascript code creates an image upload button and displays the uploaded image: function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { ...

Challenges encountered when trying to incorporate vanilla JavaScript within a Ruby environment

While working on my controller, I attempted to render vanilla JavaScript but encountered an unexpected outcome. Below is the code snippet: class UploadController < ApplicationController def index render :file => 'app\views&bs ...

Arranging divs precisely while rotating a Bootstrap Thumbnail

I've been experimenting with creating a "css3 on hover flip" effect for bootstrap thumbnails. It works perfectly fine on simple divs (check it out here) Here's the main CSS3 code I'm using: .front{ position:absolute; transform:pers ...

Expand the width of the navbar brand icon

Currently working on a landing page project and noticed that my logo appears too small, utilizing Bootstrap 5 style.css ... .navbar-brand { width: 3.5rem; padding: 0 0; margin: 0.3rem 0; position: relative; } .navbar-brand img { width: 100%; ...

JQuery is capable of hiding a div using the .hide() method but is unable to reveal it using the

I am currently working on a basic webpage that includes a question and a set of radio buttons. Depending on the option selected by the user, the question will be hidden and either a correct or incorrect message will be displayed, both of which are initiall ...

The result of the AJAX GET request is not defined

Despite seeing the response data in the browser's developer tool network tab, my AJAX GET response is showing as undefined. The AJAX request code I am using is as follows: $.ajax({ url: "https://api.leroymerlin.it/product-api-v2/v1/allStoreS ...

Combining 2 objects in vue.js that share a common field name

Currently, I am attempting to merge two objects based on a shared key, specifically when they have two fields with the same name but differing values. var players = [{ id : 'a', name : "player1",team:1},{ id : 'b', name : &quo ...

Schema for Monogo Database

My goal was to have a property that could give me the timestamp of when a specific task was created. I decided to add a timestamp property and set it to true, but now my code won't compile. The code is functioning perfectly fine without the timestamp ...

Interact with dynamically created form using jQuery

I am utilizing a for loop to dynamically generate a form. {% for id in data %} <form id="add_to_cart_{{id}}" method="POST" action="{% url 'add_to_cart' %}"> {{id}} <button type="submit" id="product_id_{{id}}" value="{{id}}">A ...

When I attempt to click on the Cancel button, the database row remains undeleted

After a user clicks on the "Cancel" button, I want to reset the source and remove the iframe to prevent the file from being uploaded to the server. This function is currently working as intended. However, I am facing an issue where even after clicking on ...

Create a full-width slider using Materialize CSS framework

When using materializecss to create a slider, I encountered an issue where the image is full width but not full height, causing scrollbars to appear. What changes can I make to ensure the slider fills out my screen without any scrollbars? Additionally, I ...