Reputation: 12512
I have a few links. When I hover mouse over the links I would like to get the values stored in data attributes. I need to pick the t values and pass them into function
HTML
<a href="#" data-lat="23.333452" data-lon="-97.2234234">
JS
var loc = document.querySelectorAll("a[data-lat]");
loc.addEventListener("mouseover", locOver);
loc.addEventListener("mouseout", locOut);
function locOver() {
// do something
}
function locOut() {
// do something else
}
It's been a while since I used vanilla JS and it's been a long day so I'm sure it's pretty close but I'm stuck. I keep getting:
Uncaught TypeError: loc.addEventListener is not a function
What am I missing here?
Upvotes: 0
Views: 2017
Reputation: 474
const loc = document.querySelector("a[data-lat]");
const locOver = () => {
console.log("Mouse is over the link");
}
const locOut = () => {
console.log("Mouse is out of the link");
}
loc.addEventListener("mouseover", locOver);
loc.addEventListener("mouseout", locOut);
<a href="#" data-lat="23.333452" data-lon="-97.2234234">Link</a>
Explanation: I target the link using .querySelector method that returns a single node. After that i created two event handler for mouseOver and mouseOut and than i added the eventListener to the link.
Upvotes: 1
Reputation: 19986
You need to loop through the nodes that you obtained with document.querySelectorAll("a[data-lat]")
for adding events.
Working example.
<a href="#" data-lat="23.333452" data-lon="-97.2234234">Node</a>
<script>
var loc = document.querySelectorAll("a[data-lat]");
loc.forEach(node => {
node.addEventListener("mouseover", locOver);
node.addEventListener("mouseout", locOut);
})
function locOver(event) {
// do something
console.log('mouseover', event.target.dataset)
}
function locOut() {
// do something
console.log('locOut')
}
</script>
Upvotes: 2