Binding event before Creating DOM in jQuery - javascript

var thumbDom = '';
for (var i = 0; i < 10; i++) {
thumbDom = thumbDom + '<div id = "div-" ' + i + '>DIV-'+ i +'</div>';
bindEvent(i);
}
$('#parent').append(thumbDom);
function bindEvent(i){
$('#div-' + i).click(function(event) {
alert(i);
});
}
I know the code can't work , beacuse event is bind before dom append.
but is there anyway to bind the click event to many dynamically doms before appending to dom tree?
I don't wnat to use $(document).on('click, ... , I want to bind event to the child node.
Any suggest will be help , thank you~
Fiddle Here

You could try this approach:
define a <div></div>
set its id and innerHtml
bind it with an onclick event (that alerts its id)
append it to the "#parent" item
$(function() {
for (var i = 0; i < 10; i++) {
$("<div></div>")
.attr("id", "div-" + i)
.html("DIV-" + i)
.click(function() {
alert($(this).attr("id"));
})
.appendTo("#parent");
}
});

Related

How to not lose my event listener in Javascript each time I use .insertBefore?

I am attempting to move a div (which contains text and other elements) each time the user clicks the up or down arrow. The goal is to simply allow users to rearrange divs to their liking, based on clicking the appropriate arrows.
The issue I'm running into is -- when I use .insertBefore to rearrange these elements? It only allows me to click the arrow and perform that action once. After that, nothing happens. It appears that I'm losing my event listener each time I do this. Is there a way for me to somehow say: "Keep that old event listener after it gets moved?"
Here is the code:
for (let i = 0; i < NumberOfSavedIdeas; i++) {
document.getElementById('DeleteIdeaButton' + [i]).addEventListener('click', () => {
var DivToDelete = document.getElementById("SavedIdeaDiv" + [i]);
DivToDelete.remove();
let ArrayContentMatch = FullSavedIdeasArray.indexOf(FullSavedIdeasArray[i])
FullSavedIdeasArray.splice(ArrayContentMatch, 1);
chrome.storage.local.set({SavedIdeas: FullSavedIdeasArray});
});
document.getElementById('MoveIdeaUp' + [i]).addEventListener('click', () => {
var DivToMove1 = document.getElementById("SavedIdeaDiv" + [i]);
var ParentDiv1 = document.getElementById("DivTesting");
ParentDiv1.insertBefore(DivToMove1, ParentDiv1.children[i-1]);
});
document.getElementById('MoveIdeaDown' + [i]).addEventListener('click', () => {
alert('move down')
});
}
Thanks!
This is because new element doesn't exist in DOM when all event listeners are set. Add an event listener on document instead of an element.
It should be wrapped like:
for (let i = 0; i < NumberOfSavedIdeas; i++) {
document.body.addEventListener( 'click', function (e) {
if (e.target.id == 'YourId' + [i]) {
yourFunction();
}
} );
}

I have a problem with an id in onClick event JavaScript function

I am trying to make a little idle click game, but have a problem with my startIdle function.
I can't pass the id to which input progressbar that is needed to start counting.
I have one input field and one button foreach id from a obj.
function addRow(id) {
var div = document.createElement('div');
div.className = 'row';
div.innerHTML =
'<div class="w3-blue" name="idle" id="'+id+'" style="height:24px;width:20%"></div>\
<button onclick="startIdle('+id+')">Click me</button>';
document.getElementById('content').appendChild(div);
}
function startIdle(id) {
_counter = 1;
_timer = setInterval(function(){
document.getElementById(id).style.width = (_counter + "%");
_counter++;
if(_counter > 100) clearInterval(_timer);
}, 100);
}
function createIdles(){
for (var key in money) {
// skip loop if the property is from prototype
if (!money.hasOwnProperty(key)) continue;
var obj = money[key].id;
addRow(obj)
}
}
createIdles()
this is the console.log I get:
Uncaught ReferenceError: startIdle is not defined at HTMLButtonElement.onclick
Your problem is that startIdle is defined inside a scope. Move it out of document.ready. Unless you can call the function from console, it isn't available globally.
Alternatively, building on Andy Hoffmans solution, bind onClick programmatically inside scope of document.ready, e.g.
document.querySelectorAll('button[data-id]')
.forEach(elm => elm.addEventListener('click',
() => startIdle(elm.dataset.id)))
You can probably improve that a bit using jquery.
I removed the onclick attribute and perform binding separately. The binding and element lookup are done inside of a setTimeout to ensure the elements are present in the DOM when that code runs.
// Note: I'm using a data-id attribute on the <button> so as to not
// duplicate the id on the <div class="w-3">
function addRow(id) {
var div = document.createElement('div');
div.className = 'row';
div.innerHTML =
'<div class="w3-blue" name="idle" id="' + id + '" style="height:24px;width:20%"></div>\
<button data-id="' + id + '">Click me</button>';
document.getElementById('content').appendChild(div);
}
function startIdle() {
// Remember the data-id attribute from above?
alert('clicked ' + this.getAttribute('data-id'));
}
for (var i = 0; i < 5; i++) {
addRow(i);
}
// Bind click events in separate event loop to ensure elements are present in DOM
setTimeout(function() {
var els = document.querySelectorAll("button[data-id]");
els.forEach(function(el) {
el.addEventListener("click", startIdle);
})
});
<div id="content"></div>
http://jsfiddle.net/4mr02ktu/2/

