Reputation: 195
I been trying to figure this out, but I haven't yet.
I am building column in html of anchor tags and I would like to know the id of the one that has the mouse over it.
It should be simple, but seems like I hit a wall and I can't see how to solve this.
The problem I have is that the id that is display on the console is all the time the last id of the array. And instead of that I want to the id of the specific anchor.
Any suggestions are really welcome.
Here is my code:
//Anchor builder
var numberOf = flatParamDateArray.length;
for (i = 0; i < numberOf; i++) {
var param2Slider = document.createElement("a");
param2Slider.id = 'sliderAnchor' + i;
sliderAnchorId = param2Slider.id;
param2Slider.name = 'param2Slider';
param2Slider.className = 'nav2Slider a';
document.getElementById('nav2Slider').appendChild(param2Slider);
$('.nav2Slider a').onmouseover = function () {
console.log('flatParamDateArray index: ' + param2Slider.id);
}
}
Upvotes: 1
Views: 241
Reputation: 3093
Your variable param2Slider
is global and the for
loop changes the value on every loop. This means that after the loop is finished param2Slider
just contains the last value.
Try this:
$('.nav2Slider a').on('onmouseover', function () {
console.log('flatParamDateArray index: ' + $(this).attr('id'));
});
Edit: onmouseover... & of course you should move this snippet out of the loop
Upvotes: 0
Reputation: 79123
1. Move this out, and after the for-loop:
$('.nav2Slider a').onmouseover = function () {
console.log('flatParamDateArray index: '+param2Slider.id);
}
2. Change onmouseover()
to mouseover()
:
$('.nav2Slider a').mouseover(function() {
console.log('flatParamDateArray index: '+param2Slider.id);
});
3. To get the ID, this is the code you need:
console.log('flatParamDateArray index: '+ $(this).prop('id'));
Bonus:
Since you are dynamically adding links, you should use the .on()
function, to reduce the number of event handlers to one (as opposed to one per element):
$('.nav2Slider').on('mouseover', 'a', function() {
console.log('flatParamDateArray index: '+ $(this).prop('id'));
});
Upvotes: 2