How can we pass an element to event handler in javascript - javascript

I have created an <input> HTML element using Javascript. Now I want to add an onblur event handler to this element dynamically. However I do not understand how I can pass the created element as an argument to the function. Here's my code:
element = document.createElement("input");
element.onblur = hello_function;
In the above code you can see that the element is created. Now I want to pass that element to hello_function. How can I do that?
function hello_function(element) {
alert(element);
}

To achieve this you can wrap the hello_function call in an anonymous function wrapper and provide the this argument:
element = document.createElement("input");
element.addEventListener('blur', function() {
hello_function(this);
});
document.body.appendChild(element);
function hello_function(element) {
console.log(element);
}
Also note the preferred use of addEventListener over onblur.

try like this. passing the another variable into a function,
var something="hello";
var element = document.createElement("input");
element.addEventListener('blur' , function ()
{
hello_function(something);
})
document.body.appendChild(element)
function hello_function (element){
alert(element);
}

i suggest to use addEventListener, also i think you need to append the created element to the document, something like this:
var elem = document.createElement("input");
if (elem) {
elem.addEventListener('blur', hello_function, false);
}
document.body.append(elem);
function hello_function(element) {
alert(element);
}

Related

pass/propagate event.target of parent element [duplicate]

I am trying to change the innerHTML of my page to become the innerHTML of the element I click on, the only problem is that i want it to take the whole element such as:
<section class="homeItem" data-detail="{"ID":"8","Name":"MacBook Air","Description":"2015 MacBook A…"20","Price":"899","Photo":"Images/Products/macbookAir.png"}"></section>
Whereas the code that i have written in javascript:
function selectedProduct(event){
target = event.target;
element = document.getElementById("test");
element.innerHTML = target.innerHTML;
}
will target the specific element that i click on.
What i would like to achieve is when i click on anywhere in the <section> element, that it will take the innerHTML of the whole element rather than the specific one that i have clicked.
I would presume it is something to do with selecting the parent element of the one that is clicked but i am not sure and can't find anything online.
If possible i would like to stay away from JQuery
I think what you need is to use the event.currentTarget. This will contain the element that actually has the event listener. So if the whole <section> has the eventlistener event.target will be the clicked element, the <section> will be in event.currentTarget.
Otherwise parentNode might be what you're looking for.
link to currentTarget
link to parentNode
To use the parent of an element use parentElement:
function selectedProduct(event){
var target = event.target;
var parent = target.parentElement;//parent of "target"
}
handleEvent(e) {
const parent = e.currentTarget.parentNode;
}
function getParent(event)
{
return event.target.parentNode;
}
Examples:
1. document.body.addEventListener("click", getParent, false); returns the parent element of the current element that you have clicked.
If you want to use inside any function then pass your event and call the function like this :
function yourFunction(event){
var parentElement = getParent(event);
}
var _RemoveBtn = document.getElementsByClassName("remove");
for(var i=0 ; i<_RemoveBtn.length ; i++){
_RemoveBtn[i].addEventListener('click',sample,false);
}
function sample(event){
console.log(event.currentTarget.parentNode);
}
$(document).on("click", function(event){
var a = $(event.target).parents();
var flaghide = true;
a.each(function(index, val){
if(val == $(container)[0]){
flaghide = false;
}
});
if(flaghide == true){
//required code
}
})

Is there a way to create an element and bind an event to it?

Is there a way I could use JavaScript to create an element, that when a user writes in it (oninput) I could display the text in the console? For example, it would be something like this:
<textarea oninput="print(this);"></textarea>
<script>
function print(e) {
console.log(e.value);
}
</script>
My function is a little bit more complex but you get the idea. What I want is to create the <textarea> element using JavaScript and then set an input event on it and pass it the this object.
This should explain the procedure pretty clearly:
// Selects an existing element in the DOM
const theParentElement = document.getElementById("container");
// Makes our new element
const newTextArea = document.createElement("textarea");
// Adds the new element to the DOM
theParentElement.appendChild(newTextArea);
// Calls printText when the textarea receives key input (or actually, ANY input)
newTextArea.addEventListener("input", printText);
// The listener gets a reference to the triggering event. Let's call it `event`
function printText(event){
// The event's `target` property holds the element where the event happened
const localReferenceToTheTextArea = event.target;
// The text of a textarea element lives in its `value` property
const text = localReferenceToTheTextArea.value;
console.log(text);
}
<div id="container"></div>
You could do this:
var textarea = document.createElement("textarea");
Then bind an event listener to your newly created element:
textarea.addEventListener("input", function () { /*Do the thing*/ });
That way, the event listener would always be binded to the element you've created.
I hope this helps you in some way. :)
if I understood you correctly you can do something like this
var myTextarea = document.createElement("textarea")
myTextarea.setAttribute("oninput", "print(this);")
// we get something like this => <textarea oninput="print(this);"></textarea>
document.body.appendChild( myTextarea )
console.log(myTextarea)
or you can use javascript EventListener
var myTextarea = document.createElement("textarea")
/* add the textarea to the body */
document.body.appendChild( myTextarea )
/* when we can use EventListener */
myTextarea.addEventListener("input", ()=>{
/* do something with value*/
console.log( myTextarea.vlaue )
})
<textarea id="area"></textarea>
<script>
const textArea = document.getElementById("area"); // Defines `textArea`
textArea.addEventListener("input", e => {
console.log(e.target.value);
});
</script>
Well first, you put set a variable to the element you want to create. In your case, <textarea>
var textareaElement = document.createElement("textarea");
Then, set the oninput like this:
textareaElement.setAttribute("oninput", "print(this)");
Lastly, add the element to the body:
document.body.appendChild(textareaElement);
Put together:
function print(e) {
console.log(e.value);
}
var textareaElement = document.createElement("textarea");
textareaElement.setAttribute("oninput", "print(this)");
document.body.appendChild(textareaElement);

