0

I saw some questions who were similar to mine and even one that is pretty much identical And the answer to that question was to use $(this) for some reason when I use this it executes the $(this) on the document.

var $dropDownItems = $('.notifi-drop').children();
$(document).on('click', $dropDownItems, function(event){

this is the code I am trying to execute. If I do a normal .click() event it works fine and I can use this to get the corrent element. e.g

$($dropDownItems).click('click', function(event){

I tried the following (with the on event) but all of them were undefined

console.log($(this).attr('id'))
console.log($(event.target.text))
console.log($(this).text())
    

Just a note: If you didn't see, $dropDownItems is the children of a specific element. I guess that this is the problem in here.

The class and the children of the class:

<div class="dropdown-menu notifi-drop dropdown-menu-right">
                                {% for i in notifications %}
                                    <a class="dropdown-item friend-name-{{username}}">{{i}}</a>
                                    <button type="button" class="btn btn-outline-danger friend-rejected">Reject</button>
                                    <a>⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀</a>
                                    <button type="button" class="btn btn-outline-success friend-accepted">Accept</button>
                                    <hr>
                                {% endfor %}
                            </div>

To clarify even more, I want to detect which child was clicked on and get the child's text.(what I am doing with the click even and this).

FYI: The reason I want to use the on event is because I am appending data and the click event can't handle it.

Patch
  • 694
  • 1
  • 10
  • 29

1 Answers1

0

When you want to use event delegation, you should be using a selector, not a jQuery object.

So in your case you want to use > * to match the children of the element.

$(document).on('click', '.notifi-drop > *', function(event){
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • There is a minor problem now, when the data is appended and I am trying to get the index of the current child, it prints `-1` insted of the actual location (in my case it should print `2`). If I refresh the page it works fine, but for some reason when I append the data it's always `-1`. What do you think the problem is and how do you suggest in order to fix it? – Patch Jul 16 '20 at 18:38