JavaScript adding event on element generated element with innerHtml - javascript

I want to add an event on an element does doesn't exist in the original HTML (created with innerHtml). When i click nothing happens.
const btnRemove = document.getElementById("remove");
btnMow.addEventListener("click", function mow() {
if (sMow === true) {
reqServices.push("Mow Lawn");
service.innerHTML += `
<div class="v1">
<p class="v3-text">Mown Lawn <span id="remove">remove</span></p>
<p class="v3-dollar"><span>$</span>20</p>
</div>`;
sMow = false;
total += 20;
totalC();
}
});
btnRemove.addEventListener("click", function remove() {
alert("HELLO");
});
I want to add a click event on the element with id remove.

Another way to do that is creating the elements instead of use the HTML code and a later search. This maybe useful if you, for example, don't want to add an id to the remove tag
btnMow.addEventListener("click", function mow() {
if (sMow === true) {
reqServices.push("Mow Lawn");
var div = document.createElement("div");
div.className = "v1";
service.appendChild(div);
var p1 = document.createElement("p");
p1.className = "v3-text";
div.appendChild(p1);
var p1Text = document.createTextNode("Mown Lawn ");
p1.appendChild(p1Text);
var p1Span = document.createElement("span");
p1Span.setAttribute("id", "remove");
p1Span.innerText = "remove";
p1Span.addEventListener("click", function remove() {
alert("HELLO");
});
p1.appendChild(p1Span);
var p2 = document.createElement("p");
p2.className = "v3-dollar";
p2.innerHTML = "<span>$</span>20";
div.appendChild(p2);
sMow = false;
total += 20;
totalC();
}
});
As you can see, creating the elements allow you do whatever you want with it. It's longer but you can use a helper function like this:
function appendTag(parent, tagName, className) {
var tag = document.createElement(tagName);
if (className)
tag.className = className;
parent.appendChild(tag);
return tag;
}
And rewrite as:
btnMow.addEventListener("click", function mow() {
if (sMow === true) {
reqServices.push("Mow Lawn");
var div = appendTag(service, "div", "v1");
var p1 = appendTag(div, "p", "v3-text");
p1.appendChild(document.createTextNode("Mown Lawn "));
var p1Span = appendTag(p1, "span");
p1Span.setAttribute("id", "remove");
p1Span.innerText = "remove";
p1Span.addEventListener("click", function remove() {
alert("HELLO");
});
var p2 = appendTag(p1, "p", "v3-dollar");
p2.innerHTML = "<span>$</span>20";
sMow = false;
total += 20;
totalC();
}
});

btnMow.addEventListener("click", function mow() {
if (sMow === true) {
reqServices.push("Mow Lawn");
service.innerHTML += `
<div class="v1">
<p class="v3-text">Mown Lawn <span id="remove">remove</span></p>
<p class="v3-dollar"><span>$</span>20</p>
</div>`;
sMow = false;
total += 20;
totalC();
}
const btnRemove = document.getElementById("remove");
btnRemove.addEventListener("click", function remove() {
alert("HELLO");
});
});

var btnremove = document.getElementById("remove");
write this before starting click event

Related

A function to remove a div element that contains specific text in Javascript?

