I'm struggling to create a button in javascript - javascript

var buttonDivEl = document.getElementById('buttonDiv');
var startFunctionEl = document.getElementById('startFunction');
startFunctionEl.onclick = myFunction;
function myFunction() {
startFunctionEl.remove();
var createButton = document.createElement("button");
createButton.innerHTML = "my new button";
document.buttonDivEl.appendChild(createButton);
}
<div id="buttonDiv"></div>
<button id="startFunction">Click</button>
My HTML is just a button (id of startFunction) inside of a div (id of buttonDiv)
I'm trying to make it so when I click the startFunction button, it will remove it and add a new button inside of buttonDiv, but it doesn't seem to be working properly. if I replace the following code:
document.buttonDivEl.appendChild(createButton);
with
document.body.appendChild(createButton);
it works, but I want it to append to the buttonDiv specifically, not the body.

Change your code from:
document.buttonDivEl.appendChild(createButton);
To:
buttonDivEl.appendChild(createButton);

Related

Fill Form from an array

I would like to fill a form from an array and then to remove that element from the array.
So when I click on the 'Fill It' button - form should be filled and now array should be without that element.
The Problem is that the array is not popped, shifted or sliced and it always loads the same data into form fields.
Html form I have:
<h3><input class="FormControl" placeholder="Discussion Title"></h3>
<textarea class="Composer-flexible" placeholder="Write something..." style="height: 166.2px;"></textarea>
My code:
var button = document.createElement("button");
button.innerHTML = "Fill It";
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);
button.addEventListener ("click", function() {
var arr =
[["title1","post1"],["title2","post2"],["title3","post3"]];
var post = arr[0][1];
var title= arr[0][0];
document.getElementsByClassName("FormControl")[0].value=title;
document.getElementsByClassName("Composer-flexible")[0].value = post;
var arr=arr.slice(1);
console.log(arr);
});
Fiddle link:
https://jsfiddle.net/q1vc26oe/2/
After I fill it I have to review it a little bit and then I would submit it.
But problem occurs next time when I load html page and try to fill the same form but this time with 'title2' and 'post2' it loads 'title1' and 'post1' cause the array is not popped, shifted or sliced.How to do that?
In addition (it would be the next step when I make sure that script is running well) how to submit it, not automatically, but after 15 seconds cause I'd like to have a brief review before submitting (this is not big priority right now so you can add to your answer or not....)
This will be your working code: -
var button = document.createElement("button");
button.innerHTML = "Fill It";
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);
var arr = [
["title1", "post1"],
["title2", "post2"],
["title3", "post3"]
];
button.addEventListener("click", function() {
var post = arr[0][1];
var title = arr[0][0];
document.getElementsByClassName("FormControl")[0].value = title;
document.getElementsByClassName("Composer-flexible")[0].value = post;
arr = arr.slice(1);
console.log(arr);
});
You were creating a new array (named 'arr') every time on button click, so make sure you create the array only once.
And make sure you check if the array is empty on button click

Setting a onClick function to a dynamically created button, the function fires onload

I am currently creating a program which utilizes localStorage to create a site with a wishlist like functionality. However when I go to generate the html page that should create the wishlist with the photo of the item, the name and a button to remove said item from the list. But when I go to assign the onClick functionality to the button, the function fires on page load rather then on click. I have four main java script functions, one to add to the localstorage, one to remove from local storage, a helper function for removing and the one that will generate the wishlist page (where the problem is).
function genWishListPage(){
for (var i = 0; i < localStorage.length; i++) {
var item = getWishlist(i);
var name = document.createElement("p");
var removeButton = document.createElement("button");
var image = document.createElement("img")
image.src = item.image;
removeButton.innerText = "Remove from wishlist";
removeButton.onClick = RemoveFromWishList(item.name);
removeButton.setAttribute("ID","remove");
name.innerText = item.name;
document.body.appendChild(image);
document.body.appendChild(name);
document.body.appendChild(removeButton);
document.body.appendChild(document.createElement("BR"));
//removeButton.setAttribute("onclick", RemoveFromWishList(item.name));
//removeButton.addEventListener('click', RemoveFromWishList(item.name));
//document.getElementById("remove").addEventListener("click",RemoveFromWishList(item.name));
}
}
The commented parts are ways I have already tried and gotten the same bug.
Any help or advice is appreciated.
When you write
removeButton.onClick = RemoveFromWishList(item.name); you are assigning the return value of the function call to the onClick event. Instead you can write
removeButton.onClick = function() { RemoveFromWishList(item.name);}
You should assign a function to the onClick event listener.

Adding html tags inside JavaScript

