Click here to Skip to main content
15,867,686 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

I have an image within an anchor. Now by clicking TAB I am focusing on the anchor and hitting ENTER. The actual operation is written within the onclick of the image. So, on the onclick of anchor I am calling the image onclick method to perform. But after performing the anchor tag onclick is being called again as propagation, and an infinite loop is getting started.

Can any one please help me to get a solution.

Full code is here.

HTML
<a onclick="alert('a clicked'); $('#i').click();" href="#" style="padding:60px 60px 60px 60px;">
<img src="Desert.jpg" width="50px" height="50x" id="i" onclick="alert('img clicked'); window.event.cancelBubble = true;event.stopPropagation();" />
</a>


What I have tried:

To solve this I have used
window.event.cancelBubble = true;
event.stopPropagation();

But its not working.

Note: Clicking on the image first, stopPropagation is working but clicking on the anchor first leads to an infinite loop.
Posted
Updated 31-Jan-17 1:07am
Comments
Richard Deeming 30-Jan-17 9:27am    
Why do you need both? Just move the real event handler code to the anchor's click event, and let the image click event bubble.
musefan 31-Jan-17 5:01am    
I have using inline event handling, so I may be wrong, but will `event` even exist? normally if you assign an event handler you need to specify the event parameter to be able to use it. Do you get any console errors?

1 solution

After all your function add return false, or from last function return false; It will stop

onclick="alert('img clicked'); return false;"


javascript - event.preventDefault() vs. return false - Stack Overflow[^]
 
Share this answer
 
Comments
Arkadeep De 3-Feb-17 0:39am    
I am sorry to say that, your trick is not working. Its still in an infinite loop.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900