2

I am facing trouble in removing a div element that I have created with JavaScript. I call this function onclick element.

function makediv(){
        var div = document.createElement('DIV');
        $(div).attr('id','md');
        $(div).css({"left":e.pageX,"top":e.pageY });
        $("body").append(div);
    }

And here how I'am trying to remove when I click somewhere else than that div. before I click somewhere else the div even showed up it just deleted at the moment it created.

window.onclick = function(event)
    {           
        dl=$('#md');
        if(event.target!=dl)
            dl.remove();
    }

I have also tried this one.

window.onclick = function(event)
    {
        if($('#md').length!=0){

        dl=$('#md');
        if(event.target!=dl)
            dl.remove();
        }
    }

But this code remove div element as it is created.

1 Answers1

0

You can use jQuery for shorter and easier code.

function makediv() {
  $("body").append("<div id='md'></div>");
}

$(document).ready(function() {
  makediv(); /* Call the function to add the div */
});

$(document).click(function(e) {
  /* Check if id is mb. If it is not, remove the div */
  if ($(e.target).attr("id") != "md") $("#md").remove();
});
#md {
  width: 100px;
  height: 100px;
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Eddie
  • 26,593
  • 6
  • 36
  • 58