I am trying to add <button id="mybtn"></button> around the some text link but I am not sure how to make it. I tried a bit with document.write but I think I am using it wrong. When I click this button some text it replaces 'ZZZ' with nothing. However the changed link something here has a plain formatting. What I want it to do is add the <button id="mybtn"> and</button> around it, so the changed button stays with the same look.
Input:
document.getElementById("DiacriticsButton").innerHTML = "some text";
Output should be something like:
document.getElementById("DiacriticsButton").innerHTML = <button id="mybtn">"some text"</button>;
The current full script:
<script>
bodyText=document.getElementById("bodytext").innerHTML;
clearText = bodyText.replace(/ZZZ/g, "");
FStr = clearText.search("some text");
do {
clearText = clearText.replace("something here","some text");
FStr = clearText.search("something here");
}
while(FStr!=-1);
function switchDiacritics() {
if (document.getElementById("bodytext").innerHTML == clearText) {
document.getElementById("bodytext").innerHTML = bodyText;
document.getElementById("DiacriticsButton").innerHTML = "something here";
} else {
document.getElementById("bodytext").innerHTML = clearText;
document.getElementById("DiacriticsButton").innerHTML = "some text";
}
}
</script>
Do you look for something like this
document.getElementById("DiacriticsButton").innerHTML = '<button id="mybtn">"some text"</button>';
It is also possible to add element like this
var btn = document.createElement("button");
btn.innerHTML = "some text";
document.getElementById("DiacriticsButton").appendChild(btn);
Are you doing anything to trigger this innerHTML change? Ex:
Wrapping the selection in window.onLoad{...}
OR
Wrapping it in a function to be triggered by an event listener. While if your goal is to simply place text within the tag in a static demeanour use the HTML attribute for a button with value="some text"

How To Create And Assign And Onclick Element To Another Element Created In JS

So, I am trying to make an element and then assign an onclick to it through JS.
Here is my code so far:
HTML
<div id = "Programs" onclick = "Cpb()">Programs</div>
JS
function Cpb() {
document.getElementById("AllBody").innerHTML = "";
var rh = document.createElement("h2");
var rht = document.createTextNode("Recent Programs");
rh.id = "Recentt";
var rh1 = document.createElement("h4");
var rh1t = document.createTextNode("test");
rh1t.onclick = window.open('website');
rh1.appendChild(rh1t);
rh.appendChild(rht);
}
So does anybody know how I can do this?
This javascript worked for me:
let h4Node = document.createElement("H4");
h4Node.innerHTML = "4th Header";
h4Node.onclick = function (){
alert('Oi!');
};
document.getElementById("demo").appendChild(h4Node);
Html:
<div class="demo"></div>
It will put an h4 element with an onclick event listener inside the demo div.
I think you want addEventListener.
Example:
rh1t.addEventListener('click', myHandlerFunction);
function myHandlerFunction () {
// ...
}
You can continue using onclick as you have in your code. But you'll need to do as I've done above and assign a function reference to it. Like this:
rh1t.onclick = myHandlerFunction;
function myHandlerFunction () {
window.open('website');
}

addEventListener programmatically is null

var button = document.createElement("button");
button.type = "button";
button.className = "button";
button.innerText = "OK";
button.addEventListener("click", function () {
console.log("Hello!");
}, false);
When I do this, the button never gets that event listener. I've tried attachEvent, button.onclick, and nothing seems to work. The button shows up fine with the class and text.
EDIT: So basically what I'm trying to do is programmatically show a "popup" array of divs.
Here is a screenshot of what it looks like: http://i.imgur.com/IqaOq.png, and I set it up like this: var x = new JMTK.Custom.MessageDialog(), then to add a popup, I just type x.addMessage({template: {type: JMTK.Custom.MessageDialog.templates.alert, title: "Alert title", message: "This is a message here", button1: {text: "Hello"}}})
This is the addMessage():
var content = document.createElement("div");
//htmlObject.template is the object that has all the info, 'this' is the scrim element that contains each "white" popup"
content.innerHTML = MessageDialogClass.html.alert(htmlObject.template, this).innerHTML
which calls this function:
alert: function (template, element) {
//Array of functions
var callbacks = MessageDialogClass.callbacks;
var alert = document.createElement("div");
var id = Date.now();
alert.id = id;
var header = document.createElement("h1");
header.innerText = (template.title ? template.title : "ALERT");
var paragraph = document.createElement("p");
paragraph.innerText = (template.message ? template.message : "No message specified")
var button = document.createElement("button");
button.type = "button";
button.className = "button";
button.innerText = (template.button1.text ? template.button1.text : "OK");
button.addEventListener("click", function () {
if (template.button1.callback) {
template.button1.callback();
}
//MessageDialogClass.popElement(id);
//delete callbacks.id;
}, false);
alert.appendChild(header);
alert.appendChild(paragraph);
alert.appendChild(button);
callbacks.id = alert;
return alert;
},
But again, when I click on the button, nothing happens, and in the DOM Explorer there is no onclick attribute.
It's hard to say what your solution might be. You've provided good detail about what you want to do with the button click, but I'm afraid there's something else at play. I wonder if you have an element in front of the button that keeps it from receiving the mouse click. I see you're in a WinJS project for Windows 8. You have really good dev tools in VS2012. Break just after you add the button to your DOM and go to the DOM Explorer and see if you find the button. Go to the JavaScript Console and see if you can access the button. See if you can add an event listener manually there. Try adding the button manually in your markup and then see if adding an event works. Hope one of these gets you to the solution. Good luck.
The issue was that I was creating a div in my 'alert' template, and then setting the innerHTML of another div to that div. So it wouldn't allow me to set the event listener because it wasn't part of the DOM.
So instead of doing
var content = document.createElement("div");
//htmlObject.template is the object that has all the info, 'this' is the scrim element that contains each "white" popup"
content.innerHTML = MessageDialogClass.html.alert(htmlObject.template, this).innerHTML
I just did
var content = document.createElement("div");
//htmlObject.template is the object that has all the info, 'this' is the scrim element that contains each "white" popup"
content = MessageDialogClass.html.alert(htmlObject.template, this).innerHTML
because alert is returning a div already. So yeah, it had to do with setting the innerHTML rather than just setting it equal to the DOM node.
I think you need append your button before set the event listener.

Categories

Resources