Is it possible to ensure that a newly created element functions in the same way as an existing element?

I am currently in the process of developing an application that empowers users to generate new items, modify existing items, or delete items by utilizing corresponding icons located adjacent to each item.

When it comes to existing items, the action icon displays upon hovering with an event handler attached to it, specifically an onClick event handler for this scenario.

$(document).ready(function() {
  var ul = `
<ul class="list-inline in-item" style="padding: 10px;">
  <li><a href="#"><i class="fa fa-plus-circle icon-add"></i></a></li>
  <li><a href="#"><i class="fa fa-pencil-square-o icon-edit"></i></a></li>
  <li><a href="#"><i class="fa fa-trash-o icon-remove"></i></a></li>
  <li><a href="#"><i class="fa fa-arrows-v icon-move"></i></a></li>
</ul>
`;

$('.item').hover(
function() {

$(ul).insertBefore($(this).find('.item-head'));

},
function() {
$(this).find('ul.list-inline').remove();
});

$('body').on('click', '.icon-add', function() {
// Add Item
items = `
<div class="item">
  <h3 class="item-head" contenteditable>[Type Item Here] [label]</h3>
  <p contenteditable>[Type what it does]</p>
</div>
`;
// $('body').append(item);
$('.item-container').append(items);
return false;
});

$('body').on('click', '.icon-edit', function() {
// Edit on Item
});

$('body').on('click', '.icon-remove', function() {
// Remove Item and its definition

});

$('body').on('click', '.icon-move', function() {
// Move item up or down
});

})
.item-head {
color: #365efe;
}

.action-icon {
float: left;
margin-top: 25px;
margin-left: -40px;
}

.icon-add {
color: #4caf50;
}

.icon-edit {
color: #00bcd4;
}

.icon-remove {
color: #f44336;
}

.icon-move {
color: #9e9e9e;
}

.in-item {
display: block;
}

.out-item {
display: none;
}

.list-inline>li:last-child {
padding-right: 25px;
}

.list-inline {
float: left;
background: transparent;
position: absolute;
left: -110px;
top: 12px;
height: 40px;
}

