Search code examples
javascripthtmlanchorzeroclipboard

Why is the onclick event not firering on my anchor with an image inside it?


I'm working on copy to clipboard using the zeroclipboard api,. I made a simple test page with an HTML anchor as follows:

<a href="#" id="copy" >copy</a>

By clicking on copy link, the text is copied to clipboard, all js events are firing and are being logged properly into the console, but when I change the example above to have an image inside the anchor for better user experience:

<a href="#" id="copy" ><img src="copy.gif" alt="copy"/></a>

...the code does no longer work and no events are fired.


Solution

  • Set the image as the background image of the a element using CSS.

    #copy {
        background-image: url('copy.jpg')
        display: block
        width: XXXpx
        height: YYYpx
    }
    

    You can use display: inline-block if you want the a element to behave more like a span.