I've written a simple code that takes text from the input field, stores it as a string in an array and creates a div with that same text every time the "add" button is pressed.
Then there's a "remove" button, that removes the item from array if the input matches the item in the array.
I need a function to remove the previously created div with the same text inside as the current input.
E.g. if I type "book1" press "add" - array gets 'book1' as a first item and a div "book1" is created, "book2", "book3" and so on. If I type 'book2' and press remove, it gets removed from the array and a respective div should be removed.
That last function I just can't figure out.
let addBtn = document.getElementById("add-btn");
let removeBtn = document.getElementById("rmv-btn");
let bookArray = [];
addBtn.addEventListener("click", addBook);
removeBtn.addEventListener("click", removeBook);
let innerDiv = document.body.newDiv.innerHTML
function addBook() {
newBook = document.getElementById("input").value;
if (newBook != '') {
bookArray.push(newBook);
addElement();
clear();
console.log(bookArray);
} else {
clear();
console.log(bookArray);
}
}
function removeBook() {
inputBook = document.getElementById("input").value;
for (i = 0; i < bookArray.length; i++) {
if (inputBook.toString() === bookArray[i].toString()) {
bookArray.splice([i], 1);
console.log(bookArray);
removeElement()
return;
} else {
clear();
}
}
console.log(bookArray);
}
function clear() {
document.getElementById("input").value = "";
}
function addElement() {
let newDiv = document.createElement("div");
newDiv.innerHTML = newBook;
my_div = document.getElementById("mydiv");
document.body.appendChild(newDiv, my_div);
}
function removeElement() {
alert("this bit needs working out");//???
}
<input type="text" id="input" />
<button id="add-btn">Add</button>
<button id="rmv-btn">Remove</button>
<div id="mydiv"></div>
</div>
You need to change how you are adding the div because it adding it outside and not as a child of my_div
let addBtn = document.getElementById("add-btn");
let removeBtn = document.getElementById("rmv-btn");
let bookArray = [];
addBtn.addEventListener("click", addBook);
removeBtn.addEventListener("click", removeBook);
function addBook() {
newBook = document.getElementById("input").value;
if (newBook != '') {
bookArray.push(newBook);
addElement();
clear();
console.log(bookArray);
} else {
clear();
console.log(bookArray);
}
}
function removeBook() {
inputBook = document.getElementById("input").value;
for (i = 0; i < bookArray.length; i++) {
if (inputBook.toString() === bookArray[i].toString()) {
bookArray.splice([i], 1);
console.log(bookArray);
removeElement(i);
return;
} else {
clear();
}
}
console.log(bookArray);
}
function clear() {
document.getElementById("input").value = "";
}
function addElement() {
let newDiv = document.createElement("div");
// count number of children in mydiv
let count = document.getElementById("mydiv").childElementCount;
// add an id
newDiv.id = 'mydiv-' + count;
newDiv.innerHTML = newBook;
my_div = document.getElementById("mydiv");
my_div.appendChild(newDiv, my_div);
}
function removeElement(el) {
// remove html element from dom
let my_div = document.getElementById("mydiv");
my_div.removeChild(my_div.childNodes[el]);
}
A workaround to remove book by the input value by user:
Modify the addElement function to:
function addElement() {
let newDiv = document.createElement("div");
newDiv.innerHTML = newBook;
newDiv.setAttribute('data-book-name', newBook); //new added line | setting data attribute
my_div = document.getElementById("mydiv");
document.body.appendChild(newDiv, my_div);
}
removeElement will be:
function removeElement() {
document.querySelector('[data-book-name="'+ newBook +'"]')?.remove();
}
But this will remove first book in the DOM. If you want to remove all books with same name use:
function removeElement() {
var books = document.querySelectorAll('[data-book-name="'+ newBook +'"]');
if(books.length == 0) return;
books.forEach(x => x.remove())
}

how to create several buttons dynamically in for loop

