Attaching Click Event to DIV Using jQuery Library - javascript

I am aware I can use the click function to attach an event to the DIV element but for some reason it is not working for me. Here is how I am creating the DIV element.
function createColorSwatchDiv(color) {
var colorSwatchDiv = $("<div>");
var image = $("<img>");
image.attr("src",color.imageURL);
var label = $("<label>");
label.text(color.title);
colorSwatchDiv.append(image);
return colorSwatchDiv;
}
Then I try to attach the click event like the following:
// run a loop and build the grid layout
for(index = 0; index < colors.length; index++) {
var colorSwatchDiv = createColorSwatchDiv(colors[index]);
// attach the event
colorSwatchDiv.click(function(){
alert('hello world');
});
colorsSection.append(colorSwatchDiv);
}
// add to the dom
$("#color .imageChartOption").after(colorsSection);
But it does not work and no click event is been attached.

following is the code
var $newdiv1 = $("<div id='object1' onClick=Test()>Hello</div>");
$("body").append($newdiv1);
function Test()
{
alert("Clicked");
}
OR
$newdiv1.on('click',function(){alert("hello");});

since you have created the div in a jQuery wrapper you don't need to wrap it again here $(colorSwatchDiv).click(.... Also, are you sure that the colorSwatchDiv variable is referencing the dom element and not the in memory element? Can you apply a class or anything to the elm in the dom?

Related

Removing an element from a node without removing the associated event?

I have been working on an html/css/javascript 'etch-a-sketch' style project.
In a nutshell I have a grid of div elements with a mouseenter event:
const fillInGrid = document.querySelectorAll(".gridSquares");
fillInGrid.forEach((div) => {
div.addEventListener('mouseenter', (e) => {
div.style.backgroundColor = 'black';
});
});
In the project I have a reset button that removes the child elements from the grid and replaces them with new divs, two prompts where a number of rows and columns specified by the user which then generates a new grid:
const resetButton = document.querySelector("#reset");
resetButton.addEventListener('click', (e) => {
const resetEvent = document.getElementById('container');
while (resetEvent.lastElementChild) {
resetEvent.removeChild(resetEvent.lastElementChild);
};
newGrid();
}
);
However, after clicking reset and choosing dimensions for a new grid, the grid is generated but the grid loses responsiveness to the mouseenter event because I'm assuming the event is being removed along with the divs, is there a way to re-add the event or a method alternative that can remove the divs without the associated event?
A link to a codepen demonstrating the issue: https://codepen.io/MaBuCode/pen/eYpjwOV
Instead of adding multiple event listeners on the child elements, you can add a single event listener at the containing element. This way, your code will become more performant and you will also get to catch any event that gets triggered on the dynamically (newly created) elements.
You will need to replace the mouseenter event with the mouseover event, that supports bubbling.
Here's the code to add and replace the mouseenter event:
// // One event listener to rule them all:
document.getElementById("container").addEventListener('mouseover', (e)=>{
if ( e.target.classList.contains('gridSquares')){
e.target.style.backgroundColor = 'black';
}
});
You can now get rid of the individual div event listener:
fillInGrid.forEach((div) => {
div.addEventListener('mouseenter', (e) => {
div.style.backgroundColor = 'black';
});
});
Codepen Demo
Tip: I have also refactored the ’gridCreator' function to reduce the number of appendChild operations, and instead replaced it with a simple string concatenation to make the code more performant:
function gridCreator(gridSize) {
let content = "";
for (let i = 0; i < gridSize; i++) {
content += "<div class='gridSquares'></div>";
}
document.getElementById("container").innerHTML = content;
}
By using the approach above, you can also omit the code that removes the .container child elements in the resetButton code.

Issue with addEventListener & target clic in my website

