Detect which link (with no id) was clicked?

Hello;
Lets say a link (with no id= ) was just clicked ,
and before it loads ,
how can I Detect which link was clicked ?

  a.addEventListener("click", WhichLinkWasClicked);
}

Function WhichLinkWasClicked() {
	
}

Thanks for your Help…

The function called WhichLinknkWasClicked is an event handler. Give that function a parameter of evt, and you can then access evt.target from inside of the function to find out which link was clicked.

1 Like

Do you mean like this ?:

  a.addEventListener("click", WhichLinkWasClicked(evt.target));
}

Function WhichLinkWasClicked(evt.target) {
	    alert(evt.target) ;
}

No, not like that. Go back to the code that you started with and only add evt as a parameter to the WhichLinkWasClicked function.

Sorry , stumped again:
Uncaught SyntaxError: Unexpected identifier
“Function WhichLinkWasClicked(evt) {”

<script>
  a.addEventListener("click", WhichLinkWasClicked());

Function WhichLinkWasClicked(evt) {
        alert("Function WhichLinkWasClicked(evt)") ;
	    alert(evt) ; 
		}
</script>

There are a few things happening here:

On a.addEventListener("click", WhichLinkWasClicked());, you should pass the function as a reference, but in your snippet, you are calling it directly. So if you remove the (), it’ll reference that function properly. That becomes this:
a.addEventListener("click", WhichLinkWasClicked);

To declare a function, you must use the reserved keyword function. Reserved keywords in Javascript are case-sensitive so Function is not the same as function. This is why you’re getting that error. The correct way of declaring it:

function WhichLinkWasClicked(evt) {
  ...
}

Next, your first alert will output the exactly this Function WhichLinkWasClicked(evt) as a string because you’re wrapping it in quotes. I’m not sure that’s what you want.

alert("Function WhichLinkWasClicked(evt)");

Your second alert is properly calling the evt argument, which is an object with several event properties and methods, and one of them is the exact link you clicked on. To access a property, you can use the dot notation, and evt.target will give you exactly that. It goes as below:

alert(evt.target);

Thanks for explaining all that Mateus .
But I am still doing something wrong
because the function never runs .

<!DOCTYPE html>
<html>
<body>

<p>This example uses the addEventListener() method to catch which kink was clicked.</p>

<a href="https://www.google.com">Visit google.com</a><br>
<a href="https://www.duckduckgo.com">Visit duckduckgo.com</a><br>
<a href="https://www.w3schools.com">w3schools.com</a>

<script>
  a.addEventListener("click", WhichLinkWasClicked);
function WhichLinkWasClicked(evt) {
	    alert(evt.target) ; 
		}
</script>

</body>
</html>

https://www.w3schools.com/code/tryit.asp?filename=GLBE1ADKI33W
Thanks

Ah right, I was under the assumption you had a reference to the anchor tags in your code. Looks like you don’t.

So the a in a.addEventListener is a variable that hasn’t been declared yet. That variable should hold a reference to your anchor tags. So before you even call your function, you need to declare what that a is, and you can add this before your code:

const a = document.querySelectorAll('a'); // This defines a variable that holds a nodelist that references all the three anchor tags in your markup.

A nodelist is very similar to an array and share similar properties and methods. Since each value inside your nodelist carries a node (an anchor tag), you should iterate through the list in order to add an event listener to each one of your anchor tags.

With the variable in hands, you can now iterate through it, for example:

for (let single_a of a) { //single_a is a single item in your array during the iteration. a is the variable you just created.
  anchor.addEventListener("click", WhichLinkWasClicked);
}

Tip: since you’re creating a nodelist with every anchor tag. I’d recommend you to change the variable name to something more meaningful, like anchorTags or anchorList. That’s up to you.

EDIT:

Check it out. I’m not sure if you’re trying to get to the solution yourself, but there’s a possible solution here.

1 Like

Hi there vmars316,

do not rely upon w3schools, it is unreliable. :wonky:

This will make your alert work…

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">

<title>Untitled document</title>

</head>
<body>

<p>This example uses the addEventListener() method to catch which kink was clicked.</p>

<a href="https://www.google.com">Visit google.com</a><br>
<a href="https://www.duckduckgo.com">Visit duckduckgo.com</a><br>
<a href="https://www.w3schools.com">w3schools.com</a>

<script>
	var link = document.querySelectorAll( 'a' );
	for ( var c = 0; c < link.length; c ++ ) {
         link[c].addEventListener('click', WhichLinkWasClicked);
      }
function WhichLinkWasClicked(evt) {
    evt.preventDefault();
    alert( evt.target ) ; 
		}
</script>

</body>
</html>

coothead

1 Like

It can be written more concise:

const logFunction = (evt) => {
  alert(evt.target)
}

document.querySelectorAll('a').forEach(anchor => {
  anchor.addEventListener('click', logFunction)
})

Also make sure to define the method you want to call before you attach the listener to it.

Thank you very much guys , that’s a wealth of information !

Thanks coothead ;
Only thing I don’t understand is “evt” .

function WhichLinkWasClicked(evt) {
    evt.preventDefault();
    alert( evt.target ) ; 
		}

How did “WhichLinkWasClicked” get hold of the event code as “evt” . It isn’t a reserved word , is it ?

Thanks

Web browsers used to put information about the event in a global variable called event. That was found to be somewhat unreliable and so now web browsers pass that event information as the first argument of the event handler. The WhichLinkWasClicked function is an event handler. Using evt for the first parameter of that function is an accepted good practice to receive the event information.

2 Likes

evt, event, or e, or, “Something descriptive of what the parameter is” which is good practice for ANY function parameter. Strictly, it doesnt matter what you call the parameter, but it makes the code readable.

function WhichLinkWasClicked(potato) would still work, and potato would be the event object. But if I handed you a piece of code that just said

function WhichLinkWasClicked(potato) {
    alert( potato.target ) ; 
		}

Which is still valid code, you’d have a lot less of an idea of what is actually being done.

2 Likes

Aha… Thank you !

It’s got a lot better to be fair.

That may well be true. :winky:

This, though, is still rather naughty…

W3Schools Certifications $95.00 :eek:

coothead

1 Like

…and it seems that I am not alone… …

Are W3Schools Certifications worthless? :rofl:

coothead

1 Like

Yeah, because no one should sell a bunch of lessons put together to teach you a subject. looks at SitePoint Books… oh right.

W3Schools, as it is today, is fine as a reference site for beginners. It’s not a technical manual, it’s not MDN, but it serves a decent role as a userfriendly basics.

“Oh but it was trash”… means nothing, unless you do your reference lookups using the wayback machine.

I think people mostly take issue with the “W3” portion of the name, as that tends to give a sense of false advertising, duping people into thinking they are associated with W3C.

However, I fully agree that they are fine as a reference site for beginners.

2 Likes