Create a Button in Javascript - javascript

Hey i want to create a button like this:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="button" value="click-me" id="myButton" onclick="myFunction()">
</body>
</html>
but i want to create from javascript, and i'm doing something really wrong cause my button does not seem
var MyButton = document.createElement("BUTTON");
MyButton.id = "Mybuttonid";
MyButton.className = "MyButtonclass";
MyButton.onclick("myFunction()");
Div.appendChild(MyButton); //i have others things working in this "Div" only this button doesn't appear

You've a misuse of onclick in the posted code, if you check the console you could notice the following message :
"Uncaught TypeError: MyButton.onclick is not a function"
To attach the click event using the onclick it should be :
MyButton.onclick = myFunction;
Else it will be better to attach the event using addEventListener() instead like :
MyButton.addEventListener("click", myFunction);
Hope this helps.
var Div = document.getElementById("my_div");
var MyButton = document.createElement("BUTTON");
MyButton.id = "Mybuttonid";
MyButton.className = "MyButtonclass";
MyButton.addEventListener("click", myFunction);
Div.appendChild(MyButton);
function myFunction(){
alert('test');
}
<div id="my_div"></div>

You are doing it wrong because Button does not exists(but MyButton exists).
Instead of :
var MyButton = document.createElement("BUTTON");
MyButton.id = "Mybuttonid";
MyButton.className = "MyButtonclass";
MyButton.onclick("myFunction()");
Div.appendChild(MyButton);

Use addEventListener to add click event to the button; And change Div.appendChild(button); to Div.appendChild(MyButton);
function myFunction(){
alert("here");
}
var Div = document.getElementById('div');
var MyButton = document.createElement("button");
MyButton.id = "Mybuttonid";
MyButton.innerHTML ="CLICK ME"
MyButton.className = "MyButtonclass";
MyButton.addEventListener("click", myFunction, false);
Div.appendChild(MyButton); //i have others think working in this "Div" only this button doesn't appear
<div id="div">
</div>

In both HTML and Javascript, you are declaring your onclick function the wrong way. Instead of
<input type="button" value="click-me" id="myButton" onclick"myFunction()">
it should be
<input type="button" value="click-me" id="myButton" onclick="myFunction()">
Which means that this piece of code in Javascript here:
MyButton.onclick("myFunction()");
Should be
MyButton.onclick = function(){ myFunction() };
By doing this and solving the typo that other users mentioned, it should work just fine.

Related

I dont understand why my code isnt working

I am trying to the value of a button once it is clicked. But for some reason, the console keeps giving me an error saying buttonValue.addEventListener is not a function!!!
The following is my code:
var buttonValue = document.querySelector('.btn').value
buttonValue.addEventListener('click', function(){
console.log(buttonValue);
});
and here is my HTML code!:
<div>
<button class='btn' value="1">1</button>
</div>
try this:
you should have placed add event listener on the element, not the value of the element
var button = document.querySelector('.btn')
buttonValue.addEventListener('click', function(){
console.log(button.value);
});

How to change button text when clicked?