I'm playing around with HTML, CSS & JavaScript but I'm not very good. I'm trying the following:
<script type="text/javascript">
var tab = document.getElementsByClassName("MYCLASS");
for(var i = 0, j=tab.length; i<j; i++){
tab[i].addEventListener('click', afficher,false);
}
function afficher(){
alert(this.class);
}
</script>
Attaching the click listener on all my .MYCLASS divs is working. However, on Google Chrome in the alert window it throws me undefined instead of .MYCLASS.
So I tried this code as alternative:
function afficher(e){
var target = e.target || e.srcElement;
var $target = $(e.currentTarget);
alert(target.class);
}
But the result is exactly the same. Any help is appreciated, thank you!
This is because there's no property defined for a html DOM object named class.
If you want to get the class value, you should use this.className.
So your function should look like this:
function afficher(){
alert(this.className);
}
You can just use a simple 'for in' loop, but you need to be sure that you are appending events to only DOM elements. The HTML list that is returned by getElementsByClassName() isn't only returning DOM elements.
var tab = document.getElementsByClassName("MYCLASS");
for(var i in tab){
// you need this check to filter anything that isn't a DOM element
if(typeof tab[i] ==="object"){
tab[i].addEventListener('click', afficher,false);
}
}
function afficher(){
alert(this.className);
}

DOM: Delete newly created 'article' element with newly created delete button within onclick event?

