trying to call an array from model.data in catListView.render(), it's showing perfectly but how to make the array item clickable, (i.e cat0 is clicked or cat2 is click).
$(function () {
var model = {
data: ["cat0", "cat1", "cat2", "cat3"],
}
var oct = {
init: function () {
catList.init();
},
getCat: function () {
return model.data;
},
};
var catListView = {
init: function () {
this.$catList = $("#cat-list");
catList.render();
},
render: function () {
var catList = this.$catList.html('');
var cats = oct.getCat();
for (var i = 0; i < cats.length; i++) {
var cat = cats[i];
var li = "<li>" + cat + "</li>";
addEventListener(li, "click", function(){
console.log(this.li.text());
});
catList.append(li);
}
}
};
oct.init();
}());
You should bind an eventListener to the EventTarget using EventTarget.addEventListener() when using pure DOM (see https://developer.mozilla.org/de/docs/Web/API/EventTarget/addEventListener for reference).
So in your code it would be:
var li = document.createElement('li'); // create an element instead if string
li.innerText = cat;
li.addEventListener("click", function(){
console.log(li.innerText);
});
Note that you also need to create a DOM element to bind events to.
The codes you typed cannot run... I try to guess what you want-
$li.bind("click", function() {
console.log("way 2", $(this).index());
});
https://codepen.io/linjiyeah/pen/QvzVQN
Related
I get the message list from the API and create a dynamic array using javascript. I would like a new page with message details to be started when a specific row is pressed.
How do I implement a call to showMessage () on a specific table row?
var list = document.getElementById("listOfMessage");
init();
function init() {
for (var i = 0; i < messageList.length; i++) {
var message = messageList[i];
var li = document.createElement("li");
var a = document.createElement("a");
var text = document.createTextNode("Nadawca: " + message.fullName);
a.appendChild(text);
a.setAttribute('onclick', showMessage(message));
list.appendChild(li);
//list.innerHTML += "<li><a href="showMessage(message)"><h2>Nadawca: " + message.fullName + "
//</h2></a></li>";
}
//list = document.getElementById("listOfTask");
}
function showMessage(message) {
window.sessionStorage.setItem("message", JSON.stringify(message));
window.location.href = 'message.html';
}
In the code above, the showMessage () function is immediately called when the array is initialized. How to make it run only after clicking on a row?
I could add an id attribute to the (a) or (li) element in the init () function, but how to find it later and use it in this code:
var a = document.getElementById('1');
a.addEventListener('click', function() {
window.sessionStorage.setItem("message", JSON.stringify(messageList[0]));
window.location.href = 'message.html';
});
I found a way to solve this problem.
Using this code fragment, we can call a function for a specific element in a dynamically created list.
function init() {
for (var i = 0; i < messageList.length; i++) {
var message = messageList[i];
list.innerHTML += "<li id="+i+"><a onClick="+
"><h2>Nadawca: " + message.fullName + "</h2></a></li>";
}
//$(document).on("click", "ui-content", function(){ alert("hi"); });
$(document).ready(function() {
$(document).on('click', 'ul>li', function() {
var idName = $(this).attr('id');
showMessage(messageList[idName]);
});
});
}
I try to make todo list app with javascript, I have function to create new each item (li elements) like that
todoView: function (todo) {
var controller = todoController.todoList;
console.log('controller', controller);
var item = document.createElement('li');
item.setAttribute('class', 'todoItem');
var inpCheckbox = document.createElement('input');
this.setAttributes(inpCheckbox, { 'type': 'checkbox', 'class' : 'itemList'} );
var lbContent = document.createElement('label');
lbContent.innerHTML = todo.getContent();
var btnRemove = document.createElement('button');
console.log('id', this.id)
this.setAttributes(btnRemove, { 'class': 'remove', 'id' : this.id} );
// btnRemove.setAttribute('id', this.id);
//item append each element
item.appendChild(inpCheckbox);
item.appendChild(lbContent);
item.appendChild(btnRemove);
console.log('item', item);
//ul append each item
document.querySelector('#todoListView').appendChild(item);
},
but in the end file I set the handle event for all li item have class .remove
var deleteItem = document.getElementsByClassName('remove')
for(var i = 0; i < deleteItem.length; i++) {
deleteItem[i].addEventListener("click", function() {
todoController.removeTodo(i);
});
}
But now I have issue that I can't call .remove class, because it just create into todoView function. It to be contain difference block. In jquery I can use delegate to resolve it, but I don't know how to fix it in js pair. Pls help me
Instead of
var deleteItem = document.getElementsByClassName('remove')
for(var i = 0; i < deleteItem.length; i++) {
deleteItem[i].addEventListener("click", function() {
todoController.removeTodo(i);
});
}
you'll want
todoListView.addEventListener('click', function(e) {
if(e.target.classList.contains('remove')){
todoController.removeTodo(e.target);
}
});
However, I think your removeTodo function is flawed
This code displays two cats and the number of times each cat is clicked, how can I increment the .clicks property of each cat from inside the Cat.prototype.clickInc() method?
$(document).ready(function() {
var cats = [];
var Cat = function(id, image_path) {
this.id = id;
this.image_path = image_path;
this.clicks = 0;
};
Cat.prototype.clickInc = function() {
$('#'+this.id).click(function(){
this.clicks++;
return this.clicks;
});
};//use a closure here
var poly = new Cat("poly", "poly.jpg");
var chewie = new Cat("chewie", "chewie.jpg");
cats.push(poly);
cats.push(chewie);
for(i=0; i<cats.length; i++)
{
var catInfo = '<div class="cats"><div id="'+cats[i].id+'"><img src='+cats[i].image_path+'><h3>'+cats[i].id+'</h3></div><div class="clickNos"><span ="label">Number of clicks</span><span class="clicks">'+cats[i].clicks+'</span></div></div>';
$("#container").append(catInfo);
cats[i].clickInc();
}
});
this is not Cat within .click() handler. Also, you cannot return from an event handler. Use .next(".clickNos") with .find(".clicks") to select next .clicks element relative to clicked <img> element; set .html() of matched element to .clicks property of Cat instance.
Cat.prototype.clickInc = function() {
var _cat = this;
$('#' + this.id).click(function() {
_cat.clicks++;
$(this).next(".clickNos").find(".clicks").html(" " +_cat.clicks);
});
};
jsfiddle https://jsfiddle.net/9cykvbyv/1/
I'm creating a tool which generates a bunch of divs based on data I input into an array, however they all have the same class. The idea is that when one link is clicked it shows one of the ".catbox" divs and hides the rest.
All of these divs have the same class so I need to iterate through them, but I'm not quite sure how this is done with jQuery. Currently clicking on the last ".list" class triggers the on click event instead of all of them, and currently it shows all of the divs with the class ".catbox" instead of the corresponding one.
Here is the code:
var HTMLcatName = '<h1>%data%</h1>';
var HTMLcatImage = '<img id="cat" src="%data%">';
var HTMLcatCounter = '<p class="counter">Number of clicks: %data%</p>';
var HTMLcatList = '<p>%data%</p>'
var noCats = 'No cats selected m8';
var getCounterClass = document.getElementsByClassName("counter");
$(document).ready(function() {
cats.display();
$('.catbox').hide();
for (u = 0; u < cats.name.length; u++) {
formattedCatList = HTMLcatList.replace("%data%", cats.name[u]);
var listDiv = document.createElement('div');
listDiv.innerHTML = formattedCatList;
listDiv.className = "list";
$(".list").click(function() {
$(".catbox").toggle("slow");
});
$("body").prepend(listDiv);
}
});
var update = function() {
for (j = 0; j < getCounterClass.length; j++) {
getCounterClass[j].innerHTML = 'Number of clicks: ' + cats.clicks[j];
}
}
var cats = {
"name": ["Monte", "Jib"],
"image": ["images/monte.jpg", "images/jib.jpg"],
"clicks": [0, 0],
display: function () {
for (i = 0; i < cats.image.length; i++) {
formattedCatNames = HTMLcatName.replace("%data%", cats.name[i]);
formattedCatImages = HTMLcatImage.replace("%data%", cats.image[i]);
formattedCatCounter = HTMLcatCounter.replace("%data%", cats.clicks[i]);
var catDiv = document.createElement('div');
catDiv.className = "catbox";
catDiv.innerHTML = formattedCatNames + formattedCatImages + formattedCatCounter;
catDiv.querySelector('img').addEventListener('click', (function(catCountUp) {
return function() {
cats.clicks[catCountUp]++;
update();
};
})(i));
document.body.appendChild(catDiv);
}
},
}
The function I need help with is found within $(document).ready(function() {
Any help would be greatly appreciated.
The following can do it:
$(".list").on("click", function(){
$(this).find(".catbox").toggle("slow");
});
With $('.list') you get a group of elements of class list, so if you use $('.list').click(); you will bind the click event to just one element. You should use:
$(".list").each(function(){
$(this).click(function() {
$(".catbox").toggle("slow");
});
});
I am trying to write jason data into separate divs with class .name and data-key za data attr. I have problem with data and getting the right index for that.
Here is my buggy attempt. Console.log writes all keys, but the last function doesn't give divs the data attr
$.post( "http://0.0.0.0:9292/api/links", function( data ) {
var names = data.map(function (i) {
return i['link'].name
});
var keys = data.map(function (i) {
return i['link']['key']
});
var container = document.querySelector(".link-names");
names.forEach(function(name) {
var div = document.createElement('div');
div.innerHTML = name;
$(div).addClass("name");
container.appendChild(div);
});
$.each((".name"), function(index) {
$(this).data("key", keys[index]);
console.log(keys[index]);
});
please try with this updated code
$.post( "http://0.0.0.0:9292/api/links", function( data ) {
var names = data.map(function (i) {
return i['link'].name
});
var keys = data.map(function (i) {
return i['link']['key']
});
var container = document.querySelector(".link-names");
names.forEach(function(name) {
var div = document.createElement('div');
div.innerHTML = name;
$(div).addClass("name");
container.appendChild(div);
});
$(".name").each(function(index) {
$(this).data("key", keys[index]);
console.log(keys[index]);
});
You missed a $ in ('.names') $.each try this,
$.each($(".name"), function(index) {
// ----^ use $ here
$(this).data("key", keys[index]);
console.log(keys[index]);
});
or simply,
$(".name").each(function(index) {
$(this).data("key", keys[index]);
console.log(keys[index]);
});
You can add key while adding element in container like,
var i=0;
var container = document.querySelector(".link-names");
names.forEach(function(name) {
var div = document.createElement('div');
div.innerHTML = name;
$(div).addClass("name");
$(div).data("key", keys[i]);// set data here
container.appendChild(div);
i++;
});