Here id my code. I want to append 4 buttons inside the specific div. In the other words, I want to put these 4 buttons inside ''. Now it works but they are not inside the div.
getmyItems function is a function that contains an array of information like: title, description , age ,... .
Help
getmyItems(param, function(data) {
var mtItem = JSON.stringify(data);
myItem = JSON.parse(mtItem);
var Item = document.getElementById('myItems');
for (var i = 0; i < myItem.results.length; i++) {
var buffer = "";
buffer += '<div class="act-time">';
buffer += '<div class="activity-body act-in">';
buffer += '<span class="arrow"></span>';
buffer += '<div class="text">';
buffer += '<p class="attribution">';
buffer += ''+myItem.results[i].title+'';
buffer += myItem.results[i].description;
buffer += '</p>';
buffer += '</div>';
buffer += '</div>';
buffer += '</div>';
var div = document.createElement('div');
div.innerHTML = buffer;
//var elem = div.firstChild;
Item.appendChild(div);
var btn = document.createElement('input');
btn.setAttribute('type', 'button');
btn.setAttribute('class', 'btn btn-danger');
btn.value = "Delete";
btn.onclick = (function(i) {
return function() {
var c=confirm('Are you Sure? ');
if (c==true)
doDelete(myItem.results[i].item_id);
};
})(i);
Item.appendChild(btn);
var show_btn=document.createElement('input');
show_btn.setAttribute('type','button');
show_btn.setAttribute('class','btn btn-primary');
show_btn.value="ShowInDetail";
show_btn.onclick=(function(i){
return function(){
showInDetail(myItem.results[i]);
window.location='showInDetail.html';
};
})(i);
Item.appendChild(show_btn);
var extend_btn=document.createElement('input');
extend_btn.setAttribute('class','btn btn-warning');
extend_btn.setAttribute('type','button');
extend_btn.value="Extend";
extend_btn.onclick=(function(i){
return function(){
extendItem(myItem.results[i]);
window.location='extendItem.html';
};
})(i);
Item.appendChild(extend_btn);
var bookmark=document.createElement('input');
bookmark.setAttribute('type','button');
bookmark.setAttribute('class','btn btn-primary');
bookmark.value='Bookmark';
bookmark.onclick=(function(i){
return function(){
var p={user_id:localStorage.getItem('user_id')};
window.localStorage.setItem('this_item_id', myItem.results[i].item_id);
getBookmarks(p, function(d){
var bk=JSON.stringify(d);
bk=JSON.parse(bk);
if(bk.results){
var l=0;
for(var j in bk.results){
if(bk.results[j].item_id==localStorage.getItem('this_item_id')){
removeBookmark(bk.results[j]);
l=1;
}
}if(l==0){
addBookmark(myItem.results[i]);
}
}else{
addBookmark(myItem.results[i]);
}
});
};
})(i);
Item.appendChild(bookmark);
//document.getElementById(i).appendChild(btn);
}
});
In what specific div do you want them? So far, in this way the four buttons are inside the myItens div see in the fiddle and in the code below.
var getmyItems = function(data) {
var item = document.getElementById('myItems');
for (var i = 0; i < data.length; i++) {
var result = data[i];
// creation of the buffer outer div
var buffer = document.createElement('div');
buffer.className = 'act-time';
//creation of de activity-body
var activity = document.createElement('div');
activity.className = 'activity-body act-in';
//creation of the first span
var arrow = document.createElement('span');
arrow.className = 'arrow';
//creation of the most inner div
var textDiv = document.createElement('div');
textDiv.className = 'text';
//creation of the content of the most inner div
var attribution = '';
attribution += '<p class="attribution">';
attribution += '' + result.title + '';
attribution += result.description;
attribution += '</p>';
//initialize the text div
textDiv.innerHTML = attribution;
//put the arrow span inside the activity div
activity.appendChild(arrow);
// put the text div inside the activity div
activity.appendChild(textDiv);
//put the activity inside the buffer div
// each time appendChild is applied the element is attach tho the end of the target element
buffer.appendChild(activity);
var div = document.createElement('div');
div.appendChild(buffer);
item.appendChild(div);
var btn = document.createElement('input');
btn.setAttribute('type', 'button');
btn.setAttribute('class', 'btn btn-danger');
btn.value = "Delete";
btn.onclick = (function(i) {
return function() {
var c = confirm('Are you Sure? ');
if (c === true) {
//do something;
};
};
})(i);
// now that all div are created you can choose which div you want to put the button inside.
// in this I chose the buffer.
buffer.appendChild(btn);
var showBtn = document.createElement('input');
showBtn.setAttribute('type', 'button');
showBtn.setAttribute('class', 'btn btn-primary');
showBtn.value = "ShowInDetail";
showBtn.onclick = (function(i) {
return function() {
window.location = 'showInDetail.html';
//do something
};
})(i);
// button is append to the end of the buffer
buffer.appendChild(showBtn);
var extendBtn = document.createElement('input');
extendBtn.setAttribute('class', 'btn btn-warning');
extendBtn.setAttribute('type', 'button');
extendBtn.value = "Extend";
extendBtn.onclick = (function(i) {
return function() {
window.location = 'extendItem.html';
//do something
};
})(i);
// button is append to the end of the buffer
buffer.appendChild(extendBtn);
var bookmark = document.createElement('input');
bookmark.setAttribute('type', 'button');
bookmark.setAttribute('class', 'btn btn-primary');
bookmark.value = 'Bookmark';
bookmark.onclick = (function(i) {
return function() {
var p = { user_id: localStorage.getItem('user_id') };
window.localStorage.setItem('this_item_id', myItem.results[i].item_id);
//do something
};
})(i);
// button is append to the end of the buffer
buffer.appendChild(bookmark);
}
};
var myItem = [{ title: 'person', description: 'familyName' }, { title: 'ohterPerson', description: 'otherFamilyName' }];
getmyItems(myItem);

Display One Div at a Time and Disable Active Div's Button

