Marcelo Barganha
Marcelo Barganha

Reputation: 379

Onclick function related to an element dynamically created

I have a button that, when clicked, calls a function show().

This function dynamically creates a DIV with a close button!

This close button should call a function to remove the created DIV from the DOM.

Considering that this second function will only be necessary within this scenario, can I do that without having to declare the function explicitly?

Here's a demo:

More clearly, the idea is to dispense the need to declare the "close ()" function and set this functionality within the "show ()" function using only vanilla JS.

function show() {
	var div = document.createElement('div');
  div.setAttribute("id", "myDiv");
  div.innerHTML = "Hello World ";
  var button = document.createElement('button');
  button.innerHTML = "CLOSE";
  button.setAttribute("onclick","close();");
  div.appendChild(button);
  document.body.appendChild(div);
}

function close() {
  //code to remove element
}
#myDiv {
  background:yellow;
  border:1px solid black;
  margin-top:10px;
  padding:20px;
}
<button onclick="show();">
  Show
</button>

JSFIDDLE: https://jsfiddle.net/do4yq2w9/1/

Upvotes: 1

Views: 34

Answers (1)

Cuong Le Ngoc
Cuong Le Ngoc

Reputation: 11975

You can assign onclick of the button with a new function like below:

function show() {
	var div = document.createElement('div');
  div.setAttribute("id", "myDiv");
  div.innerHTML = "Hello World ";
  var button = document.createElement('button');
  button.innerHTML = "CLOSE";
  button.onclick = function() {
  	document.getElementById('myDiv').remove();
  }
  div.appendChild(button);
  document.body.appendChild(div);
}
#myDiv {
  background:yellow;
  border:1px solid black;
  margin-top:10px;
  padding:20px;
}
<button onclick="show();">
  Show
</button>

Upvotes: 1

Related Questions