I have one section element that contains one article element. Also, I have one input button with 'onclick' event. Whenever this event fired, a new article element appended to the section element with unique id.
The newArticle element contains a label, text box and a delete button. All these three elements get created within the on-click event.
document.getElementById("addRow").onclick = function () {
var newCustomerlbl = document.createElement("label");
newCustomerlbl.innerHTML = "Cutomer Name: ";
var newCustomertxt = document.createElement("input");
newCustomertxt.setAttribute("type", "text");
var delBtn = document.createElement("input");
delBtn.setAttribute("type", "button");
delBtn.setAttribute("value", "Delete");
delBtn.setAttribute("id", "btnDelete");
var newArticle = document.createElement("article");
newArticle.appendChild(newCustomerlbl);
newArticle.appendChild(newCustomertxt);
newArticle.appendChild(delBtn);
var customerSection = document.getElementById("customerRecords");
var customerArticles = customerSection.getElementsByTagName("article");
for (var i = 0; i < customerArticles.length; i++) {
var lastDigit = i + 1;
var newArticleValue = "article" + lastDigit;
newArticle.setAttribute("id", newArticleValue);
}
customerSection.appendChild(newArticle);
}
Now what I want is whenever user click upon the newly created appended delete button, only that particular article get deleted without effecting the rest of articles.
Here is the my jsFiddle code.
If you don't want to use jQuery you can add event listeners to your buttons:
delBtn.addEventListener('click', function () {
this.parentElement.remove();
}, false);
https://jsfiddle.net/3nq1v5e1/
You need to bind an event listener on the newly created delete button. Your example code about using $(this) suggest that you are using JQuery, but then again in the rest of the code you are not using any JQuery?
If you are using JQuery, things get real simple, just add something like
$(document).on('click','.btnDelete', function(){
$(this).closest('article').remove();
});
(and remember to give the deletebutton a CLASS rather than ID, as there will be multiple delete buttons).
If you are NOT using JQuery, you need to add the event listener EVERY TIME a new delete button is created
newArticle.appendChild(delBtn);
delBtn.onclick = function(.....
etc.

Attaching eventListener to dynamic elements in Javascript

I'm making a todo list and I have li and button tags added dynamically when adding a new list item. The button is an x which is supposed to remove the list item. I have tried several things but can't figure out how to make an eventListener for each individual x button and remove the corresponding list item when it is clicked.
The renderTodos function is where all of the dynamically added content is created. I have a data-index set to each button in which I was trying to use to access each button to attach an eventListener on each dynamic button, but I wasn't sure how to implement that. From what I have read there should be a way to do this using the currentTarget or target of the event but I don't understand how that works.
var input = document.querySelector('input[name=todoItem]'),
btnAdd = document.querySelector('button[name=add]'),
btnClear = document.querySelector('button[name=clear]'),
list = document.querySelector('.todo'),
storeList = [];
function renderTodos(){
var el = document.createElement('li'),
x = document.createElement('button');
listLength = storeList.length;
//Set text for remove button
x.innerHTML = 'x';
for(var i = 0; i < listLength; i++){
el.innerHTML = storeList[i];
list.appendChild(el);
x.setAttribute('data-index', i);
el.appendChild(x);
}
// check for correct data-index property on x button
}
function addTodos(){
storeList.push(input.value);
// Check that input is getting pushed to list array
console.log(storeList);
renderTodos();
}
function clearList(){
// make list empty
list.innerHTML = '';
storeList.splice(0, storeList.length);
//render empty list
renderTodos();
//Check that list array is empty
console.log(storeList);
}
btnAdd.addEventListener('click', addTodos);
btnClear.addEventListener('click', clearList);
Everything else on the list works so far I just can't figure out how to implement this eventListener.
One simple example can be
//a click hadler is added to #mylist which is already present in the dom
document.querySelector('#mylist').addEventListener('click', function(e) {
//assuming that the the `x` is in a span and it is the only span in the `li` we check for that, we can improve this check more to make sure we have actually clicked on the delete button
if (e.target.tagName == 'SPAN') {
//if so then since we know the structure we can delete the parent node of the target which is the span element
e.target.parentNode.parentNode.removeChild(e.target.parentNode);
}
}, false);
//kindly forgive the use of jQuery here
for (var i = 0; i < 10; i++) {
$('<li />', {
text: i
}).append('<span class="x">X</span>').appendTo('#mylist');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="mylist"></ul>
This is a very basic implementation of event delegation, where the actual event is bound to an ancestor element but then we use the actual event target to determine whether to act on it. We can improve the if condition to test for an class for any other attribute!!!
You can add a listener to each button using something like:
x.innerHTML = '';
x.onclick = function(){
var node = this.parentNode;
node.parentNode.removeChild(node);
};
Or you can keep the renderTodos code as it is and delegate the remove to the parent UL:
// Add the listener
list.addEventListener('click', removeItem);
// The listener function
function removeItem(event) {
var node = event.target;
// Check that the click came from an X button
// better to check against a class name though
if (node.tagName &&
node.tagName.toLowerCase() == 'button' &&
node.innerHTML == 'x') {
node = node.parentNode;
node.parentNode.removeChild(node);
}
}
basically what you want to do is add an event on the parent container and wait for the event to bubble up and identify if the event originating is from your x mark and if it is then trigger the callback function.. This is the concept I think most of the libraries use..
Or use a library like jQuery, why solve a problem that has already been solved by others.

On events in loop in dynamic elements

I need to set events to elements makes "on the fly", like var X = $('HTML CODE HERE'), but when I set the events to the last element, all other elements get this last event.
Example here: http://jsfiddle.net/QmxX4/6/
$(document).ready(function() {
var ulItem = $('.lst');
for (var x=0; x<5; x++) {
var newItemElement = $('<li style="border:solid 1px blue;width:200px;height:40px;"></li>');
ulItem.append(newItemElement);
var generator = Math.random();
newItemElement.on('click', function() {
console.log(generator);
});
}
});
All elements are diferents, and I attach the event in the element directly, im try to append before and after add event to element, but not work, all element get the last event.
If you make click in the <li></li> get code generated in the last event, but "in theory" all elements have diferent events attached..
But if I make other loop appending elements after append al items to <ul></ul>, like this:
$.each($(ulItem).children('li'), function(i, item) {
console.log($(this));
var generator = Math.random();
$(this).on('click', function() {
console.log(generator);
});
});
Works... what is the problem?
In your first loop, the generator variable belongs to the ready callback function, and the inner log functions all share it.
In your second loop, the generator variable belongs to the each callback function which is called once for each item and therefore the log functions all see a different variable.

Categories

Resources