Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

[Easy] AddEventListener - How do I use "This"?

Featured Replies

  	document.getElementById ("readM").addEventListener ("click", 	function (){
		$.ajax({
			url: "ajax/updateReadMessage.php",
			type: "post",
			dataType: "json",
			data: { msgID: $('#readM').val() },
			success:function(result){
				console.log(result.abc);
			}
		});
	}, false);


Hi there. So I havn't used Javascript or really much programming at all in the past 2-3 years. I am trying to build myself a Messages system though for an idea I'm working on! My problem is however, that I can't access the correct data from this code above... The main parts are:

1) I have the ID "ReadM" which i access at the beginning. Now I have to say, i have multiple of these "ReadM" items. Each one will have its own event listener. So my problem is trying to make each event listener unique from each other...

2) On Line 6, i have a part which should make my event listener unique by passes a unique ID

The problem i face, is that with the current code, it will simply find the first "#readM' elment on the page and take the value from there. I essenetially feel like i want to change it to "this.val()" but that is not possible, it seems. 

 

So any support on this? would be great if anyone knew a quick fix for this... in the meantime howeve, i will continue to find a workaround!

 

thankyou!

 

 

 

Edit: 

for reference. the element in question!!!!

<button id='readM' value='".$row['ID']."' class='readMessage_trigger'>Read Message</button>

 

Edited by geniebud2

An elements ID attribute should be unique per page, you should never have more than one element on the page with the same ID.

You could use the class name and add event listeners on that, for example (just written quickly, not tested)

document.querySelectorAll('.readMessage_trigger').forEach((trigger) => {
  trigger.addEventListener('click', () => {
    $.ajax({
      url: "ajax/updateReadMessage.php",
      type: "post",
      dataType: "json",
      data: { msgID: trigger.value() },
      success:function(result){
        console.log(result.abc);
      }
    });
  });
});

Which gets all of the elements with a class of readMessage_trigger, then for each one assigns that element to the 'trigger' variable, then adds the click event listener.

  • Author

Thanks for reply. Essentially I think this is what i did slightly differently:

 

                var forumLinks = document.getElementsByClassName('forumLink');

                for(let i = 0; i < forumLinks.length; i++) {
                  forumLinks[i].addEventListener("click", function() {


So yeah, your code is nicer though, i should use foreach more but yeah... thanks dude!
 

  • 2 weeks later...
On 8/4/2019 at 1:21 PM, geniebud2 said:

i should use foreach more but yeah... thanks dude!

I agree foreach writes and reads better, but the for-loop is faster and doesn't generate a new scope. So there's really no need to write foreach, 'cause the best performance is with the oldfashioned for...-loop

Edited by Maarten

18 hours ago, Maarten said:

I agree foreach writes and reads better, but the for-loop is faster and doesn't generate a new scope. So there's really no need to write foreach, 'cause the best performance is with the oldfashioned for...-loop

The performance debate doesn't really add up here, looping over an event listener is slow regardless, especially compared to making use of event bubbling and capturing. The performance of one type of loop isn't going to be noticeable unless you have an obvious bottleneck, but in most JS code you won't feel the affects of it.

I'd also argue the other point, I'd prefer to have scope rather than declare everything in the global scope, lexical scope and closures are some of the best parts of JS. Even if you're not using forEach here, you still have scope inside of addEventListener since it's a function, so this doesn't really make sense anyway.

Edited by Jack

Create an account or sign in to comment

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.