0

Ok, I am a super newbie here, so keep that in mind. I have several messages in li items saved in bskt_messages. It is an HTML Collection. I am trying to add a click event listener, but every time I run the page, it calls the return_value function automatically. I have used code from similar posts on this site but there seems to be no difference. What am I doing wrong here?

$(document).ready(function() {  
     var bskt_messages = document.querySelectorAll('.message_item');    
    for (let i = 0; i < bskt_messages.length; i++) {
        bskt_messages[i].style.cursor = 'pointer';
        bskt_messages[i].addEventListener("click", return_value(i));
    };
});

function return_value(i) {
console.log("clicked " + i);
}
  • that's because you are executing this function right when document is ready. If you want to set `return_value` function as a listener, you should use itself: ```bskt_messages[i].addEventListener("click", return_value);``` – Dmitry Aug 26 '20 at 18:55

1 Answers1

0

That's because you're executing the function. You want to nest your function call within the click method.

$(document).ready(function() {  
    var bskt_messages = document.querySelectorAll('.message_item');    
    for (let i = 0; i < bskt_messages.length; i++) {
        bskt_messages[i].style.cursor = 'pointer';
        bskt_messages[i].addEventListener("click", function (event) {
            event.preventDefault();
            return_value(i);
        }
        
        );
    };
});
function return_value(i) {
    console.log("clicked " + i);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="message_item">btn0</button>
<button type="button" class="message_item">btn1</button>
<button type="button" class="message_item">btn2</button>

Note that it's not a good practice to spawn too many event listeners. For three buttons you're fine, but with dozens of items, you should listen to events on the parent element and compare the event target with your desired element (e. g. a button Node perhaps stored in an array).

const wrapper = document.querySelector('#wrapper_around_buttons');
const myButtons = wrapper.querySelectorAll('button');
wrapper && wrapper.addEventListener('click', event => {
   let button = event.target.closest('button');
   if (button && myButtons.include(button)) {
       console.log("clicked a button!");
   }
});
ericek111
  • 575
  • 7
  • 15
AHT Cloud
  • 51
  • 4