As you can see, 3 divs are created using JavaScript when their respective buttons are clicked. I pass their values and then use those to create the content. I am not sure if this is the best way... but anyway.
The problem is that the divs keep appending. I only want to show one div at a time, and I also want to disable the active div's button. I've seen that you can use something like document.querySelector('button[onclick]').disabled = true;, but I am unsure of how to make it dynamically work because it would have to be set to false once any of the other buttons are clicked.
Here is my JavaScript that is responsible for creating the content:
function showDiv(name) {
var selectedButton = name.value;
var div = document.createElement('div');
div.id = 'myDiv';
document.body.appendChild(div);
if (selectedButton === 'home') {
div.innerHTML = 'Hi, this is a test for the ' + selectedButton + ' div.';
} else if (selectedButton === 'about') {
div.innerHTML = 'Hi, this is a test for the ' + selectedButton + ' div.';
} else if (selectedButton === 'contact') {
div.innerHTML = 'Hi, this is a test for the ' + selectedButton + ' div.';
}
}
My JSFiddle: http://jsfiddle.net/wwen39o9/
I've updated your fiddle: http://jsfiddle.net/wwen39o9/3/
In short, add one div to the html:
<div id="myDiv"></div>
Give buttons a class navbutton:
Javascript:
function showDiv(me) {
$('.navbutton').prop('disabled', false);
$(me).prop('disabled', true);
$('#myDiv').html('Hi, this is a test for my ' + $(me).val() + ' div.');
}
Pure JS version without jQuery:
function showDiv(me) {
var div = document.getElementById('myDiv');
var buttons = document.getElementsByTagName('button');
for (var i = 0; i < buttons.length; i++) {
if (buttons[i].className == 'navbutton')
buttons[i].disabled = false;
}
me.disabled = true;
div.innerHTML = 'Test for ' + me.value;
}
A couple of ways to set an active button in a group of buttons:
If they are confined to a wrapper:
function setActive(selectedButton){
var parent = selectedButton.parentNode;
var children = parent.getElementsByTagName('button');
var child_ct = children.length - 1;
while (child_ct) {
children[child_ct].disabled = false;
child_ct--;
}
selectedButton.disabled = true;
}
Or by giving all a class like .nav-btn
function setActive(selectedButton) {
var parent = selectedButton.parentNode;
var children = parent.getElementsByClassName('nav-btn');
var child_ct = children.length - 1;
while (child_ct) {
children[child_ct].disabled = false;
child_ct--;
}
selectedButton.disabled = true;
}
A good way to swap out div:
Check if div exists. Replace content if so, create div if not.
function showDiv(content) {
var div = document.getElementById('the-div');
if (div) {
//May be better to remove children, then append content, but...
div.innerHTML = content
} else {
var the_div = document.createElement('div');
the_div.id = 'the-div';
the_div.innerHTML = content;
document.appendChild(the_div);
}
}
So:
function handleClick() {
setActive(this);
if (this.name === 'home') {
showDiv('Information about being home');
}
}
<button onclick="handleClick">
The append method should be call only if we did not found one.
Something like
function showDiv(name) {
var selectedButton = name.value;
var div = document.getElementById('myDiv');
if(!div) {
document.createElement('div');
div.id = 'myDiv';
document.body.appendChild(div);
}
We can check the number of div elements on page
Or why not to do it like following. At the beginning we have an empty div with id="myDiv" and then we are just changing its content with JavaScript. Have a look at JSFiddle example.
HTML
<button value="home" onclick="showDiv(this);">Home</button>
<button value="about" onclick="showDiv(this);">About</button>
<button value="contact" onclick="showDiv(this);">Contact</button>
<!-- create an empty div -->
<div id="myDiv"></div>
JavaScript
function showDiv(name) {
var selectedButton = name.value;
var div = document.getElementById('myDiv');
if (selectedButton === 'home') {
div.innerHTML = 'Hi, this is a test for the ' + selectedButton + ' div.';
} else if (selectedButton === 'about') {
div.innerHTML = 'Hi, this is a test for the ' + selectedButton + ' div.';
} else if (selectedButton === 'contact') {
div.innerHTML = 'Hi, this is a test for the ' + selectedButton + ' div.';
}
}

How can I remove unwanted piece of HTML markup on the page?

I have trouble with this piece of code. When I click it once, all is good and the behavior is as designed , but when I click it more than once, then there is all bunch of HTML that appears in the div (text area). How should I revise my JS to make it not happen?
HTML :
<div id="transcriptText">Lorem ipsum dolor sit amet </div>
<br>
<div id="divideTranscript" class="button"> Transform the Transcript! </div>
JS :
window.onload = function() {
var transcriptText = document.getElementById("transcriptText");
var newTranscript = document.createElement("div");
var divideTranscript = document.getElementById("divideTranscript");
divideTranscript.onclick = EventHandler;
function EventHandler() {
changeText();
}
function changeText() {
var sArr = transcriptText.innerHTML.split(" ");
transcriptText.innerHTML = "";
console.log(sArr);
var count = 0;
for (var i = 0; i < sArr.length; i++) {
var item = sArr[i];
var newSpan = document.createElement("span");
var newText = document.createTextNode(item);
var dotNode = document.createTextNode(" ");
newSpan.id = "word" + i;
var mouseOverFunction = function () {
this.style.backgroundColor = 'yellow';
};
newSpan.onmouseover = mouseOverFunction;
var mouseOutFunction = function () {
this.style.backgroundColor = '';
};
newSpan.onmouseout = mouseOutFunction;
newSpan.appendChild(newText);
newSpan.appendChild(dotNode);
transcriptText.appendChild(newSpan);
count++;
};
}
};
Here is it live http://jsfiddle.net/b94DG/1/
The main problem is that you use the innerHTML property instead of the .textContent property each time.
Here is an improved version of changeText() that doesn't matter how many times you run it:
function changeText() {
var sArr = transcriptText.textContent.split(/\s+/g); // changed
transcriptText.innerHTML = "";
var count = 0;
for (var i = 0; i < sArr.length; i++) {
var item = sArr[i];
if (!item) continue; // changed: don't add spans for empty strings
var newSpan = document.createElement("span");
var newText = document.createTextNode(item);
var dotNode = document.createTextNode(" ");
newSpan.id = "word" + i;
var mouseOverFunction = function () {
this.style.backgroundColor = 'yellow';
};
newSpan.onmouseover = mouseOverFunction;
var mouseOutFunction = function () {
this.style.backgroundColor = '';
};
newSpan.onmouseout = mouseOutFunction;
newSpan.appendChild(newText);
newSpan.appendChild(dotNode);
transcriptText.appendChild(newSpan);
count++;
};
}

Creating dynamic div using javascript

<script>
function selecteditems()
{
var i=1;
var val="";
while(i<=53)
{
if(document.getElementById('timedrpact'+i)!="")
{
val+=document.getElementById('timedrpact'+i).value;
document.getElementById('showselecteditems').innerHTML=val;
}
i++;
}
}
</script>
How to create a new div and add contents to it?In the above case i lost previous content due to innerHTML.I want new div each time for dynamically attach an image and the above variable val to it.
Thanks in advance.
Check this Demo
<div id="output" class="out">
</div>
window.onload=function(){
var output = document.getElementById('output');
var i=1;
var val="";
while(i<=3)
{
if(!document.getElementById('timedrpact'+i))
{
var ele = document.createElement("div");
ele.setAttribute("id","timedrpact"+i);
ele.setAttribute("class","inner");
ele.innerHTML="hi "+i;
output.appendChild(ele);
}
i++;
}
};
Look at document.createElement() and element.appendChild().
var newdiv = document.createElement("div");
newdiv.innerHTML = val;
document.getElementById("showselecteditems").appendChild(newdiv);
Because you will likely encounter this in the near future: You can remove any element with this code:
element.parentNode.removeChild(element);
Using createElement:
function selecteditems() {
var container = document.getElementById('showselecteditems');
for (var i=1;i<=53;i++) {
var fld = document.getElementById('timedrpact'+i);
if (fld) {
var div = document.createElement("div");
div.appendChild(document.createTextNode(fld.value));
container.appendChild(div);
}
}
}
Full version using cloneNode (faster) and eventBubbling
Live Demo
var div = document.createElement("div");
var lnk = document.createElement("a");
var img = document.createElement("img")
img.className="remove";
img.src = "https://uperform.sc.gov/ucontent/e14c3ba6e4e34d5e95953e6d16c30352_en-US/wi/xhtml/static/noteicon_7.png";
lnk.appendChild(img);
div.appendChild(lnk);
function getInputs() {
var container = document.getElementById('showselecteditems');
for (var i=1;i<=5;i++) {
var fld = document.getElementById('timedrpact'+i);
if (fld) {
var newDiv = div.cloneNode(true);
newDiv.getElementsByTagName("a")[0].appendChild(document.createTextNode(fld.value));
container.appendChild(newDiv);
}
}
}
window.onload=function() {
document.getElementById('showselecteditems').onclick = function(e) {
e=e||event;
var target = e.target||e.srcElement;
// target is the element that has been clicked
if (target && target.className=='remove') {
parentDiv = target.parentNode.parentNode;
parentDiv.parentNode.removeChild(parentDiv);
return false; // stop event from bubbling elsewhere
}
}
getInputs();
}
Syntax for dynamic create div:
DivId = document.createElement('div');
DivId.innerHtml ="text"

Categories

Resources