Reputation: 65
I am using Greasemonkey and JavaScript to modify a page. I have found all the external links and added a image before links, I want to add a mouseover event on images. I don't know how to do that in the loop. Here is what I have:
var anchors = document.evaluate('//a[@target]',document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var icon4 = document.createElement('img');
icon4.src = '...';
for (var a = 0; a < anchors.snapshotLength; a++){
if (anchors.snapshotItem(a).href.substring(0,16) != location.href.substring(0,16)){
icon4.addEventListener('mouseover', function(){this.title = 'Hello'}, false);
icon4.addEventListener('mouseout', function(){this.title = ''}, false);
anchors.snapshotItem(a).parentNode.insertBefore(icon4.cloneNode(true),anchors.snapshotItem(a));
}
}
Upvotes: 1
Views: 681
Reputation: 93493
Do not use anonymous functions in a loop like that. That leads to memory and performance problems.
Anyway, use the return value of insertBefore()
. like so:
var anchors = document.evaluate (
'//a[@target]', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null
);
var icon4 = document.createElement('img');
icon4.src = '...';
for (var a = 0; a < anchors.snapshotLength; a++) {
if (anchors.snapshotItem(a).href.substring(0, 16) != location.href.substring(0, 16)) {
var newNode = anchors.snapshotItem(a).parentNode.insertBefore (
icon4.cloneNode (true), anchors.snapshotItem (a)
);
newNode.addEventListener ('mouseover', myMouseInOutHandler, false);
newNode.addEventListener ('mouseout', myMouseInOutHandler, false);
}
}
function myMouseInOutHandler (zEvent) {
if (zEvent.type == "mouseover") {
zEvent.target.title = 'Hello';
}
else if (zEvent.type == "mouseout") {
zEvent.target.title = '';
}
}
Upvotes: 1