Newly created button (by createElement("Button")) activates itself. How to stop that? - javascript

In hmtl file I have a simple button
<body>
<button type="button" onclick="create_button()">Create button</button>
</body>
and in js file I have two functions
function create_button() {
var new_button = document.createElement("Button");
new_button.innerHTML = "Pop the alert";
new_button.type = "button";
new_button.onClick = my_function();
document.body.appendChild(new_button);
};
function my_function() {
alert("Not so fast");
};
Obviously it should work in following manner:
Click Create button -> Pop the alert button appears
Click Pop an alert -> "Not so fast" alert appers
However after I click Create button, the alert appears. I guess that Pop an alert button activates itsef, but I don't know how to prevent it from doing so.
Edit. I actually have a problem in which my_function depends on some parameters.
So lets say we have following situation:
function my_function(x) {
alert("I like " + x);
};
and I want to create button which does my_function("Stack Overflow").
Based on this SO discussion I used
new_button.addEventListener('click', function(){my_function("Stack Overflow");});
and it works.

You can use new_button.addEventListener('click',my_function);. So my_function would be referenced, but not called imidiatley:
function create_button() {
var new_button = document.createElement("Button");
new_button.innerHTML = "Pop the alert";
new_button.type = "button";
new_button.addEventListener('click', my_function);
document.body.appendChild(new_button);
};
function my_function() {
alert("Not so fast");
};
<button type="button" onclick="create_button()">Create button</button>
After the edit
If your my_function have arguments, you have to wrap it into anonymous function, so it would be:
new_button.addEventListener('click',function(){
my_function(5);
});
Or
new_button.onclick=function(){
my_function(5);};

As extend to #itsgoingdown answer:
function create_button() {
var new_button = document.createElement("Button");
new_button.innerHTML = "Pop the alert";
new_button.type = "button";
new_button.addEventListener('click', function () {
var x = ' sport'
my_function(x)
});
document.body.appendChild(new_button);
};
function my_function(x) {
alert("Not so fast" + x);
};

Related

Javascript. Pressing button - call function

function greet () {
console.log ("Hi there!");
}
function addButton () {
document.createElement("[wanted_HTML_tag_here]");
}
There is separate HTML document. It has a button that calls the function addButton() upon being pressed. Said function has to create a new element and append it to the element. Pressing this new button has to call the function greet().
I try with [element_name].setAttribute("[attribute]", "[attribute_value]") but useless
Also trying document.[element_to_append_into].appendChild([element_being_added]); but same
Here's a complete working example (it is one way of doing it):
<html lang="en">
<body>
<button id="btn">Create Button</button>
</body>
<script>
function greet() {
console.log('Hi there')
}
function addButton() {
const button = document.createElement('button')
const buttonTextNode = document.createTextNode('Click')
button.appendChild(buttonTextNode)
button.onclick = greet
document.body.appendChild(button)
}
// get the button that creates other buttons
const buttonCreator = document.getElementById('btn')
buttonCreator.onclick = addButton
</script>
</html>

Why can't I assign a function to Object.prototype.click?

I know how to create dynamic elements and append them to existing ones, and how to create click events and attach them. See my snippet below
var container = document.getElementById("container");
var btn1 = document.createElement("button");
var btn2 = document.createElement("button");
btn1.innerHTML = "button 1";
btn2.innerHTML = "button 2";
btn1.onclick = function(){ console.log('button 1 clicked'); }; // this works fine
btn2.onclick = function(){ console.log('button 2 clicked'); };
container.append(btn1);
container.append(btn2);
<div id="container"></div>
I am trying to mimic jQuery's .click() behavior. (I don't want to use jQuery, I just need a shorter way of assigning click events to dynamically created elements).
What I mean, is I would like to extend Object.prototype by adding a function that accepts a function as the parameter, and all it does behind the scenes is assign it to the object's .onclick property.
However, the code runs, but no click event is triggered, and no error is reported.
var container = document.getElementById("container");
var btn1 = document.createElement("button");
var btn2 = document.createElement("button");
btn1.click(function(){ console.log('button 1 clicked'); }); // this doesn't work
btn2.click(function(){ console.log('button 2 clicked'); }); // this doesn't work
btn1.innerHTML = "button 1";
btn2.innerHTML = "button 2";
container.append(btn1);
container.append(btn2);
Object.prototype.click = function(fn) {
console.log('this function never gets executed');
this.onclick = fn;
}
<div id="container"></div>
I can tell that my extension of Object.prototype.click has not been executed since the console.log() never happens.
Is it because Object.prototype.click is reserved? If so, why am I not being able to override its definition?
What am I doing wrong?
There are two issues. First, you should assign to the prototype before you try calling btn1.click(), else the native .click() will be called. (The native .click() method of an element programatically triggers a click event on that element.)
The other problem is that btn1 is an element, not just an object, and HTMLElements have a click property on their prototype. So, even if you assign to Object.prototype.click, HTMLElement.prototype.click will be seen sooner in the prototype chain, and so your Object.prototype.click will be ignored. You'll have to either overwrite HTMLElement.prototype.click or HTMLButtonElement.click:
var container = document.getElementById("container");
var btn1 = document.createElement("button");
var btn2 = document.createElement("button");
HTMLElement.prototype.click = function(fn) {
console.log('setting up click event');
this.onclick = fn;
}
btn1.click(function(){ console.log('button 1 clicked'); });
btn2.click(function(){ console.log('button 2 clicked'); });
btn1.innerHTML = "button 1";
btn2.innerHTML = "button 2";
container.append(btn1);
container.append(btn2);
<div id="container"></div>
But mutating the built-in objects like this isn't very good practice and can lead to things breaking (such as if a library assumes that .click() will trigger the normal HTMLElement.prototype.click function) - you might consider assigning click property directly to the instance, rather than to the prototype:
var container = document.getElementById("container");
function myCreateElement(type) {
const elm = document.createElement(type);
elm.click = function(fn) {
console.log('setting up click event');
this.onclick = fn;
}
return elm;
}
var btn1 = myCreateElement("button");
var btn2 = myCreateElement("button");
btn1.click(function(){ console.log('button 1 clicked'); });
btn2.click(function(){ console.log('button 2 clicked'); });
btn1.innerHTML = "button 1";
btn2.innerHTML = "button 2";
container.append(btn1);
container.append(btn2);
<div id="container"></div>

