Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding click event listener to elements with the same class

Tags:

javascript

I have a list view for delete id. I'd like to add a listener to all elements with a particular class and do a confirm alert.

My problem is that this seems to only add the listener to the first element with the class it finds. I tried to use querySelectorAll but it didn't work.

var deleteLink = document.querySelector('.delete');

deleteLink.addEventListener('click', function(event) {
    event.preventDefault();

    var choice = confirm("sure u want to delete?");
    if (choice) {
        return true;
    }
});

List:

<?php 
    while($obj=$result->fetch_object())
    {
        echo '<li><a class="delete" href="removeTruck.php?tid='.$obj->id.'">'.$obj->id.'</a>'
            . '<a href="#" class="delete"></a>
                      </li>'."\n";
    }
    /* free result set */
    $result->close();       
    $mysqli->close();
?>
like image 259
user1246950 Avatar asked Feb 11 '14 11:02

user1246950


People also ask

Can you add multiple click event listeners?

The addEventListener() methodYou can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements.

Can you add a click event listener to a div?

To add a click event listener on div tag using JavaScript, we can call the addEventListener method on the selected div. to add a div with a class. Then we write: const div = document.

Can a button have 2 event listeners?

We can add multiple event listeners for different events on the same element. One will not replace or overwrite another. In the example above we add two extra events to the 'button' element, mouseover and mouseout.

How do I add an event listener to multiple elements?

One way to add an Event Listener to multiple elements is by using the convenience of a for…of statement, which creates a loop to iterate over its passed elements. Another way to add an EventListener to multiple elements is by using a forEach () loop.

How to add click event to parent class?

It might be better to attach the click event to the actual parent container element instead of body. You have to use querySelectorAll as you need to select all elements with the said class, again since querySelectorAll is an array you need to iterate it and add the event handlers

How to attach the same event to multiple elements in JavaScript?

In JavaScript you add an event listener to a single element using this syntax: document.querySelector('.my-element').addEventListener('click', event => { //handle click }) But how can you attach the same event to multiple elements? In other words, how to call addEventListener () on multiple elements at the same time? You can do this in 2 ways.

What is addEventListener () in JavaScript?

The JavaScript addEventListener() method allows you to set up functions to be called when a specified event happens, such as when a user clicks a button. This tutorial shows you how you can implement addEventListener() in your code.


3 Answers

You should use querySelectorAll. It returns NodeList, however querySelector returns only the first found element:

var deleteLink = document.querySelectorAll('.delete');

Then you would loop:

for (var i = 0; i < deleteLink.length; i++) {
    deleteLink[i].addEventListener('click', function(event) {
        if (!confirm("sure u want to delete " + this.title)) {
            event.preventDefault();
        }
    });
}

Also you should preventDefault only if confirm === false.

It's also worth noting that return false/true is only useful for event handlers bound with onclick = function() {...}. For addEventListening you should use event.preventDefault().

Demo: http://jsfiddle.net/Rc7jL/3/


ES6 version

You can make it a little cleaner (and safer closure-in-loop wise) by using Array.prototype.forEach iteration instead of for-loop:

var deleteLinks = document.querySelectorAll('.delete');

Array.from(deleteLinks).forEach(link => {
    link.addEventListener('click', function(event) {
        if (!confirm(`sure u want to delete ${this.title}`)) {
            event.preventDefault();
        }
    });
});

Example above uses Array.from and template strings from ES2015 standard.

like image 54
dfsq Avatar answered Oct 18 '22 06:10

dfsq


The problem with using querySelectorAll and a for loop is that it creates a whole new event handler for each element in the array.

Sometimes that is exactly what you want. But if you have many elements, it may be more efficient to create a single event handler and attach it to a container element. You can then use event.target to refer to the specific element which triggered the event:

document.body.addEventListener("click", function (event) {
  if (event.target.classList.contains("delete")) {
    var title = event.target.getAttribute("title");

    if (!confirm("sure u want to delete " + title)) {
      event.preventDefault();
    }
  }
});

In this example we only create one event handler which is attached to the body element. Whenever an element inside the body is clicked, the click event bubbles up to our event handler.

like image 67
jackvsworld Avatar answered Oct 18 '22 06:10

jackvsworld


A short and sweet solution, using ES6:

document.querySelectorAll('.input')
      .forEach(input => input.addEventListener('focus', this.onInputFocus));
like image 42
Francisco Hodge Avatar answered Oct 18 '22 06:10

Francisco Hodge