attach event handler to dynamically added element

I have a javascript code, which adds an element dynamically and event handler to it.this event handler is called (and vanishes) when the element is added.when I see the dynamically added element through inspector(to see if the event handler was added successfully or not) I can't find onchnage="texttol(eletext)" function added it it.
eletext = document.createElement("input");
eletext.type="text";
eletext.placeholder = "Type Here";
eletext.onchange=texttol(eletext);
event.target.appendChild(eletext);
Add your event handling once the element is actually in the DOM.
var eletext = document.createElement("input");
eletext.type = "text";
eletext.placeholder = "Type Here";
eletext.id = "eletext";
document.body.appendChild(eletext);
eletext.addEventListener('change', function(e) {
texttol(eletext.value);
}, false);
function texttol(str) {
alert('texttol function passes: ' + str);
}
With this line, you are calling the method texttol and attaching whatever it returns to the event handler.
eletext.onchange=texttol(eletext);
You need to use a closure
eletext.onchange = function() { texttol(eletext) };
even better, use addEventListener
i have the same issue but the mentioned solutions do not work.
The event handler function theme_onChange is executed on adding each element.
I have a Bootstrap dropdwn menu (#themeDropdownMenu) and want to fill it dynamically with button elements via looping over the "Themes" object properties.
function setThemes () {
var lstThemes = document.querySelector('#themeDropdownMenu');
var newItem;
for ( x in Themes ) {
newItem = document.createElement('button');
newItem.innerHTML = x;
newItem.classList.add('dropdown-item');
newItem.type='button';
lstThemes.appendChild(newItem);
newItem.addEventListener('click', theme_onChange(newItem) );
}
}
function theme_onChange (item) {
/* console.log("Theme: " + item.innerHTML); */
console.log (item);
}
Result:
console logs each added button element.

Adding an Event via jQuery to newly created DOM Element

I am trying to assign an event to a newly created DOM Element:
var Element = document.createElement("div");
$(document).on('click',Element,function() {
console.log("B");
});
After executing this code and clicking on the newly created div, nothing happens.
Any idea why?
I have also tried:
var Element = document.createElement("div");
$(Element).click(function(event) {
console.log("B");
});
You need to add the element to the DOM before it will receive events.
Here's one way to do it:
var $div = $('<div>')
.text('Click Me!')
.on('click', function() {
alert('Clicked!');
});
$(document.body).append($div);
// Now you can click on it and see the alert.
Since you're using jQuery...
var Element = $("<div/>").click(function() {console.log("B");}).appendTo('body');
Of course, append it where you need it...
Just bind your event on the body and pass your selector in parameter like this:
$('body').on('click','.foo',function() {
console.log("B");
});
var Element = document.createElement("div").className = "foo";
Here the codepen :
http://codepen.io/anon/pen/xvLqo

How can I attach event to a tag which is in string form?

I'm creating html on runtime like this:
var myVar = "<div id='abc'>some clickable text</div>"
Now, I want to attach some event, say onclick, to this div. How can I do that on next line? I'll add this to DOM later.
PS: I've to accomplish this without using JQuery.
Instead of building your div as a string, you'll want to use document.createElement('div'). This way you will have a real dom object, and can get and set it's propeties, including onClick
Will this help? Since you dynamically generate it, you know the control id of the DIV.
document.getElementbyId('abc').onClick = foo;
function foo()
{
alert("All your impl to go here");
}
Try building the div as a DOM element first.
var myVar = document.createElement("div"),
parentDiv = document.getElementById("parent_div");
parentDiv.appendChild(myVar);
myVar.innerHTML = "some clickable text";
if(myVar.addEventListener){
myVar.addEventListener("click", clickFn, false);
}
else if(myVar.attachEvent){
myVar.attachEvent("onclick", clickFn);
}
else{
myVar.onclick = clickFn;
}
The addEventListener method is standard, but not every browser plays nice with the standard.
EDIT: As mentioned, an element must be added to the DOM first.
Or you can use this technique: attach event to the document.body. Then if the event target is not the needed div than just do nothing. It is the same techinque jquery uses for its live function:
// crossbrowser event attachment function
function listen(evnt, elem, func) {
if (elem.addEventListener) {
elem.addEventListener(evnt, func, false);
}
else if (elem.attachEvent) {
var r = elem.attachEvent("on" + evnt, func);
return r;
}
else window.alert('I\'m sorry Dave, I\'m afraid I can\'t do that.');
}
// this is an analog of the jquery.live
var assignLiveEvent = function(id, evnt, callback) {
var handler = function(e) {
e = e || window.event;
e.target = e.target || e.srcElement;
if (e.target.id == id) {
//your code here
callback(e);
}
};
listen(evnt, document.body, handler);
};
var myVar = "<div id='abc'>some clickable text</div>";
assignLiveEvent("abc", "click", function(e) {
//your code here
});
// now you can add your div to DOM even after event handler assignation
Here is demo.
Brian Glaz is totally right but, if for some reason, you really need to do it this way, you have two options:
you can only add events to something that is already in the DOM, using pure javascript, so you would have to include it in the html like:
document.body.innerHTML += myVar;
and then, attach the event with
document.getElementById('abc').addEventListener('click', function(e){
//your code
}, 1);
With jQuery, you could use .live() to attach events to elements that are not yet present in the DOM:
$('#abc').live('click', function(e){
//your code here
});
so you could add the div later...

Categories

Resources