How do you dynamically display a button using JavaScript?

Below I have code where I am trying to dynamically create a button using Javascript (I don't want to just create a button with HTML) When I locally run the web page no button appears.
The buttonActionFunction is a separate function I have (that is fully working) where an image appears when the button is clicked.
Also how do I add to that code so that once the button is clicked that the button deactivates so they can't click it again?
<script>
function buttonFunction() {
var button= document.createElement("button");
button.appendChild(document.createTextNode("Click Me"));
button.onclick=buttonActionFunction();
document.getElementById("divId").appendChild(button);
}
buttonFunction();
</script>
function createButton(context, func) {
var button = document.createElement("input");
button.type = "button";
button.value = "Click Me";
button.onclick = func;
context.appendChild(button);
}
function functienaam()
{
createButton(document.body, functienaam);
}
createButton(document.body, functienaam);
jsfiddle : https://jsfiddle.net/fv42orad/1/
Add <div id="divId"></div> to your html
As for disabling the button on click
function buttonActionFunction(e) {
e.target.disabled = true
}
and button.onclick=buttonActionFunction; not
button.onclick=buttonActionFunction();
Based on #lordKain answer I've updated the code to disable the previous button when it is clicked, as shown bellow:
function createButton(context){
var button = document.createElement("input");
button.type = "button";
button.value = "Click Me";
button.onclick = function() {functienaam(button)};
context.appendChild(button);
}
function functienaam(button)
{
createButton(document.body);
button.disabled = true;
}
createButton(document.body);
https://jsfiddle.net/5unLc5xr/

How to set a javascript function to an element with no postback

I created an input type=file and I need to connect it to my Javascript function, the problem is that I get postback (I don't need server-side), I tried different ways (code below).. maybe I set the function wrong... Help please
++ createMyButton is fired from another function and works fine.
//JAVASCRIPT
function createMyButton(){
var deleteBtn = document.createElement('input');
deleteBtn.type = "button";
deleteBtn.title = "Delete";
//1 try
deleteBtn.onclick = 'deleteItem()';
//2 try
deleteBtn.onclick = 'deleteItem();return false';
}
//FUNCTION
function deleteItem() {
alert("delete");
}
These are the issue I seen
1.deleteBtn.onclick = 'deleteItem();' are you missing quote "''here ?
2
. If u want to bind event to element use addEventListener to for
E.g
var deleteBtn = document.createElement('input');
deleteBtn.type = "button";
deleteBtn.title = "Delete";
// you missed button value here
deleteBtn.value = "Delete";
deleteBtn.addEventListener('click', deleteItem);
//FUNCTION
function deleteItem() {
var btn = this; // you can use button here
alert("delete");
}
JSBIN EXAMPLE

Range of variables or sth else? very beginning JS

Sorry for mistakes - my first post. I'd like to click on the 'Try it' button and change the type of the first 'ok' input. After this change I'd like to click the 'Try it' button again and change the type of the element with id="inputt" to INPUT again. I think it's sth wrong with the range of my variable done which tells if i have 2 buttons or input and button.
//JS
window.onload = function Load(){
var done = false;
var foo = document.getElementById('g');
if(!done){
foo.onclick = Change1;
}else{
foo.onclick = Change2;
}
};
function Change1(){
inp = document.getElementById('inputt');
inp.setAttribute('type', 'button');
done = true;
}
function Change2(){
but = document.getElementById('inputt');
but.setAttribute('type','input');
}
//HTML
<input value="ok" id="inputt">
<p>Click the button below to set the type attribute of the button above.</p>
<button id="g">Try it</button>
The window.onload event is not going to get executed again, it only happens once when the window...loads
see if this is what you want.
http://jsfiddle.net/7W4Xw/1/
//JS
window.onload = function Load(){
var foo = document.getElementById('g');
foo.onclick = Change1;
};
function Change1(){
inp = document.getElementById('inputt');
inp.setAttribute('type', 'button');
var foo = document.getElementById('g');
foo.onclick = Change2;
}
function Change2(){
but = document.getElementById('inputt');
but.setAttribute('type','input');
}

Categories

Resources