0

½I'm trying to make a close button for a dynamically created div.

At the moment the below code can create a div repeated, but I cannot seem to get the div close button to work. I'm trying to make it so even if multiple divs are open, the close button works on each.

If there is a way to do via jQuery please let me know as I couldn't get it to work.

<html>
    <title>Test Platform</title>

    <head>
        <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    </head>

    <style>
        body {
          margin: 0 0;
        }
        #container {
          border: 1px solid blue;
          white-space: nowrap;
          overflow: auto;
            font-size: 0;
        }

        #container > * {
          font-size: 8px;
          font-family: 'Open Sans', sans-serif;
        }

        #headerbar {
          font-size: 30px;
          color: white;
          padding-left: 10px;
          border: 1px solid darkgrey;
          height: 50px;
          background-color: darkslateblue;
        }
        #sidebar {
          display: inline-block;
          color: black;
          border: 1px solid darkgrey;
          width: 50px;
          height: 100vh;
          vertical-align: top;
          background-color: lightgrey;
          text-align: center;
          padding-top: 10px;
        }
        .content {
          display: inline-block;
          width: 200px;
          height: 100vh;
          border: 1px solid lightslategrey;
          margin: 0 1px 0 0;
          vertical-align: top;
          background-color: lightsteelblue;
        }
        .close {
            display: inline-block;
            padding: 2px 5px;
            background: #ededed;
            float: right;
        }
        .close:hover {
            float: right;
            display: inline-block;
            padding: 2px 5px;
            background: #ccc;
            color: #fff;
        }
    </style>

    <body>
        <div id='container'>
            <div id='headerbar'>Header Div</div>
            <div id='sidebar'> <input type="button" value="O" id="calculate" />
                <br/><br/>
                <br/><br/>
            </div>
        </div>

        <script type='text/javascript'>
            window.onload = function(){
                document.getElementById('close').onclick = function(){
                    this.parentNode.parentNode.parentNode
                    .removeChild(this.parentNode.parentNode);
                    return false;
                };
            };
        </script>

        <script>
            function makeResponseBox() {
                document.getElementById("calculate").onclick = function()
                {
                    var responseBox = document.createElement("DIV"); //create <div>
                    var spanclose = document.createElement("span");
                    var spantext = document.createTextNode("X");
                    spanclose.appendChild(spantext);
                    spanclose.setAttribute("class", "close" );
                    responseBox.setAttribute("class", "content" );
                    responseBox.appendChild(spanclose);
                    document.getElementById('container').appendChild(responseBox);
                }
            } // Close function (makeResponseBox)
            window.onload = makeResponseBox;
        </script>
    </body>
