rupali317
rupali317

Reputation: 512

How to trigger an event when a particular HTML element is removed automatically?

Overview of the code: This code consists of an editable div section. Below the div, there is a button which creates a span element, inserts the text "tag" in the span element and finally appends the span element in that editable div

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
    <style type="text/css">
        #sample-div
        {
            border-style: solid;
            border-width: 1px;
            border-color: black;
            height:100px;
            overflow: auto;
        }
    </style>
    <script type="text/javascript">
        function addTags()
        {
            var tag = document.createElement("span");
            tag.className = "$(tag)"
            tag.innerHTML = "tag";
            tag.contentEditable = false;
            $('#sample-div').append(tag);
        }

        $(document).ready(function(){
            $('span').keyup(function(){
                if(!this.value)
                {
                    alert('this is empty');
                }
            });
        });
    </script>
</head>
<body>
 <div id="sample-div" contenteditable="true"></div>
 <input type="button" value="date" id="sample-tags" onclick="addTags()">
</body>
</html>

General observation: When I type something inside the div and then click on the button, the HTML DOM will change as:

<div id="sample-div" contenteditable="true">
    this is a <span class="$(tag)" contenteditable="false">tag</span>
</div>

Please note that the text "this is a", is provided by me when I type inside the div element. "tag" appears when I click on the input button

Expectation / Trying to achieve: When I delete the text in the span, the DOM will change as:

<div id="sample-div" contenteditable="true">
    this is a
</div>  

So, my aim is to get the information that the element span is removed when I delete the text in span. I am trying to achieve that by doing the following, which is not correct:

$(document).ready(function(){
    $('span').keyup(function(){
        if(!this.value)
        {
            alert('this is empty');
        }
    });
});

So, my question is how do I get the message "this is empty" when the DOM removes the span element?

Upvotes: 3

Views: 1381

Answers (2)

Tns
Tns

Reputation: 410

You probably should use MutationObserver

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title></title>
    <style type="text/css">
        #sample-div
        {
            border-style: solid;
            border-width: 1px;
            border-color: black;
            height:100px;
            overflow: auto;
        }
    </style>
</head>
<body>
    <div id="sample-div" contenteditable="true"></div>
    <input type="button" value="date" id="sample-tags" onclick="addTags()">
    <script type="text/javascript">

        'use strict';

        function addTags()
        {
            var tag = document.createElement("span");
            tag.className = "$(tag)"
            tag.innerHTML = "tag";
            tag.contentEditable = false;
            document.getElementById('sample-div').appendChild(tag);
        }

        function onTagRemoved(node)
        {
            alert(`node ${node.tagName}.${node.className} removed`);
        }

        //
        // https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
        //

        // select the target node
        let target = document.querySelector('#sample-div');

        // create an observer instance
        let observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {

                // console.log(mutation);

                let node = null;
                for (var i = 0; i < mutation.removedNodes.length; i++) {
                    node = mutation.removedNodes[i];
                    if (/span/i.test(node.tagName)) {
                        onTagRemoved(node);
                    }
                }
            });
        });

        // configuration of the observer:
        let config = { attributes: false, childList: true, characterData: false }

        // pass in the target node, as well as the observer options
        observer.observe(target, config);

        // later, you can stop obser
        // observer.disconnect();

    </script>
</body>
</html>

Tested on Firefox 52

Upvotes: 1

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

You could use a variable as a "tag" counter.
When the amount tags present in the div gets lower than the tag counter, that is when one got deleted.

var tagCount = 0;

function addTags(){
  var tag = document.createElement("span");
  tag.className = "$(tag)"
  tag.innerHTML = "tag";
  tag.contentEditable = false;
  $('#sample-div').append(tag);
  
  // Increment tagCount
  tagCount++;
}


$(document).ready(function(){

  $('#sample-div').keyup(function(){
    if($(this).find("span").length < tagCount){
      alert('One tag was removed');
      
      // Decrement tagCount
      tagCount--;
    }
  });

}); // Ready
#sample-div{
  border-style: solid;
  border-width: 1px;
  border-color: black;
  height:100px;
  overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="sample-div" contenteditable="true"></div>
 <input type="button" value="date" id="sample-tags" onclick="addTags()">

Upvotes: 1

Related Questions