I'm currently having trouble understanding what's going on with this code
$("#table").on("click", ".plusRow", function(event){
var name = this.getAttribute("table-data");
tableData.addData(name, 0, 1);
displayTable();
});
I understand that the first part should go something along the lines of
document.getElementById("table").addEventListener("click", function(event)
but im having trouble understanding where the ".plusRow" class should go, is it added onto the eventlistener? or how would this code be better translated back to regular Javascript.
This code snippets binds a listener on a single element (the table) and delegates it to its children which means that it will only run the event handler when it bubbles up to one or multiple elements that match the predicate (having a "plusRow" class).
With event delegation you could do:
let table = document.getElementById('table');
table.addEventListener('click', event => {
const elem = event.target;
if (elem.classList.contains('plusRow')) {
const name = elem.getAttribute("table-data");
tableData.addData(name, 0, 1);
displayTable();
}
});
Here we have to keep in mind that this code will always run when a child of the table is clicked but will only update the table when the target matches the predicate.
Without using event delegation you could do the following which will have similar results but behaves quite differently:
let tableElem = document.getElementById('table');
// To keep this simple we assume there is only one button
let button = tableElem.getElementsByClassName('plusRow')[0];
button.addEventListener('click', event => {
const name = event.currentTarget.getAttribute("table-data");
tableData.addData(name, 0, 1);
displayTable();
})
This version will only ever run when the first child of the table with a class of "plusRow" is clicked. Please note that this is just an example because if there is no element with such class an exception will be raised when we try to bind the event listener.
So I've come up with a dummy possible solution example using querySelector and querySelectorAll. Let me know if anyone sees an issue with the suggested solution.
function delegate(parentSelector, eventType, childSelector, callback) {
//lookup the parent element
var parent = document.querySelector(parentSelector);
//put the event listener for the event on the parent
parent.addEventListener(eventType, function(event) {
//get the element that caused the event
var element = event.target;
//find all the children in the parent that match the child selector,
//at this point in time
var children = parent.querySelectorAll(childSelector);
//if the element matches a child of the parent that matched the
//childSelector, we want to do our callback
for (var i = 0; i < children.length; i++) {
if (children[i] === element) {
callback();
break;
}
}
});
}
delegate('#table', 'click', '.addRow', function() {
document.querySelector('#table').innerHTML += `
<tr>
<td>Something</td>
<td><button class="addRow">Add Row</button></td>
</tr>
`;
});
<table id="table">
<tr>
<td>Something</td>
<td><button class="addRow">Add Row</button></td>
</tr>
</table>
Related
I am quite new to manipulating elements in the DOM in JS so I am creating a simple to do list to get more comfortable and where I can add items using the input and remove items by clicking on the list item.
ALthough this may not be best practice and limitting I am just wanting to use create and remove elements rather than using objects or classes until I get more familar, also using plain/vanilla js so please keep this in mind when answering.
I am trying to add a click event which removes the <li> when the <li> is clicked.
My logic is...
When the page is loaded I can't just run a for loop over all of the <li>s and add event handlers as all of the <li>'s do not exist yet.
So my attempted solution is when the addTaskButton event is triggered, we get all of the <li> that are on the page at the time of the event, we loop through all of them and add an eventlistener to <li>'s that are waiting to be removed when clicked.
This doesn't seem to work and may be overly complicated.
Can someone please explan to me very simply like I'm 5 why this doesn't work or what a better way to do this would be?
Thank you in advance
HTML
<ul id="taskList">
<li>example</li>
</ul>
<input type="text" id="addTaskInput">
<button id="addTaskButton">Add Task</button>
JavaScript
const taskList = document.querySelector("#taskList");
const addTaskInput = document.querySelector("#addTaskInput");
const addTaskButton = document.querySelector("#addTaskButton");
let taskItem = document.querySelectorAll("li");
addTaskButton.addEventListener("click", () => {
let taskItem = document.createElement("li");
taskItem.textContent = addTaskInput.value;
for (let i = 0; i < taskItem.length; i++) {
taskItem[i].addEventListener("click", () => {
let taskItem = document.querySelectorAll("li");
taskList.removeChild(taskItem[i]);
});
}
taskList.appendChild(taskItem);
addTaskInput.value = " ";
});
Here is code i created for your requirement, this implement jQuery $(document).on mechanism in vanilla javascript, now where ever you create an li inside the document, on clicking that li it will be removed.
Explaination
What it does is on clicking the document it checks on which element is clicked (e.target is the clicked element, e is is the click event on document), then checks if the clicked item is an li tag (e.target.tagName will tell us the tag name if the item clicked), so if it is an li just remove it;
const taskList = document.querySelector("#taskList");
const addTaskInput = document.querySelector("#addTaskInput");
const addTaskButton = document.querySelector("#addTaskButton");
addTaskButton.addEventListener("click", () => {
let taskItem = document.createElement("li");
taskItem.textContent = addTaskInput.value;
taskList.appendChild(taskItem);
addTaskInput.value = " ";
});
document.onclick = function(e)
{
if(e.target.tagName == 'LI'){
e.target.remove();
}
}
<ul id="taskList">
<li>example</li>
</ul>
<input type="text" id="addTaskInput">
<button id="addTaskButton">Add Task</button>
Update your for loop like so:
for (let i = 0; i < taskItems.length; i++) {
taskItems[i].addEventListener("click", () =>
taskList.removeChild(taskItems[i]);
});
}
Also your initial taskItem variable should be taskItems and is reflected in the for loop above.
taskList.addEventListener("click", (event) => {
event.target.remove();
});
When the specified event occurs the event object is returned.
The event object has several properties, one of them being target which is the element which is the element which the event occured on. event.target is returned to us and we are applying the remove() method to event.target
because of event "bubbling" or "Event Propagation", we can attach the event handler to an ancestor. It's best to attach the event listener to the closest ancestor element that is always going to be in the DOM (won't be removed).
When an event is triggered-in this case the "click" event. All decending elements will be removed - which in our case as there are only <li>'s this would be fine. But we should be more specific as in a different case we could be attaching this event handler to a div which has several different elements.
To do this we add an if condition to check that the tagName is an <li>
if (event.target.tagName == "LI")
note that the element must be calpitalised
Solution is as follows
taskList.addEventListener("click", (event) => {
if(event.target.tagName == "LI"){
event.target.remove();
}});
Further reading:
Event object and its properties:
https://developer.mozilla.org/en-US/docs/Web/API/Event
Event Bubbling:
https://developer.mozilla.org/en-US/docs/Web/API/Event/bubbles
tagName:
https://developer.mozilla.org/en-US/docs/Web/API/Element/tagName
I am using some code based on the following JSFiddle. The intention is to show more information when the user clicks the "Show Extra" link.
The problem that I'm having is that when the link is clicked on all but the bottom row of the table the hidden element is shown briefly and then closes.
I am populating my table using template strings in javascript. Here is the code that I use to add rows to the table:
this.addRecordToTable = function(bet, index, id){
console.log(index);
console.log($.data(bet));
var butId = id.toString();
if (bet.bookies == null){
bet.bookies = "";
}
if (bet.bet == null){
bet.bet = "";
}
var newRow = `
<tr>
<td>${bet.date}</td>
<td>${bet.bookies}</td>
<td>${bet.profit}</td>
<td><button id=${butId}>Delete</button></td>
<td>Show Extra</td>
</tr>
<tr>
<td colspan=\"5\">
<div id=\"extra_${index}\" style=\"display: none;\">
<br>hidden row
<br>hidden row
<br>hidden row
</div>
</td>
</tr>
`
console.log(newRow);
console.log("#"+butId);
$(newRow).appendTo($("#betTable"));
$("#"+butId).click(
function()
{
if (window.confirm("Are you sure you want to delete this record?"))
{
var rec = new Records();
rec.removeRecordAt(index);
$("#betTable tbody").remove();
var c = new Controller();
c.init();
}
});
$("a[id^=show_]").click(function(event) {
$("#extra_" + $(this).attr('id').substr(5)).slideToggle("slow");
event.preventDefault();
});
}
EDIT:
I had to change $("a[id^=show_]").click to $("a[id=show_"+index).click..., as the event handler was being added to each element every time I added a new element. Thanks to #freedomn-m.
This code:
$("a[id^=show_]")
adds a new event handler to every existing link as well as the new one as it's not ID/context specific so all the show a's match the selector.
You need to add the context (newRow) or use the existing variable(s) as part of the loop that are already defined, eg:
$("a[id^=show_]", newRow)
$("a#show_" + index)
(or any other variation that works).
An alternative would be to use even delegation for the dynamically added elements, eg:
$(document).on("click", "a[id^=show_]", function...
in which case you'd only need to define/call the event once and it would be fired for new elements (ie put that outside the new row loop).
Example: A table with 1 row and 1 cell. Javascript gives this one cell and event handler which will append new rows.
<table border=1>
<tbody id="target">
<tr>
<td class="hi" >I append</td>
</tr>
</tbody>
</table>
var els = document.getElementsByClassName("hi");
for(i=0;i<els.length;i++){
els[i].onclick = function(){callMe(this)};
}
function callMe(t){
var el = document.getElementById("target");
el.innerHTML += '<tr><td class="hi" >appended...</td></tr>';
}
The callMe function gets called once, a new row is appended, the old row stays the same(I suppose).
The second time the first cell is clicked the function does not get called. Why?
What happened there?
What am I missing?
http://jsfiddle.net/2U3m3/1/
I am not using any libraries, just plain JavaScript. I want the first cell to be clickable always. It is meant to add rows forever not just one.
The second time the first cell is clicked the function does not get called. Why?
Because overwriting the innerHTML of an element re-recreates all child elements, no matter if you just “append” to the innerHTML using +=.
And that the table cell has gotten replaced by a new one means that the event handler bound to the old table cell is also gone.
The callMe function gets called once, a new row is appended, the old row stays the same(I suppose).
You “suppose” wrong here.
You need to use DOM methods for row/cell insertions if you plan to keep original event:
function callMe(t){
var el = document.getElementById("target");
var row = el.insertRow(el.rows.length);
var cell = row.insertCell(0)
cell.innerHTML = "Hi"
}
Demo: http://jsfiddle.net/ygalanter/2U3m3/2/
You can delegate the event to the class name directly. So any element with that class will have the click event including newly created ones. Adapted from the answer here.
if (document.body.addEventListener) {
document.body.addEventListener('click',clickHandler,false);
} else {
document.body.attachEvent('onclick',clickHandler); //for IE
}
function clickHandler(e)
{
e = e || window.event;
var target = e.target || e.srcElement;
if (target.className.match(/hi/)) //or whatever classname you want
{
callMe(target);
}
}
So I have EDIT and REMOVE buttons that are dynamically added for each data node (a "poll") in a Firebase database. I have a function which assigns onclick listeners to these with jQuery, but oddly, the event only fires when there just happens to be a single node, and hence a single pair of EDIT/REMOVE buttons. When there are multiple nodes and multiple pairs of buttons, none will fire. Here's the javascript where the events are added to the buttons...
function displayCurrentPollsForEditing(pollsRef)
{
var tbl = createTable();
var th = ('<th>Polls</th>');
$(th).attr('colspan', '3');
$(th).appendTo($(tbl).children('thead'));
pollsRef.once('value', function(pollsSnapshot) {
pollsSnapshot.forEach(function(pollsChild) {
var type = pollsChild.name();
// If this is true if means we have a poll node
if ($.trim(type) !== "NumPolls")
{
// Create variables
var pollRef = pollsRef.child(type);
var pollName = pollsChild.val().Name;
var btnEditPoll = $('<button>EDIT</button>');
var btnRemovePoll = $('<button>REMOVE</button>');
var tr = $('<tr></tr>');
var voterColumn = $('<td></td>');
var editColumn = $('<td></td>');
var rmvColumn = $('<td></td>');
// Append text and set attributes and listeners
$(voterColumn).text(pollName);
$(voterColumn).attr('width', '300px');
$(btnEditPoll).attr({
'class': 'formee-table-button',
'font-size': '1.0em'
});
$(btnRemovePoll).attr({
'class': 'formee-table-remove-button',
'font-size': '1.0em'
});
$(btnEditPoll).appendTo($(editColumn));
$(btnRemovePoll).appendTo($(rmvColumn));
// Append to row and row to table body
$(tr).append(voterColumn).append(editColumn).append(rmvColumn);
$(tr).appendTo($(tbl).children('tbody'));
// Append table to div to be displayed
$('div#divEditPoll fieldset#selectPoll div#appendPolls').empty();
$(tbl).appendTo('div#divEditPoll fieldset#selectPoll div#appendPolls');
$(btnEditPoll).click(function() {
displayPollEditOptions(pollRef);
return false;
});
$(btnRemovePoll).click(function() {
deletePoll($(this), pollsRef);
return false;
});
}
});
});
}
The markup would be something like the following...
<div id="divEditPoll">
<form class="formee" action="">
<fieldset id="selectPoll">
<legend>SELECT A POLL</legend>
<div class="formee-msg-success">
</div>
<div class="grid-12-12" id="appendPolls">
</div>
</fieldset>
</div>
EDIT - So I've switched some lines around and now I don't set the click() events until the buttons are appended to the document, so the button elements are definitely in the DOM when the click events are attached. So could this issue result from not setting id's for these buttons? That seems strange to me, since I'm using variable references rather than ids to attach the events.
There are two things I would check for.
First, make sure you don't have two elements with the same id. If you do, jquery may only bind to the first, or not bind at all.
Second, make sure the element is added to the dom before jquery attempts to bind the click event. If the code is running asynchronously, which can easily happen if you're using ajax, then you may be trying to bind the event before creating the element. Jquery would fail to find the element then give up silently.
you should use .on() for dynamically added button
I'm trying to add rows to a table in HTML using JavaScript that are clickable.
Here is my codes:
HTML:
<table border="1" id="example" style="cursor: pointer;">
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
</tr>
</table>
JavaScript:
//clicked function
$('#example').find('tr').click( function(){
alert('You clicked row '+ ($(this).index()) );
});
//add new row
var x=document.getElementById('example');
var new_row = x.rows[0].cloneNode(true);
new_row.cells[0].innerHTML = "hello";
x.appendChild( new_row );
The problem is that the newly added rows are clickable but won't go through the clicked function to get the alert.
Anyone know why?
The problem is that the newly added rows are clickable but won't go
through the clicked function to get the alert.
Anyone know why?
When you are executing the initial binding of the click event to your tr elements the event is only bound to the tr elements which exist at that time in the DOM.
That is how event binding works by default. You can only bind what is currently in the DOM.
However, using jQuery 1.7+'s on() or jQuery 1.6-'s delegate() methods you can bind event with delegation.
This allows you to bind the event to the closest static parent element of the element you actual want to delegate the event to.
I'm assuming the table itself is the closest static parent element, meaning it always exists and all you add dynamically is the tr elements.
Using on() when using jQuery 1.7+ would look similar to this:
$('#example').on('click', 'tr', function(){
alert('You clicked row '+ ($(this).index()) );
});
Using delegate() when using jQuery 1.6- would look similar to this:
$('#example').delegate('tr', 'click' , function(){
alert('You clicked row '+ ($(this).index()) );
});
What this will do is bind the event to the element with id of example but delegate the click to any tr clicked within that element. As the event is delegated each time, any newly added tr elements within #example will also be included.
Try this:
Following code will take care of dynamically added rows.
//clicked function
$('#example').on('click', 'tr', function(){
alert('You clicked row '+ ($(this).index()) );
});
You are binding your click event on document.ready. New elements added after wards wil not share this binding.
Yu can acheive what you are after by using .on()
$("body").on("click", "#example tr", function(event){
alert('You clicked row '+ ($(this).index()) );
});
DEMO
is this what you are trying to achieve?
<table border="1" id="example" style="cursor: pointer;">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
</tr>
</thead>
<tbody id="addHere"></tbody>
</table>
var addHere = document.getElementById("addHere");
var newTr;
var newTd;
function clicked(evt) {
alert("clicked tr: " + evt.target.parentNode.id);
}
for (var i = 1; i < 11; i += 1) {
newTr = document.createElement("tr");
newTr.id = "row" + i;
newTr.addEventListener("click", clicked, false);
for (j = 1; j < 5; j += 1) {
newTd = document.createElement("td");
newTd.textContent = j;
newTr.appendChild(newTd);
}
addHere.appendChild(newTr);
}
on jsfiddle
In your code it seems that you are looking for rows and then bind an event to any that you find.
You then proceed to add rows using Node.cloneNode
Cloning a node copies all of its attributes and their values,
including intrinsic (in–line) listeners. It does not copy event
listeners added using addEventListener() or those assigned to element
properties (e.g. node.onclick = fn).
so there are no event handlers bound to any of these newly added elements.
Another way to deal with this would be to use jquery delegate event handler method (on)
When a selector is provided, the event handler is referred to as
delegated. The handler is not called when the event occurs directly on
the bound element, but only for descendants (inner elements) that
match the selector. jQuery bubbles the event from the event target up
to the element where the handler is attached (i.e., innermost to
outermost element) and runs the handler for any elements along that
path matching the selector.
and do the following.
var addHere = document.getElementById("addHere");
var newTr;
var newTd;
function clicked(evt) {
alert("clicked tr: " + evt.target.parentNode.id);
}
$(document).on("click", "#addHere tr", clicked);
for (var i = 1; i < 11; i += 1) {
newTr = document.createElement("tr");
newTr.id = "row" + i;
for (j = 1; j < 5; j += 1) {
newTd = document.createElement("td");
newTd.textContent = j;
newTr.appendChild(newTd);
}
addHere.appendChild(newTr);
}
on jsfiddle