'How can I prevent link behavior on clicking an image inside an anchor element?

I have a code similar to this:

<a href='link.html'>goto link page <img src='images/edit.gif' alt='Dont Go, just edit' onclick='doEdit()'></a>

Now I want the href link to work as normal if you click on the text, but if you click on the image, it should do something else and not goto the link at all.

There is also a restriction, I cannot edit the link or its text, the only thing that I have total control over is the img tag and its called onclick function. So I have to prevent the link from going on from within that img tag.

Any help will be appreciated.



Solution 1:[1]

Just preventDefault on the click event when the target is an <img>

yourAnchor.addEventListener('click', function (e) {
    if (e.target.tagName === 'IMG')
        e.preventDefault();
});

Solution 2:[2]

Pass the event through to the doEvent method call, similar to this:

<a href='link.html'>goto link page <img src='images/edit.gif' alt='Dont Go, just edit' onclick='doEdit(event)'></a>

Then you can call event.preventDefault() to cancel the event and do your own thing, similar to this:

function doEdit(event){
    // your code here

    event.preventDefault();
}

DEMO - Using the event object to cancel the event.


Solution 3:[3]

Im not quite sure what you mean but if you want the text to have a link and the image to have a onclick event

text

<a href='link.html'>goto link page</a>

image

 <img src='images/edit.gif' alt='Dont Go, just edit' onclick='doEdit()'></img>

Solution 4:[4]

My initial thought is to simply remove the image tag from between the link tags.

    <a href='link.html'>goto link page</a>

    <img src='images/edit.gif' alt='Dont Go, just edit' onclick='doEdit()'/>

Are there more restrictions that do not allow you to do something like this?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Paul S.
Solution 2 Nope
Solution 3 OHH-MYSTA-CODE
Solution 4 mustaccio