Home > front end >  I want to make a div appear when you click a button
I want to make a div appear when you click a button

Time:12-09

I need help with creating a div that when you click a button, the div with custom HTML inside gets created.

<html>
<link rel="stylesheet" href="style.css">
   <script type="text/javascript">
   var template = `
   <div >
      Hello World!
      </div>
`
function createBlock() {

}
   </script>
   <button onclick="createBlock()">Create div</button>
</html>

If this is possible(it most likely is), I am making a post box thing.

Thanks!!!

CodePudding user response:

are you looking for something like this?

var template = `
   <div >
      Hello World!
      </div>
`
function createBlock() {
  let myDiv = document.createElement('div');
  document.body.append(myDiv);
    myDiv.outerHTML = template;
}
.block{ background: red }
<html>
<link rel="stylesheet" href="style.css">
   <button onclick="createBlock()">Create div</button>
</html>

If you want put your template as a child inside new div you can change your createBlock like this:

function createBlock() {
  let myDiv = document.createElement('div');
  myDiv.innerHTML= template;
  document.body.append(myDiv);
}

CodePudding user response:

Instead of creating an element, a better way to do this (with the same effect) is hiding and then showing the element, like so:

#block {
  display: none;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<link rel="stylesheet" href="style.css">

<button onclick="createBlock()">Create div</button>
  <div id="block">
    Hello World!
   </div>
      
  <script type="text/javascript">
  function createBlock() {
    block = document.getElementById("block")
    block.style.display = "block"
  }
   </script>

</body>
</html>

  • Related