How can I add an onclick handler on a dynamic element? - javascript

Here is the important part of my JS code:
function createClose() {
var cButton = document.createElement("img");
cButton.src = "close.gif";
cButton.style.cursor = "pointer";
cButton.onclick = closeWindow;
document.getElementById("my_window").appendChild(cButton);
}
function closeWindow() {
document.getElementById("my_window").style.display = "none";
}
The image gets created and appended, but there is no onClick event invoked when it is clicked. I also tried using an anonymous function, but that didn't work either.
No, I'm not going to use jQuery (although I believe you that it's easier).

input.setAttribute('onclick','handleClick();');

input = document.getElementById("my_window").appendChild(cButton);
input.onclick = function() { yourFunction(); };
This question is almost a duplicate of "Add onclick property to input with JavaScript"
As an alternative way I've seen the use of input.setAttribute('onclick', 'yourFunction();'); too but cannot guarantee it works.

Related

toggle class on click Javascript

I want to know WHY its not working.
I have a bunch of classes called yellow.
I then add an event listener to them with a callback function to activate upon clicking. What am I not seeing here? :(
function test(){
var allYellow = document.querySelector('.yellow');
allYellow.addEventListener('click', function(){
this.classList.toggle = 'testyellow';
})
}
test();
In JavaScript..
function myFunction() {
var element = document.getElementById("myDIV");
element.classList.toggle("mystyle");
}

How can we pass an element to event handler in 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);
}

jQuery nested functions

I am still new to JavaScript and jQuery, so I am confused as to why the following code is not working as I anticipated. All I am trying to do is save input on a button click (id=recordInput) and display it with another button click (id=displayInput). What I observe is that tempInput is stored, (the code works until that point) but assignment of displayInputs onclick attribute is not executed. My question is, can you not nest a $().click() call inside of another &().click() call?
<script>
$(document).ready(function () {
$('#recordInput').click(function(event) {
var tempInput = $('#testInput').val();
&('#displayInput').click(function(event) {
console.log(tempInput);
});
});
});
</script>
My thinking is this in pseudocode:
assign recordInput onclick attribute to the following function:
store tempInput
set displayInput onclick to alert the tempInput value
what is wrong with my thinking?
NOTE: I did not include any html tags but all of the ids are referenced correctly
It's not working because you have put & instead of $ here
$('#displayInput').click(function(event) {
Fixing this may work, but you shouldn't set event handlers this way. Because every time your first handler function is called it will set an event handler for the second one. You can try with your console.log and you will see that the number of console.log is increasing by every click on #recordInput. So you should better set it like this :
var tempInput;
$('#recordInput').click(function(event) {
tempInput = $('#testInput').val();
});
$('#displayInput').click(function(event) {
console.log(tempInput);
});
I would change
$(document).ready(function () {
$('#recordInput').click(function(event) {
var tempInput = $('#testInput').val();
&('#displayInput').click(function(event) {
console.log(tempInput);
});
});
});
to
$(function(){
var testInput = '';
$('#recordInput').click(function(){
testInput = $('#testInput').val();
});
$('#displayInput').click(function(){
if(testInput !== ''){
console.log(testInput);
}
});
});
You are using & instead of $. Of course, you don't have to format the code exactly like I did.

Why is the button disapearing?

The text "Now I'm here..." is supposed to disappear when the button is clicked, not the button itself.
<div id="alpha">Now I'm here...</div>
<button type="button" onclick="remove()">Remove</button>
<script>
function remove()
{
var element = document.getElementById("alpha");
element.parentNode.removeChild(element);
}
/*function add()
{
var ele = document.createElement("p");
var text = document.createTextNode("This is new text");
ele.appendChild(text);
var location = document.getElementById("alpha");
location.appendChild(ele);
}*/
</script>
There is another function called remove that is interfering with your function.
Rename your function and it works fine:
http://jsfiddle.net/fL3gZ/
<div id="alpha">Now I'm here...</div>
<button type="button" onclick="Myremove()">Remove</button>
<script>
function Myremove()
{
var element = document.getElementById("alpha");
element.parentNode.removeChild(element);
}
</script>
What's happening is remove() is being called on the button itself! HTMLElement.prototype.remove is an existing function (in some browsers)! Oh god!
var button = document.getElementsByTagName("button")[0];
// surprise! this is what's actually happening
button.remove();
Check out this alternative approach. See: fiddle
Change HTML to
<div id="alpha">Now I'm here...</div>
<button type="button">Remove</button>
Then use this JavaScript
function remove(id) {
var elem = document.getElementById(id);
if (elem) elem.parentNode.removeChild(elem);
}
var button = document.getElementsByTagName("button")[0];
button.addEventListener("click", function(event) {
remove("alpha");
event.preventDefault();
});
A couple things about this:
I'm favoring a more unobtrusive approach
The remove function is single purpose, and reusable
It will work in more browsers
You won't run into WTFs like you just experienced
remove() is already an excisting javascript method, so you are actually calling that method on your button instead of calling the function.
Just rename the function and it will be fine.
Fiddle: http://jsfiddle.net/WkUqT/7/
function removeText()
{
var element = document.getElementById("alpha");
element.parentNode.removeChild(element);
}
You are probably using chrome as your browser to test that code. Elements in chrome have a self-removal, .remove() method which removes the element itself from its container.
This is the main reason why the code above removes the button, because of this the appended event in your onclick() declaration was not invoked because the element invoking the event does not exist anymore. Try changing the name of your function to removeElement().

how to call onclick function on dynamically created button in javascript

var del = document.createElement('input');
del.type = 'button';
del.name = 'delll';
del.value = 'del';
del.onClick = 'alert("hi javascript")';
Here I have dynamically created a input type BUTTON and now I want to call function on button click event. I am using onClick(); function for this. In the above code all is working fine but del.onclick is not working as I want (for generating alert for demo)
I am not using any jquery code in this program so please don't use any jquery code.
set the onclick (all lower case) to an anonymous function
del.onclick = function(){ alert('hi javascript');};
note the function is not in quotes like other attributes
del.onclick = function () {
alert("hi jaavscript");
};
Use small "C" in onClick and pass a function for it.
Demo here
Try like this
var del = document.createElement('input');
del.setAttribute('type', 'button');
del.setAttribute('name', 'delll');
del.setAttribute('value', 'del');
del.setAttribute('onClick', 'alert("hi jaavscript")');
So to answer the question in details:
del.onclick = '' does not "execute" something within quotes.
If you want to execute/call a function, you would want to pass the function as a parameter.
i.e
del.onclick = function() { alert('hi there!')}

Categories

Resources