DEV Community

prajin10
prajin10

Posted on

Difference between onClick and onMouseDown with real world project example

What exactly is the difference between.

  1. onMouseDown: A MouseEvent handler function. Fires when the pointer is pressed down.

2.onClick: A MouseEvent handler function. Fires when the primary button was clicked on the pointing device.

Now lets just move to its practical useCase.

So basically there was a input placeholder and i had to add the ❌ icon inside placeholder which would clear the input if there was any value typed in the input placeholder and the ❌ icon should only be shown if the input is focused (onFocus) and icon should be hidden if focus is removed from input box (onFocusOut) . I made this functionality by adding onFocus and onFocusOut to my input and added onClick event to my cross icon to clear the value .

But the problem that was occuring was when i did onFocus and typed something the ❌ icon was appearing but when i clicked on that ❌ icon instead of triggering functionality of on Click onFocusOut was triggered. So i got to know about onMouseDown and i had to do e.preventDefault which solved my problem.

Hope you understand the useCase and if u want to see the exact implementation in code i will show u just comment in this post.

Happy coding.

Note: In react/next onFocus and onBlur is used as replacement of onFocus and onFocusOut

Top comments (0)