I'm trying to add a link on an image when i'm hovering the image. Currently my javascript is as follow:
// check elements mouse is hover
document.addEventListener("mouseover", addCropLink, true);
document.addEventListener("mouseout", removeCropLink, true);
// add link if element is image
function addCropLink(){
var target = event.target;
if (target instanceof HTMLImageElement){
var cropLink = document.createElement("a");
cropLink.setAttribute("class", "resizeMyPhoto");
cropLink.setAttribute("id", "resizeMyPhoto");
cropLink.setAttribute("target", "_blank");
cropLink.innerHTML += "Crop/Resize";
cropLink.href = chrome.extension.getURL("index.html#");
cropLink.href = cropLink.href + target.src;
target.parentNode.style.position = "relative";
target.parentNode.style.display = "inline-block";
target.parentNode.insertBefore(cropLink, target.nextSibling);
}
}
// remove link if element is image
function removeCropLink(){
var target = event.target;
if (target instanceof HTMLImageElement){
var cropLink = document.getElementById("resizeMyPhoto");
cropLink.parentNode.removeChild(cropLink);
}
}
The problem is that when a user tries to click the link, he is doing mouseout from the image and the link is being removed.
Can some one suggest a solution?
edited using mouseout / mouseleave did not solved the issue.
OK so I have changed my script so it won't run on mosueleave / mouse out at all. i'm cecking on which element the mouse is over and if he is not on the image OR the link i created, i remove the link. here is the full javascript with comments:
iconURL = chrome.extension.getURL("/icons/button-icon.png");
// check elements mouse is hover
document.addEventListener("mouseover", setLink, true);
// handles creating of the crop link
function setLink(){
var target = event.target;
if (target instanceof HTMLImageElement){
// make sure no links are visible
var cropLink = document.getElementById("resizeMyPhoto");
if (cropLink !== null){
cropLink.parentNode.removeChild(cropLink);
}
// create the link
else{
cropLink = document.createElement("a");
cropLink.setAttribute("class", "resizeMyPhoto");
cropLink.setAttribute("id", "resizeMyPhoto");
cropLink.setAttribute("target", "_blank");
cropLink.innerHTML += "Crop/Resize";
cropLink.href = chrome.extension.getURL("index.html#") + target.src;
target.parentNode.style.position = "relative";
target.parentNode.style.display = "inline-block";
target.parentNode.insertBefore(cropLink, target.nextSibling);
}
}
else{
var cropLink = document.getElementById("resizeMyPhoto");
// make sure mouse is not on link
if(target == cropLink || cropLink == null){
return;
}
// remove the link
else{
cropLink.parentNode.removeChild(cropLink);
}
}
}
Hope this will help someone...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.