skip to Main Content

I’ve created a simple chrome extension to place a download button over any image that you hover your mouse over. The problem is the positioning of this icon is based on the location of the hovered image at the time of mouseover, so if you scroll and your cursor stays hovered on the image as the scroll happens, the icon stays visible but does not follow the scroll because it’s position is just static until you stop hovering and it goes away. I made a picture to more easily explain. I’m trying to have the icon follow the corresponding image if you scroll while keeping your cursor hovered.

Hover before and after scroll

The problem is that I cannot just give it position: absolute because ideally I can use this on any website and I cannot always account for the parent div attributes. So I position based on the location on the page at the time hover.

    let left= img.get(0).getBoundingClientRect().left+10,
         top= img.get(0).getBoundingClientRect().top+10;
    $('body').prepend(`
            <img id="ext-emp-download" src="${chrome.runtime.getURL("img/down.png")}" style="width:45px !important;height:45px !important;position:fixed;z-index:123456789;border-radius:20px;margin-top:${top}px;left:${left}px">`)
        

any suggestions on what I can add to this to make it function better or have the icon follow the image with the scroll?

3

Answers


  1. Use position: absolute; and make parent position: relative; then icon will folow parent.

    Login or Signup to reply.
  2. Stop using margin-top, use top instead and use position:absolute instead of fixed, also since it seems you are already using jQuery (?), use jQuery:s offset-method to calculate the placement rather than getBoundingClientRect:

    let left = img.offset().left + 10, top = img.offset().top + 10;
      $('body').prepend(`
      <img id="ext-emp-download" src="${chrome.runtime.getURL("img/down.png")}" style="width:45px !important;height:45px !important;position:absolute;z-index:123456789;border-radius:20px;top:${top}px;left:${left}px">`)
    
    Login or Signup to reply.
  3. I don’t think there’s a good solution for this especially if you want to account for all possible scenarios of the parent element.

    However, instead of appending your element to the body element, you can choose to append to the .scrollParent() of the img tag instead. This makes sure the position of it is dependent on the element that is scrolling. In addition, position: fixed is probably not what you want given that once the user scroll, you have to manually update its position.

    An alternative approach is you can make use of context menu instead: https://developer.chrome.com/docs/extensions/reference/contextMenus/, this allow user to right-click and select your extension for "Download" for instance.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search