I am running my website off of squarespace and I have a button that says "DELIVER ME" but when you click it, I want it to say "G.T.F.O" while the next page loads.
I don't have a code for this and need help writing one.
function changeButtonText(DELIVER ME, G.T.F.O.){
if (this.value== "DELIVER ME"){
this.value = "G.T.F.O.";
} else {
this.value = "DELIVER ME";
}
}
changeButtonText();
I want the button to say "DELIVER ME" until you click it, then once you click it the button will say "G.T.F.O."
I want the button to say "DELIVER ME" until you click it, then once you click it the button will say "G.T.F.O."
Given this button:
<input type="button" id="myButton" value="DELIVER ME">
You could do it like this:
const myButton = document.getElementById("myButton");
myButton.addEventListener("click", function() {
this.value = "G.T.F.O."
});
Or, if the button is like this:
<button id="myButton">DELIVER ME</button>
You would do:
const myButton = document.getElementById("myButton");
myButton.addEventListener("click", function() {
this.innerText = "G.T.F.O."
});
function changeText() {
return document.querySelector("#button").innerHTML = "New text";
}
document.addEventListener("click", changeText);
<button type="button" id="button">Text</button>
most of the answer can solve your particular problem but I just want to add more information about selecting htmlElement.
in VanillaJS(pure Javascript) DOM. you can select element with 3 DOM method.
Select by ID's attribute
elem = document.getElementById("id")
Select by class attribute
elem = document.getElementsByClassName("class")
Select by TagName
elem = document.getElementByTagName("Tag")
and 1 more extra way which used.
elem = document.querySelector(selector)
selector can be one of ".class","#id", or "Tags"
Thanks
<button type="button" id="btn" onclick=changeButtonText()>deliver me</button>
<script>
function changeButtonText(){
document.getElementById("btn").innerHTML = "GTFO";
}
</script>

How can I remove every listener from a page?

I know how to remove a listener from an element, but how can I remove every event listener from every element on the page?
A jQuery and pure JS solution would be nice.
I would suggest to look into the .off function of jQuery.
Also, based on this stackoverflow question, I would try to remove all every listeners with the following code
$("body").find("*").off();
Hope this could help you.
You can try this too.
http://jsfiddle.net/LkfLezgd/9/
$("#cloneButton").click(function() {
$('body').replaceWith($('body').clone().html());
});
You can loop through the form elements as below to remove the event listeners at your preferred way.
The fastest way to do this is to just clone the node which will remove all event listeners but this won't remove if 'onclick' attribute is used.
document.getElementById('button').addEventListener('click', onClick, false);
function onClick() {
console.log('Form clicked');
var form = document.getElementById('myForm');
for(var i = 0; i < form.elements.length; i++){
var elm = form.elements[i];
removeEvents(elm);
}
}
function removeEvents(elm) {
// The fastest way to do this is to just clone the node, which will remove all event listeners:
var new_element = elm.cloneNode(true);
elm.parentNode.replaceChild(new_element, elm);
}
<form id="myForm">
<input id="button" type="button" value="Click" />
</form>
Just Clone the HTML dom, that will remove the events by default.
Here is an example.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#EventButton").click(function () {
alert("Click event worked");
var old_element = document.documentElement;
var new_element = old_element.cloneNode(true);
old_element.parentNode.replaceChild(new_element, old_element);
});
});
</script>
</head>
<body>
<button id="EventButton">Remove Events</button>
</body>
</html>

Remove button and assign on click

I'm working on coding javascript and I'm kind of a noob here. This is my code:
<button onclick="test()">Click Me!</button>
<script>
function test()
{
var btn = document.createElement("BUTTON");
var name = document.createTextNode("Button");
btn.appendChild(name);
document.body.appendChild(btn);
btn.onclick = ex();
}
ex()
{
}
</script>
I want to do two things, and I can't seem to find a solution. I want to:
use the function "ex" to remove the button that says "Click Me!"
assign btn.onclick to the button I just created.
Can anyone help me with this?
EDIT: Although all you guys are trying to help me, I'm not sure you guys are quite understanding the question fully. So, expanding on the first request:
I want to use the function "ex" to delete the button "Click Me!" I want this button to be deleted from the page, and no longer visible.
Second:
I want the btn.click in the function "test" to only be assigned to the button created in the function "test." I've noticed that when you click "Click Me!" it runs the function "ex."
try this one
<script>
function test() {
var btn=document.getElementsByTagName('button')[0];
btn.attributes[0].value="ex()";
btn.innerText="second function";
}
function ex() {
console.log("ex executer");
}
</script>
<button onclick="test()">
click me!
</button>
<button onclick="test()">
Click Me!
</button>
<script>
function test(){
var btn = document.createElement("BUTTON")
var name = document.createTextNode("Button")
btn.appendChild(name);
document.body.appendChild(btn);
btn.onclick = ex;//() remove. btn.onclick is a handler i.e. a function object,
// not the result your ex() returns.
}
function ex(){//add function
this.style.color = 'red'; // makes text of the button red
// **ONLY if button IS clicked**
}
</script>

