I want to break and center after each button, any suggestions? setAttribute did not work and does not add the breaks
for (var j = 0; j <= 6; j++) {
var btn = document.createElement("BUTTON");
var t = document.createTextNode(sm[j] + " " + sy[j]);
btn.appendChild(t);
document.body.appendChild(btn);
}
jsfiddle
HTML
<div id='theParent' class='center_the_stuff'>
</div>
JS
function addInput(type, value, name, id, onclick, parentId) {
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.type = type;
element.value = value; // Really? You want the default value to be the type string?
element.name = name; // And the name too?
element.id = id;
element.onclick = onclick;
var parent = document.getElementById(parentId);
//Append the element in page (in span).
parent.appendChild(element);
}
function addBreak(parentId) {
var br = document.createElement("br");
var parent = document.getElementById(parentId);
parent.appendChild(br);
}
window.onload = function () {
for (var j = 0; j <= 6; j++) {
var temp = 'mybutton' + j;
addInput('button', temp, temp, temp, undefined, 'theParent');
addBreak('theParent');
}
}
CSS
.center_the_stuff {
text-align: center;
}
Related
I am trying to change the css property of the "node"-class by clicking on the div inside of it which got the class "expand".
When I click on the "expand" div inside the "note", I want to go to parent "note" for changing it size:
var text = document.getElementById("text");
var add = document.getElementById("add");
var notespace = document.getElementById("notespace");
var expand = document.getElementsByClassName("expand");
var notes = document.getElementsByClassName("note");
add.addEventListener("click", function () {
var textValue = text.value;
var p = document.createElement("p");
p.innerHTML = "<div class='note'>" + textValue +
"<br/><br/><div class='expand'> Expand </div></div>";
notespace.appendChild(p);
text.value = "";
for (var i = 0; i < expand.length; i++) {
expand[i].addEventListener("click", function () {
notes[i].style.size = "3000px";
})
}
})
You have to re-get the values of expand and notes, because after you add them to your html, the two variables expand and notes, dont know yet that you have added them and they don't contain them. ( you also have to removee the eventlistner otherwise you're gonna get a bugg at approximately twelve notes added :D because you will have too many eventListners on each element
var text = document.getElementById("text");
var add = document.getElementById("add");
var notespace = document.getElementById("notespace");
var expand = document.getElementsByClassName("expand");
var notes = document.getElementsByClassName("note");
add.addEventListener("click", function(){
var textValue = text.value;
var p = document.createElement("p");
p.innerHTML = "<div class='note'>" + textValue + "<br/><br/><div class='expand'> Expand </div></div>";
notespace.appendChild(p);
text.value = "";
for( var i = 0; i < expand.length; i++){
const note = notes[i];
expand[i].addEventListener("click", function() {
note.style.size = "3000px";
note.style.backgroundColor = "red";
});
}
})
#notespace {
width: 100%,
height: 100%,
background: grey,
}
<button type="button" id="add">add</button>
<input id="text"/>
<div id="notespace">
</div>
You can use the parentNode attribute :
for( var i = 0; i < expand.length; i++){
expand[i].addEventListener("click", function(){
this.parentNode.style.size = "3000px";
})
}
Or the closest() method :
for( var i = 0; i < expand.length; i++){
expand[i].addEventListener("click", function(){
this.closest(".note").style.size = "3000px";
})
}
Note that closest() is not supported on IE.
I want to create buttons and add classes to those button after creation
I am working on below code !1 Please Help me out :)
Will this work?
$("#"+element.id).addClass(".btn");
Thank you in advance !!
for (var i = 0; i < 9; i++) {
add(i);
}
function add(i) {
var element = document.createElement("input");
element.type = "button";
element.value = i;
element.name = i + 1;
element.id = "btn" + i;
element.onclick = function() {
window.move(i);
};
var append = document.getElementById("append");
append.appendChild(element);
alert(element.id);
$("#" + element.id).addClass(".btn");
}
You can add classes in javascript like that:
element.className += 'className';
If you are using jQuery then what you did is correct, except the dot you put into addClass function. So instead of:
$(element).addClass('.className');
You do:
$(element).addClass('className');
I think you should use without dot.
$("#"+element.id).addClass("btn");
You can just use the classList.add method on the element you create.
for (var i = 0; i < 9; i++)
{
add(i);
}
function add(i) {
var element = document.createElement("input");
element.type = "button";
element.value = i;
element.name = i + 1;
element.id="btn"+i;
element.classList.add("btn");
element.onclick = function () {
window.move(i);
};
var append =document.getElementById("append");
append.appendChild(element);
}
You can add class directly by accessing "className" property.
var element = document.createElement("input");
element.type = "button";
element.className = "clr-red";
Refer here for more
you just type the class name only
addClass("btn"); instead of addClass(".btn");
The first part of the code is working correctly, but now that each button appears, how do i add functionality to each of them? currently the only button which does something when pressed is always the last one, the rest do nothing.
Change it to
{
var output = "";
var data = JSON.parse(e.target.responseText);
for(var i=0; i<data.length; i++)
{
output = data[i].title + ' ';
var p = document.createElement("p");
var div = document.getElementById("response");
var textNode = document.createTextNode(output);
p.appendChild(textNode);
var button = document.createElement("button");
button.innerHTML = "Download";
p.appendChild(button);
div.appendChild(p);
button.addEventListener ("click", () =>
{
alert("Test");
});
}
}
You are adding the below code out side the for loop
button.addEventListener ("click", () =>
{
alert("Test");
} );
Keep the above code inside the for loop. So that for each button the event listener will be added.
Another way to approach this would be to add the callback function to the onclick variable of the elements prototype:
function doStuff() {
var output = "";
var data = JSON.parse(e.target.responseText);
for (var i = 0; i < data.length; i++) {
output = data[i].title + ' ';
var p = document.createElement("p");
var div = document.getElementById("response");
var textNode = document.createTextNode(output);
p.appendChild(textNode);
var button = document.createElement("button");
button.innerHTML = "Download";
// Adds the callback function here
button.onclick = () => {
// fill in your arrow function here...
alert("Test");
};
p.appendChild(button);
div.appendChild(p);
};
}
doStuff();
Here is a jsFiddle
You should use event delegation for dynamically added elements
// sample data
var data = [{
title: 'one'
}, {
title: 'two'
},{
title: 'three'
}];
var output = "";
for (var i = 0; i < data.length; i++) {
var output = data[i].title + " ";
var p = document.createElement("p");
var div = document.getElementById("response");
var textNode = document.createTextNode(output);
p.appendChild(textNode);
var button = document.createElement("button");
// added output to button text for identification
button.innerHTML = output + " Download";
p.appendChild(button);
div.appendChild(p);
}
// Get the parent element, add a click listener
document.getElementById("response").addEventListener("click", function(e) {
// e.target is the clicked element!
// If it was a button
if (e.target && e.target.nodeName == "BUTTON") {
// Button found! Output the identifying data!
// do other work on click
document.getElementById("display").innerHTML = e.target.innerHTML + " Clicked";
}
});
<div id="response"></div>
<div id="display">Display</div>
I'm dynamically creating 3 buttons. How can I pass an argument tohandlerX?
So basically I want the values in the category Array to be passed on to the handlerX eventListener.
Example:
When myBtn1 is clicked, I want the alert to be "fur_",
When myBtn3 is clicked, I want the alert to be "fas_"
var btns = '';
var category = ["fur_", "fts_", "fas_"];
for (i = 1; i < category.length; i++) {
btns += '<button type="button" class=' + category[i] + ' id= "myBtn' + i + '">.....</button>';
}
var div = document.getElementById('div');
div.innerHTML = btns;
var handlerX = function () {
alert('Clicked'); //get value from the 'category' Array
};
var buttons = div.querySelectorAll('button');
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', handlerX, false);
}
The answers given so far are good and should solve your problem. Just thought I'd add this one because I think it's a solution more in line with what you were asking for: Make your handlerX return a function like so:
var handlerX = function (param) {
return function() {alert(param);};
};
var buttons = div.querySelectorAll('button');
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', handlerX(category[i]), false);
}
Edit: Here's a Fiddle
If you're willing to extract it from the class attribute, then:
var handlerX = function () {
alert(this.getAttribute('class'));
};
Or you better associate it with some data- attribute. For example:
for (i = 1; i < category.length; i++) {
btns += '<button type="button" data-category="' + category[i] + '" class=' + category[i] + ' id= "myBtn' + i + '">.....</button>';
}
Then:
var handlerX = function () {
alert(this.getAttribute('data-category'));
};
See Fiddle
EDIT:
then i would reccomend adding an attibute: data-category="fur_" for example, and access that from your event handler:
this.getAttribute('data-category')
in hadlerX there is a "this" that is the element that was clicked. You can access its getAttribute("class") to get the class EDIT:this, not self
var fragment = document.createDocumentFragment(),
categories = ["fur_", "fts_", "fas_"],
btn;
function onClickBtn() {
alert(this.getAttribute("data-category"));
}
for (var i = 0; i < categories.length; i++) {
btn = document.createElement("button");
btn.id = "myBtn" + string(i);
btn.setAttribute("data-category", category[i]);
btn.addEventListener("click", onClickBtn);
fragment.appendChild(btn);
}
var div = document.getElementById('div');
div.appendChild(fragment);
In a dinamically generated "ol" :
document.getElementsByTagName('ol');
for (i = 0; i < len; i++){
var newLi = document.createElement("li");
var link = document.createElement('a');
link.href = "#";
link.innerHTML = (results.rows.item(i).location + "-" + results.rows.item(i).datte);
newLi.appendChild(link);
olnew[0].appendChild(newLi);
i need find the "li" clicked, i use jquery library only for this function, i am searching for the same functionality in javascript, but at momento i have not idea how i can code it. thx
var ss;
ss=$("#idfromOl");
ss.click(clickhecho);
}
function clickhecho()
{
var $all_lis = $('li');
$all_lis.on('click', function() {
var index = $all_lis.index(this);
});
}
try this:
function createfunc(i) {
return function() { alert(i); };
}
for (i = 0; i < len; i++){
var newLi = document.createElement("li");
var link = document.createElement('a');
link.href = "#";
link.innerHTML ="test"
newLi.appendChild(link);
// just add onclick event; use createFunc to create function closure (otherwise 'i' would always be the last 'i'
newLi.onclick = createfunc(i);
olnew[0].appendChild(newLi);
}
I might be mistaken, but is this what you are looking for?
var elements = document.getElementsByTagName('li');
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', function (e) {
$("#clickedLi").text(e.srcElement.id);
});
}
It appends an event called addEventListener to every li element.
Inside each li element there is an click event given as a parameter which contains the id of the li clicked.
demo: http://jsfiddle.net/DUzMc/1/
Your first part of script is incomplete, so I did a short script to generate a dynamic list.
Basicly you were looking for addEventListener():
var elements = 10;
ol = document.createElement('ol');
for(i = 1; i <= elements; i++){
var li = document.createElement('li');
var a = document.createElement('a');
a.setAttribute('href', '#');
a.text = 'Link ' + i;
li.appendChild(a);
ol.appendChild(li);
a.addEventListener("click", who, false); // THIS IS THE IMPORTANT PART
}
document.getElementsByTagName('body')[0].appendChild(ol);
function who(e){
var myTarget = e.target;
myTarget.text = "clicked!";
}
The easiest way is to include the event while generating the list:
document.getElementsByTagName('ol');
for (i = 0; i < len; i++){
var newLi = document.createElement("li");
var link = document.createElement('a');
link.href = "#";
link.innerHTML = (results.rows.item(i).location + "-" + results.rows.item(i).datte);
// Add this
link.onclick = function(index) { return function() {
// do something with index variable
}}(i);
newLi.appendChild(link);
olnew[0].appendChild(newLi);
Note I use a local variable index instead of i, this is because when the item is clicked the value of i will be different (equal to len).