JSFiddle - React, Tailwind, and code Playground
by Oz Weiss
HTML
<body>
<div id="container">
<input type="text" id="itemName" onkeydown="if (event.keyCode == 13) document.getElementById('addItem').click()">
<button id="addItem" type="button">add item</button>
<input type="text" id="tagName" onkeydown="if (event.keyCode == 13) document.getElementById('addTag').click()">
<button id="addTag" type="button">add tag</button>
<table id="itemsTable"></table>
</div>
</body>
CSS
.targetItem {
color: red;
}
JavaScript
$(document).ready(function () {
//targetItem will always hold the item which is marked for tags addition
var targetItem = $();
//oldItem and newItem are used for coloring items that are marked for tags addition and de-coloring them
var oldItem = $();
var newItem = $();
//clicking the 'close' button of each tag will remove the tag
$("table#itemsTable").delegate(".tagRemover", "click", function () {
$(this).parent().remove();
});
//clicking the 'close' button of each item will remove the item (double parent() because we we go from button to td to tr and remove tr)
$("table#itemsTable").delegate(".itemRemover", "click", function () {
$(this).parent().parent().remove();
});
//clicking on an item name will color it in red, and make it target for tags addition
$("table#itemsTable").delegate("td.item", "click", function (event) {
//change the color of the previous targeted item back to black
$("table#itemsTable").find('.targetItem').removeClass('targetItem');
//change the color of the newly targeted item to red and make it the target
targetItem = $(event.target).parent().children("td.tags");
targetItem.parent().children("td.item").addClass("targetItem");
});
//general add tag to item function
function addTag(targetItem, tagName) {
if (tagName != "") {
$(targetItem).append("<span class=\"tag\"><button class=\"tagRemover\" type=\"button\">X</button>" + tagName + "</span>");
}
}
//copy a tag to the marked item by clicking a tag
$("table#itemsTable").delegate("span.tag", "click", function (event) {
if (event.target.tagName == "SPAN") {
//get only the text of the tag span, without the text of the inside button (x)
var tagName = $(event.target).clone().children().remove().end().text();
addTag(targetItem, tagName);
}
});
//if user clicks in the background...