Without using jQuery or any other library, the objective is to inform the user which URL will visit with an alert event. In the markup, there are multiple <a>
tags with different href
values for each, when the user clicks the <a>
tag, an alert
event displays mentioning where the user is going before actually leaving the website.
Workflow:
- The document loads
- The user clicks an
<a>
tag - An
alert
event displays with thehref
value of the clicked<a>
tag - Once the user closes the
alert
event, the browser starts loading thehref
website
Code sample:
document.querySelector('a').onclick = function(e) {
e.preventDefault();
var href = document.querySelector('a').href;
alert('You are going to: ' href);
window.location = href;
}
<div id="container">
<a href="https://www.microsoft.com/">Link A</a>
<a href="https://www.google.com/">Link B</a>
<a href="https://www.apple.com/">Link C</a>
</div>
Objective:
- Set up the JavaScript dynamically for all the
<a>
tags to achieve the workflow output for each one of them (and for any further<a>
tags with the sameclass
that might be included in the document). Please note that only Link A works as desired so far.
Your coding to solve this is appreciated!
CodePudding user response:
Use querySelectorAll()
to get all the anchor tags, then loop through them and addEventListener()
instead of onclick
, because onclick
can only be assigned to one element at a time. Also, you can grab the href with e.target.href
. e.target
is the element that was acted upon to start the event.
document.querySelectorAll('a').forEach(function(el) {
el.addEventListener("click", function(e) {
e.preventDefault();
var href = e.target.href;
alert('You are going to: ' href);
//window.location = href;
})
})
<div id="container">
<a href="https://www.microsoft.com/">Link A</a>
<a href="https://www.google.com/">Link B</a>
<a href="https://www.apple.com/">Link C</a>
</div>
CodePudding user response:
querySelector
will only match the first element that matches the selector. You can either use querySelectorAll
to match all of those elements, add listeners to all of them...
OR
Attach one listener to the container (event delegation allows it to capture events from its children as they "bubble up" the DOM). When a child element is clicked the handler function checks that its an anchor with a .link
class, and then executes the rest of the code.
const container = document.querySelector('#container');
container.addEventListener('click', handleClick);
function handleClick(e) {
if (e.target.matches('.link')) {
e.preventDefault();
const { href } = e.target;
alert(`You are going to: ${href}`);
window.location = href;
}
}
<div id="container">
<a href="https://www.microsoft.com/">Link A</a>
<a href="https://www.google.com/">Link B</a>
<a href="https://www.apple.com/">Link C</a>
</div>