0

In my .js script, I need to implement functionality that re-adds a div to a page if a user deletes it by hand, like if they select "Edit as HTML" and just delete a div from the DOM.

I did some research about setting up observers with IntersectionObserver API, and they work great with changed visibility, changes in colors etc. However, in my case that is not applicable because if i delete the whole div, then the observer is becoming useless.

So far I have this code which works for scrolling up / down with respect to an element, but if i delete the element it becomes useless.

window.addEventListener("load", (event) => {            
    boxElement = document.getElementById("notification_popup"); console.log(boxElement);
    createObserver();
}, false);
function createObserver() {
    let observer;

    let options = {
        root: null,
        rootMargin: "0px",
        threshold: buildThresholdList()
    };

    observer = new IntersectionObserver(handleIntersect, options);
    observer.observe(boxElement);
}
function buildThresholdList() {
    let thresholds = [];
    let numSteps = 20;

    for (let i = 1.0; i <= numSteps; i++) {
        let ratio = i / numSteps;
        thresholds.push(ratio);
    }

    thresholds.push(0);
    return thresholds;
}
function handleIntersect(entries, observer) {
    entries.forEach((entry) => {
        if (entry.intersectionRatio > prevRatio) {

             entry.target.style.backgroundColor = increasingColor.replace("ratio", entry.intersectionRatio);    console.log("higher detected"); 
    


        } else {


    console.log( document.getElementById("notification_popup") == null ); 

    if(document.getElementById("notification_popup") == null){
        var para = document.createElement("P");                       // Create a <p> node
var t = document.createTextNode("This is a paragraph.");      // Create a text node
para.appendChild(t);                                          // Append the text to <p>
document.body.appendChild(para);
    
    } 

Any ideas about how i can change my code, or re-write it to be able to detect a delete event?

Please note that i cannot use jQuery in this case, vanilla JS only.

Thanks!

ishaba
  • 551
  • 2
  • 10
Dennis Kozevnikoff
  • 2,078
  • 3
  • 19
  • 29
  • How you delete your element? – ishaba Jul 30 '21 at 17:55
  • Just right click -> inspect -> edit as HTML -> remove a div – Dennis Kozevnikoff Jul 30 '21 at 17:56
  • 2
    If you want to track it use MutationObserver https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver see: https://stackoverflow.com/questions/20156453/how-to-detect-element-being-added-removed-from-dom-element – ishaba Jul 30 '21 at 17:57
  • 1
    Note that the users can do anything to their local copy of the website; you shouldn't optimize for those who use the DevTools to delete an element. – FZs Jul 30 '21 at 18:10

0 Answers0