Javascript Dynamic Event Handling, Not Jquery

here is my code
<html>
<head>
<script type="text/javascript">
window.onload = function(){
sel = document.getElementsByTagName('select');
for(i=0;i<sel.length;i++)sel[i].onclick = function(){alert('');}
}
</script>
</head>
<body>
<div id="ss"></div>
<select></select>
<input type="button" onclick="document.getElementById('ss').appendChild(document.createElement('select'))"/>
</body>
</html>
"onclick" event working for static tag "Select" but not working for Dynamically created "Select". In other word i want to know what is alternate to .live of JQuery in Javascript.
Bind the event to a parent element, that already exists in the DOM:
document.body.addEventListener('click', function (e) {
if (e.target.tagName.toLowerCase() == 'select') {
alert('You clicked a select!');
}
});
JS Fiddle demo.
It would be slightly more sensible to bind the click to an element 'closer' to the form, and if you use getElementById() rather than getElementByTagName() it's more simple, since you don't have to worry about the index of the number you're binding to.
jQuery's live function works by using "Event Delegation". The basic idea is that you bind a listener on a parent element, which is guaranteed to exist when the page loads. Any element below that (with the exception of some) will fire off an event which can be caught by the parent listener. From there you would need to retrieve the target/sourceElement of the event and determine whether or not it's one you care about.
Something like this will work for listening to clicks. Just make sure that any new elements you are adding are located within the proper parent container and have an attribute which distinguishes them from the rest of the clickable elements.
<html>
<head>
<script type="text/javascript">
window.onload = function(){
// get the relevant container
var eventContainer = document.getElementById("EventContainer");
// bind a click listener to that container
eventContainer.onclick = function(e){
// get the event
e = e || window.event;
// get the target
var target = e.target || e.srcElement;
// should we listen to the click on this element?
if(target.getAttribute("rel") == 'click-listen')
{
alert("You clicked something you are listening to!");
}// if
};
};
</script>
</head>
<body>
<div id="EventContainer">
<input type="button" rel="click-listen" name="myButton" value="Listening to this button." />
<input type="button" name="anotherButton" value="Not listening." />
<p>I'm also listening to this a element: listening to this</p>
</div>
</body>
</html>
there's no need to bind the onclick handler to every select every time you add one.
I am not going to retype your whole page, but you'll see what's going on by reading following snippets:
function handler() {
alert('You clicked a select!');
}
window.onload = function(){
sel = document.getElementsByTagName('select');
for(int i= 0; i < sel.length; i++) {
sel[i].onclick = handler;
}
}
function addSelect() {
var slt = document.createElement("select");
document.getElementById('ss').appendChild(slt);
slt.onclick = handler;
}
<input type="button" onclick="addSelect();"/>
You're only setting the onclick when the window loads. All you need to do is put the code currently in the window.onload into a named function, then call it every time you add a new select.
here's the dumb way to do it:
<html>
<head>
<script type="text/javascript">
function update () {
sel = document.getElementsByTagName('select');
for(i=0;i<sel.length;i++)sel[i].onclick = function(){alert('');}
}
window.onload = update;
</script>
</head>
<body>
<div id="ss"></div>
<select></select>
<input type="button" onclick="document.getElementById('ss').appendChild(document.createElement('select'));update();"/>
</body>
</html>
You can use a cross-browser solution as shown below to add event handler dynamically
sel = document.getElementsByTagName('select');
for( i=0; i<sel.length; i++){
if (sel[i].addEventListener){
sel[i].addEventListener("click", clickHandler, false);
} else if (sel[i].attachEvent){
sel[i].attachEvent("onclick", clickHandler);
}else{
sel[i].onclick = clickHandler;
}
}
function clickHandler(event){
}

Categories