div.item {
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-T8Gy5hrqNKT+hzMclPo118YTQO6cYprQmhrYwIiQ/3axmI1hQomh7Ud2hPOy8SP1" crossorigin="anonymous">
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<div class="col-sm-12">
  <div class="message"></div>
  <h3>Preview</h3>
  <div class="container" style="border: 1px solid #ccc;width: 70%;">
    <div class="row">
      <div class="col-xs-12 item-container">
        <div class="item">
          <h3 class="item-head" style="float: left;">Customer [form]</h3>
          <p style="clear: both;">Customer is module for recording information related to customer such as Name, Address, Date of Birth, Place of Birth, ID Number, etc.</p>
        </div>
        <div class="item">
          <h3 class="item-head">First Name English [label]</h3>
          <p class="definition">The name that was given to you when you were born and that comes before your family name. This field accepts only English Characters.</p>
        </div>
        <div class="item">
          <h3 class="item-head">Salutation [label]</h3>
          <p>A greeting in words or actions, or the words used at the beginning of a letter or speech. This field has values such as Mr, Ms, Miss.</p>
        </div>
      </div>
    </div>
  </div>
  </form>
</div>

However, newly created items from the add icon lack the associated action icons and functionality present in existing items, appearing identical to the current items. What steps can be taken to ensure that newly created items also function similarly to existing items? Thank you!

Answer №1

It is not necessary to dynamically append a list. Instead, write it once and reuse it.

$(document).ready(function() {
  
$('.list-inline').mouseleave(function(){
  $(this).hide();
})

$('body').on('mouseenter', '.item', function(e){
  var topPosition = $(this).position().top + 10;
  $('.list-inline').show().css('top', topPosition);
  
})

  $('body').on('click', '.icon-add', function() {
    // Add Item
    items = `
<div class="item">
  <h3 class="item-head" contenteditable>[Type Item Here] [label]</h3>
  <p contenteditable>[Type what it does]</p>
</div>
`;
    // $('body').append(item);
    $('.item-container').append(items);
    return false;
  });

  $('body').on('click', '.icon-edit', function() {
    // Edit on Item
  });

  $('body').on('click', '.icon-remove', function() {
    // Remove Item and its definition

  });

  $('body').on('click', '.icon-move', function() {
    // Move item up or down
  });

})
.item-head {
  color: #365efe;
}

.action-icon {
  float: left;
  margin-top: 25px;
  margin-left: -40px;
}

.icon-add {
  color: #4caf50;
}

.icon-edit {
  color: #00bcd4;
}

.icon-remove {
  color: #f44336;
}

.icon-move {
  color: #9e9e9e;
}

.in-item {
  display: block;
}

.out-item {
  display: none;
}

.list-inline>li:last-child {
  padding-right: 25px;
}

.list-inline {
  background: trasparent;
  position: absolute;
  left: -110px;
  top: 12px;
  height: 40px;
}

div.item {
  position: relative;
  overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-T8Gy5hrqNKT+hzMclPo118YTQO6cYprQmhrYwIiQ/3axmI1hQomh7Ud2hPOy8SP1" crossorigin="anonymous">
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<div class="col-sm-12">
  <div class="message"></div>
  <h3>Preview</h3>
  <div class="container" style="border: 1px solid #ccc;width: 70%;">
    <div class="row" style="position:relative">
      <div class="col-xs-12 item-container">
      
      
      <!-- list here -->
          <ul class="list-inline in-item" style="display:none;padding: 10px;">
  <li><a href="#"><i class="fa fa-plus-circle icon-add"></i></a></li>
  <li><a href="#"><i class="fa fa-pencil-square-o icon-edit"></i></a></li>
  <li><a href="#"><i class="fa fa-trash-o icon-remove"></i></a></li>
  <li><a href="#"><i class="fa fa-arrows-v icon-move"></i></a></li>
</ul>
          
        
        <div class="item">
          <h3 class="item-head" style="float: left;">Customer [form]</h3>
          <p style="clear: both;">Customer is module for recording information related to customer such as Name, Address, Date of Birth, Place of Birth, ID Number, etc.</p>
        </div>
        <div class="item">
          <h3 class="item-head">First Name English [label]</h3>
          <p class="definition">The name that was given to you when you were born and that comes before your family name. This field accept only English Character.</p>
        </div>
        <div class="item">
          <h3 class="item-head">Salutation [label]</h3>
          <p>A greeting in words or actions, or the words used at the beginning of a letter or speech. This field has values such as Mr, Ms, Miss.</p>
        </div>
      </div>
    </div>
  </div>
  </form>
</div>

Answer №2

@Ibra, I really appreciate your helpful response and I will acknowledge it as the solution. However, I want to share some insights I have gathered regarding my initial query.

After reading through this post: is-it-possible-to-use-jquery-on-and-hover, I discovered that the issue lies with my usage of the .hover() event handler to display the action icons.

It became apparent that using .hover() on dynamically created elements from JavaScript, along with nesting .hover() within an .on() handler, was causing difficulties in accessing the action icons on dynamic elements.

Consequently, following the advice provided in the aforementioned post, I replaced .hover() with the following code:

$(".selector").on({
    mouseenter: function () {
        // actions on mouse enter
    },
    mouseleave: function () {
        // actions on mouse leave
    }
});

As a result, I updated the .hover() handler to use the event handlers .mouseenter() and

.mouseleave()</code like so:</p>

<pre><code>/**
* Show Action Icons on Mouse over and hide them
* on Mouse out
*/
$('body').on({
    mouseenter: function () {
        // actions on mouse enter
        $(ul).insertBefore($(this).find('.item-head'));
    },
    mouseleave: function () {
        // actions on mouse leave
        $(this).find('ul.list-inline').remove();
    }
}, ".item");

Subsequently, my application structure transformed into this format:

(preformatted text snippet)

Feel free to point out any missing or necessary additions. Thank you!

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

Button Vote in Bootstrap is unresponsive

I have a voting system implemented on my website using normal CSS buttons, and it works perfectly fine. However, when trying to integrate it with Bootstrap buttons, it seems to not function properly. I am looking to switch to using Bootstrap buttons for t ...

Adjust the SVG to match the dimensions of the label, which may vary in both

How can I efficiently resize and embed SVG images into checkbox labels without using a viewbox attribute? Each SVG varies in height and width, making it challenging to find the best solution. .check__button { display: none; } .check__icon { display ...

Achieving the minimum width of a table column in Material-UI

Currently I am in the process of developing a React website with Material-UI. One query that has come up is whether it's feasible to adjust the column width of a table to perfectly fit the data, along with some extra padding on both ends? Outlined be ...

How to change a string from utf-8 to iso-8859-1 using Javascript

Although it may seem unpleasant, it is essential. I am facing an issue with a HTML form on my website that uses utf-8 charset but is sent to a server operating with iso-8859-1 charset. The problem arises when the server fails to interpret characters commo ...

Don't forget to include a file upload feature when submitting a form

I'm working with codeigniter and jquery to develop a form that includes text input fields as well as a single file upload option. I'm aiming for the functionality where even if the form validation fails, the uploaded image will still be visible t ...

shard: the dropdown menu can be interacted with by clicking, but the options

Having trouble selecting an item from a dropdown menu on a modal using splinter. Despite the dropdown being visible and clickable, the selection is failing unexpectedly. (Pdb) dropdown = next(i for i in my_browser.find_by_xpath('//select[@name="exist ...

Is the JavaScript progress bar dysfunctional when used with object-oriented JavaScript code, but functions properly with arrow functions?

After posting a question about the JavaScript progress bar not working with object-oriented JavaScript code on Stack Overflow, I decided to try rewriting the script using arrow functions. Here is the new code: document.getElementById("barButton").addEve ...

Left-hand navigation panel that complements entire screen

Web Design .sidenav { height: 100%; position: relative; overflow-y: scroll; background: #000000; width: 15%; } Ensuring the menu covers the full screen correctly by setting its height to 100% is effective, but it may appear awkward wh ...

How to easily incorporate images after text in Bootstrap 4 beta

I seem to be having trouble inserting an image in the "menu" section for the last item "Kava so sebou" after the text. I want the picture to be centered vertically and the row to maintain consistency with the other items above it. Any advice or suggestions ...

Interacting div elements with jQuery's dynamic content

I am searching for a way to populate a div with content based on my click selection. To begin, I create a dynamic table like the one below: user name total hours worked button(unique id fetched from database) user name total ho ...

Challenges regarding variable scope in JavaScript

Presented below is the JavaScript code I am currently using, which involves jQuery: function language(language) { var text = new Object(); $.ajax({ type: "GET", url: "includes/xml/languages/" + language + ".xml", dataType: ...

What is the best way to adjust the minimum width of the HTML5 progress element?

There is a similar question which addresses input elements having a minimum width determined by the size parameter. I am attempting to create a layout with an inline-flex element with a flex-direction: column property like this: .item { border: 1px s ...

Enabling auto-expansion for textareas with every keystroke

Currently, I have implemented the following script: jQuery.each(jQuery('textarea[data-autoresize]'), function() { var offset = this.offsetHeight - this.clientHeight; var resizeTextarea = function(el) { jQuery(el).css('h ...

modify the color of a particular div element in real-time

I am looking to dynamically change the color of the divs based on values from my database. Here is what I have so far: Database: shape id is_success id1 0 id2 1 id3 0 id4 1 <div class="container" style="background: black; widt ...

The property 'innerHTML' cannot be assigned to null, as stated in Vue

I am dealing with two components that allow for editing JSON objects. Additionally, I have a button that toggles between these two components. Below is the HTML code snippet: <v-btn @click="switchConfigClicked">Switch config</v-btn> <h4 cla ...

Angular ng-show does not seem to evaluate properly

After receiving the JSON array object below: "Tools": [ { "name": "Submit a Claim", "position": 1, "isOn": true, "alert": null }, { "name": "My Recurring Claims", "position": 2, "isOn": true, "alert": null }, { "name": "Online Enrollment ...

The price filter slider is experiencing issues with the onresize function not functioning properly

I am facing an issue with a price filter I developed for my project. Despite having coded it, the filter is not functioning properly. <div class="price_range_caption"> <span class="currency_from">Rs.</span><span id="price_range_f ...

Sending data through forms

I'm having trouble storing values input through a dropdown menu in variables event1 and event2, despite trying global declarations. How can I successfully store a value to both variables and pass it to the JavaScript code? Thank you. <!DOCTYPE HT ...

JQuery form plugin - submitting a form automatically on onchange event

As a beginner in JQuery, I am looking to utilize the JQuery form plugin for file uploads and would like to trigger the form submission as soon as a file is selected. This should occur upon the onchange event of the input tag: myfile. <html> <body ...

How to create a vertical bar chart in ASP.Net using C# with the help of jQuery?

Currently, I am looking to generate a stacked bar chart using query. Initially, I was successful in creating the chart with static values. However, now I need to implement it with dynamic values. I have been utilizing the flot plugin for this task, but I ...