jQuery Append with event bind

I am trying to append a number of Div's to a div with an id "list", and each div has an event so i make an array for each div to be appended.
here is my code.
var count = Object.keys(data.results).length;
var el = [];
for(var i=1; i<=count; i++){
el[i] = $('<div id="'+i+'">data.results[i].name</div>');
$("#list").append(el[i]);
el[i].click(function(){
alert(data.results[i].name);
$('#searchbox').modal('toggle');
});
}
the data in div's was successfully appended. but as a try to alert the data in the event i bind to each div, it doesn't alert the data in the div.
what I am trying to do is append names with a div within the div with id "list" and if i click on a name, it should alert the name itself.
You can simplify the logic here by using a delegated event handler on all the appended div elements, then using the text() method to retrieve the required value. Try this:
var data = {
results: {
foo: { name: 'foo_name' },
bar: { name: 'bar_name' }
}
}
var $list = $("#list").on('click', 'div', function() {
console.log($(this).text());
//$('#searchbox').modal('toggle');
});
Object.keys(data.results).forEach(function(key, i) {
$list.append('<div id="' + i + '">' + data.results[key].name + '</div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="list"></div>
The problem is that by the time an element is clicked i is already set to the maximum value i = count. To fix that you'll have to create a closure. Try this:
var count = Object.keys(data.results).length;
var el = [];
function closure(index){
el[index].click(function(){
alert(data.results[index].name);
$('#searchbox').modal('toggle');
});
}
for(var i=1; i<=count; i++){
el[i] = $('<div id="'+i+'">data.results[i].name</div>');
$("#list").append(el[i]);
closure(i);
}

Click event on every item on populated list with jQuery

Here is how I populate my list:
function bingNetworksList(myList) {
var list = '';
for (i = 0; i < myList.length; i++) {
list += '<li>' + myList[i] + '</li>';
}
$('#myList').empty();
$('#myList').append(list);
}
Here is my html file:
<ul id="myList"></ul>
I want to add a click event for every item of list (without having separate ids):
$(function() {
$('#myList').click(function() {
var listItem = this.find('a').text();
console.log(listItem); // never logged
});
});
However, when I click at a list item, click event doesn't fire.
What am I doing wrong?
I can only assume there's a js error in your console.
I've created a working sample for you. We can use event delegation and then retrieve the DOM node that was clicked. You need to ensure you call the bingNetworksList [assume typo in here and meant binD ;)] function when the DOM ready event has fired.
function bingNetworksList(myList) {
var list = '';
for (i = 0; i < myList.length; i++) {
list += '<li>' + myList[i] + '</li>';
}
$('#myList').empty();
$('#myList').append(list);
}
$(function() {
var list = ["foo", "bar"]
bingNetworksList(list);
$('#myList').click(function(evt) {
var listItem = $(evt.target).text();
console.log(listItem); // never logged
});
});
You need to wrap this inside $ as like this:
$(function() {
$('#myList').click(function() {
var listItem = $(this).find('a').text();
console.log(listItem); // will always be logged
});
});

Pressing a button in the list of JQM

I have a list of JQM, and a button for each instance on a list.
When click on the button I call to function ...
function xxx()
{
alert ('click on me!! :]');
}
Clicking on the button Not triggering the function, why?
Look at the following jsFiddle: http://jsfiddle.net/Hodaya/nR369/3/
To bind the xxx function to the click event of the newLI DOM element you should either use the newLI.onclick=xxx; or better yet use jQuery to do the binding with $(newLI).click(xxx);
Finally the problem is resolved:
Pressing the button did not work because:
to each button on the list was the same id ,In the moment I added a unique name for each of the buttons, it worked.
Here the code:
for (var i = 0; i < Local.length; i++) {
newLI.innerHTML = '<a href="to.html" data-transition="slide" dir="rtl" onclick="YYY();" >' +
'<p>...'</p>' +
'<a id="btnClearOneBookmark' + i + '" data-role="button" data-icon="delete" data-theme="b"></a>' +
' </a>';
$("#btnClearOneBookmark" + i).click(function () { xxx(); });
}
Try this:
$("#mybutton").on('click',function() {
var ul = document.getElementById("bookMarkMenu");
for (var i = 0; i < 5; i++) {
var newLI = document.createElement("LI");
console.log(i)
newLI.innerHTML = '<p>...</p>' +'<a id="btnClearOneBookmark" data-theme="b" data-role = "button"></a>';
newLI.setAttribute('data-theme', 'c');
newLI.setAttribute('onclick', 'DisplayBookMark()');
ul.appendChild(newLI);
$('ul').listview('refresh');
}
});
$("#btnClearOneBookmark").live('click',function() {
alert("click on me!! :]");
});

Categories

Resources