</html>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pow
  • 25
  • 4
  • 1
    What do you mean by close? If you mean document.createElement("DIV") will create a
    so it will be closed.
    – E.Serra Aug 26 '16 at 16:27
  • @e.serra Hi, At the moment the button creates a div, how can I make it when I click on the corner "x" button of the div that was created, it deletes the div/removes the div from the page. – Pow Aug 26 '16 at 16:28
  • It would be simpler to use `jQuery`. [Example](http://stackoverflow.com/questions/867916/creating-a-div-element-in-jquery) – Arjun Aug 26 '16 at 16:30
  • You're binding the close event to click on `window.onload` before the close-able `
    `s exist. You need to bind the click event as they're created.
    – J. Titus Aug 26 '16 at 16:33
  • You can either hide it or remove it, there is no such thing as closing. I would remove it. You can give responseBox an id then remove it capturing it using the id http://www.w3schools.com/js/js_htmldom_nodes.asp Another alternative is to use className (but it should be uniq as it only exists between the user clicks the button and the x button right? so a unique id should be the way to go). – E.Serra Aug 26 '16 at 16:34
  • Theres no element with the id "close" there classes – Jonas Wilms Aug 26 '16 at 16:35
  • And your event listener is added before the element is created... – Jonas Wilms Aug 26 '16 at 16:35
  • This is not valid [HTML](http://en.wikipedia.org/wiki/HTML) at all. The `` and `<style>` tags are outside the `<head>` tag. I recommend using an [HTML validator](http://validator.w3.org/check?uri=pmortensen.eu&charset=utf-8).</style> – Peter Mortensen Aug 28 '16 at 12:47

8 Answers8

1
$("body").on("click", ".content .close", function() {
    $(this).parent().remove();
});

Your code to remove the dynamically created div almost worked, but it was looking for the id close instead of class and wouldn't work since the event would be added before the content is added to the DOM.

To solve that we can use event delegation in jQuery as shown above. We attach the click to the body instead of the close button and only make it trigger when the close button is clicked.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alan
  • 56
  • 2
1

This would be your function using jQuery. Note that you still have to add the return value to the DOM.

function makeResponseBox() {
    $close = $('<div>').addClass('close');
    $window = $('<div>').addClass('window');
    $window.append($close);
    $close.on('click', function(e){
        e.preventDefault();
        // removes the enclosing div.window
        $(e.target).closest('.window').remove();
        return false;
    });
    return $window;
}

https://jsfiddle.net/p96Lq65s/17/

Cristian Torres
  • 256
  • 3
  • 12
0

The below code will help you with that:

JavaScript:

function makeResponseBox() {
    document.getElementById("calculate").onclick = function()
    {
        var responseBox = document.createElement("DIV"); //create <div>
        var spanclose = document.createElement("span");
        var spantext = document.createTextNode("X");
        spanclose.appendChild(spantext);
        spanclose.setAttribute("class", "close" );
        spanclose.setAttribute("onclick", "removeDiv(this)" );
        responseBox.setAttribute("class", "content" );
        responseBox.appendChild(spanclose);
        document.getElementById('container').appendChild(responseBox);
    }
} // Close function (makeResponseBox)

window.onload = makeResponseBox;

function removeDiv(elem){
    elem.parentElement.remove()
}

jQuery

function makeResponseBox() {
    document.getElementById("calculate").onclick = function()
    {
        var responseBox = document.createElement("DIV"); //create <div>
        var spanclose = document.createElement("span");
        var spantext = document.createTextNode("X");
        spanclose.appendChild(spantext);
        spanclose.setAttribute("class", "close" );
        responseBox.setAttribute("class", "content" );
        responseBox.appendChild(spanclose);
        document.getElementById('container').appendChild(responseBox);
    }
} // Close function (makeResponseBox)

window.onload = makeResponseBox;
$( "#container" ).on( "click",".close", function() {
    $(this).parent().remove();
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nalin Aggarwal
  • 886
  • 5
  • 8
0

You can use this code:

$("#container").on("click",".close",function(){
    $(this).closest(".content").hide()
})

This is the demo code:

<html>
    <title>Test Platform</title>

    <head>
        <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
   

    <style>
        body {
            margin: 0 0;
        }
        #container {
            border: 1px solid blue;
            white-space: nowrap;
            overflow: auto;
            font-size: 0;
        }

        #container > * {
            font-size: 8px;
            font-family: 'Open Sans', sans-serif;
        }

        #headerbar {
            font-size: 30px;
            color: white;
            padding-left: 10px;
            border: 1px solid darkgrey;
            height: 50px;
            background-color: darkslateblue;
        }
        #sidebar {
            display: inline-block;
            color: black;
            border: 1px solid darkgrey;
            width: 50px;
            height: 100vh;
            vertical-align: top;
            background-color: lightgrey;
            text-align: center;
            padding-top: 10px;
        }
        .content {
            display: inline-block;
            width: 200px;
            height: 100vh;
            border: 1px solid lightslategrey;
            margin: 0 1px 0 0;
            vertical-align: top;
            background-color: lightsteelblue;
        }
        .close {
            display: inline-block;
            padding: 2px 5px;
            background: #ededed;
            float: right;
        }
        .close:hover {
            float: right;
            display: inline-block;
            padding: 2px 5px;
            background: #ccc;
            color: #fff;
        }
    </style>
    </head>
    <body>
        <div id='container'>
            <div id='headerbar'>Header Div</div>
            <div id='sidebar'> <input type="button" value="O" id="calculate" />
                <br/><br/>
                <br/><br/>
            </div>
        </div>

        <script type='text/javascript'>
            $("#container").on("click",".close",function(){
                $(this).closest(".content").hide()
            })
        </script>

        <script>
            function makeResponseBox() {
                document.getElementById("calculate").onclick = function()
                {
                    var responseBox = document.createElement("DIV"); //create <div>
                    var spanclose = document.createElement("span");
                    var spantext = document.createTextNode("X");
                    spanclose.appendChild(spantext);
                    spanclose.setAttribute("class", "close" );
                    responseBox.setAttribute("class", "content" );
                    responseBox.appendChild(spanclose);
                    document.getElementById('container').appendChild(responseBox);
                }
            } // Close function (makeResponseBox)
            window.onload = makeResponseBox;
        </script>
    </body>
</html>
Ying Yi
  • 784
  • 4
  • 16
  • 1
    This is not valid [HTML](http://en.wikipedia.org/wiki/HTML) at all. The `` and `<style>` tags are outside the `<head>` tag. I recommend using an [HTML validator](http://validator.w3.org/check?uri=pmortensen.eu&charset=utf-8).</style> – Peter Mortensen Aug 28 '16 at 12:45
0

When you run the function to add close functionality to all elements with class .close there are no such elements. Because you haven't created any divs yet. You should add the onclick listener when you create new divs.

<html>
<title>Test Platform</title>

<head>
  <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>

<style>
  body {
    margin: 0 0;
  }
  #container {
    border: 1px solid blue;
    white-space: nowrap;
    overflow: auto;
    font-size: 0;
  }
  #container > * {
    font-size: 8px;
    font-family: 'Open Sans', sans-serif;
  }
  #headerbar {
    font-size: 30px;
    color: white;
    padding-left: 10px;
    border: 1px solid darkgrey;
    height: 50px;
    background-color: darkslateblue;
  }
  #sidebar {
    display: inline-block;
    color: black;
    border: 1px solid darkgrey;
    width: 50px;
    height: 100vh;
    vertical-align: top;
    background-color: lightgrey;
    text-align: center;
    padding-top: 10px;
  }
  .content {
    display: inline-block;
    width: 200px;
    height: 100vh;
    border: 1px solid lightslategrey;
    margin: 0 1px 0 0;
    vertical-align: top;
    background-color: lightsteelblue;
  }
  .close {
    display: inline-block;
    padding: 2px 5px;
    background: #ededed;
    float: right;
  }
  .close:hover {
    float: right;
    display: inline-block;
    padding: 2px 5px;
    background: #ccc;
    color: #fff;
  }
</style>

<body>

  <div id='container'>
    <div id='headerbar'>Header Div</div>
    <div id='sidebar'>
      <input type="button" value="O" id="calculate" />
      <br />
      <br />
      <br />
      <br />
    </div>

  </div>

  <script>
    function makeResponseBox() {
        document.getElementById("calculate").onclick = function() {
          var responseBox = document.createElement("DIV"); //create <div>
          var spanclose = document.createElement("span");
          var spantext = document.createTextNode("X");
          spanclose.appendChild(spantext);
          spanclose.setAttribute("class", "close");
          spanclose.onclick = function() {
            this.parentNode.parentNode
              .removeChild(this.parentNode);
            return false;
          };
          responseBox.setAttribute("class", "content");
          responseBox.appendChild(spanclose);
          document.getElementById('container').appendChild(responseBox);


        }
      } //close function (makeResponseBox)
    window.onload = makeResponseBox;
  </script>

</body>

</html>
knutesten
  • 594
  • 3
  • 16
0

Add this to your makeResponseBox function:

spanclose.onclick=function(){
this.parentNode.removeChild(this);
}
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

You can use this code:

<script type="text/javascript">
    $(document).ready(function() {
        $("body").on('click', '.close', function(e) {
            $(e.target.parentElement).remove();
        });
    });
</script>
Parveen Sachdeva
  • 989
  • 2
  • 19
  • 28
0

See this fiddle

Below is the updated JavaScript code.

function add() {
    var responseBox = document.createElement("DIV"); //create <div>
    var spanclose = document.createElement("span");
    var spantext = document.createTextNode("X");
    spanclose.appendChild(spantext);
    spanclose.setAttribute("class", "close");
    responseBox.setAttribute("class", "content");
    responseBox.setAttribute("onclick", "remove(this)");
    responseBox.appendChild(spanclose);
    document.getElementById('container').appendChild(responseBox);
}

function remove(elt) {
    elt.parentNode.removeChild(elt);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Lal
  • 14,726
  • 4
  • 45
  • 70