I want to attach an event to an element in JavaScript, problem is that I know only simple event attachment without parameters but here I want to attach an event with this parameter, something like shown below
element.addEventListener("onclick",
function RemoveDirectory(this) {
alert(this);
});
here this should refer to element of course.
Edit
I tried using Jquery but since the element is not selected from the DOM it is a dynamically created element can some one tell me how can I use Jquery’s $("selector").click() method with dynamically created elements which were created via document.createElement("input");
I tried this with jquery 1.7.2 NO LUCK
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"
type="text/javascript" language="javascript">
</script>
<div id="diver">
Hello events !
</div>
<script type="text/javascript" language="javascript">
var btn = document.createElement('INPUT');
btn.type = 'button';
btn.value = "CLICK me";
document.getElementById("diver").appendChild(btn);
$(document).on('click', btn, function () {
alert(this.value);
});
</script>
problems with this are
- Event is added to whole document instead of that dynamically added button only.
thiskeyword refers todocumentinstead of that dynamically added button only.
add event with dynamically created element. try with jQuery .on
here selector will be your dynamically created element.
Note : jQuery 1.7 is required