0

I am creating a weird WYSIWYG from scratch using pure JS as an exercise. Here is my code thus far:

<style> 
    body {
        height: 200px;
        background: white;
    }

    .title1 {
        height: 12px; 
        width: 100px;
        background: white;
        position: relative;

    }
</style>    
<script>
newTitle1 = function() {
    var title1 = document.createElement("div")
    title1.setAttribute("contentEditable", "true")
    title1.innerHTML = "whatever";
    title1.className = "title1";
    title1.addEventListener("click", function() {
        removeEventListener("click", newTitle1);
    })

    title1.style.left = (event.pageX -4) + "px";
    title1.style.top = (event.pageY -4 ) + "px";
    document.body.appendChild(title1)

}   

addEventListener("click", newTitle1)    
</script>

My question is specifically about

title1.addEventListener("click", function() {
        removeEventListener("click", newTitle1);
    })

I want removeEventListener to work while I click into the div that it just created. BUT, when I click outside of the div, I want newTitle1 to work.

Bottomline: I want newTitle1 listener to work outside of the div it just created, and not to work inside the div it creates. Any ideas how to make this happen? Here is a fiddle of my code to test if needed: https://jsfiddle.net/nirchernia/v3cLwb82/

ApathyBear
  • 9,057
  • 14
  • 56
  • 90

1 Answers1

1

You want to stop the event propagating. Solution shamelessly stolen from over here.

newTitle1 = function() {
var title1 = document.createElement("div")
title1.setAttribute("contentEditable", "true")
title1.innerHTML = "whatever";
title1.className = "title1";
title1.addEventListener("click", function(event) {
    event.stopPropagation()
    window.event.cancelBubble = true
})

title1.style.left = (event.pageX -4) + "px";
title1.style.top = (event.pageY -4 ) + "px";
document.body.appendChild(title1)

}

addEventListener("click", newTitle1)

/edit: And I think you want your .title1 CSS to have position:absolute; too :)

Community
  • 1
  • 1
SpoonNZ
  • 3,780
  • 1
  • 20
  • 25