I have a parent div which when clicked, initializes a function. Inside this parent div, i have selectable and draggable divs which in an intuitive sense are suppose to "lay above the parent div" or "lay inside the drawing board". These child divs also have functions initialized when these divs are clicked.
My problem is that mouseclicks made on these child divs, triggers mouseclicks on the parent div. The on:mouseclick action defined in the parent div shall only be initialized when clicking the parent div, and not when clicking the child div.
Screenshot taken from inspection. Here the div with the class "board" is the parent div, containing a on:mouseclick, which should not be triggered when clicking on the child divs contained in the parent div.
A codesnippet. Here, when ObjectSelection and ObjectOnBoard are clicked, the shown on:mouseup action is triggered, which is undesirable.
<div class='board' on:mouseup={$selected != null ? createObject : null}>
<ObjectSelection/>
{#each $editor.objects as object}
<ObjectOnBoard bind:x={object.geometry.x} bind:y={object.geometry.y}/>
{/each}
</div>
CodePudding user response:
It is normal behavior for events to bubble up the hierarchy. You can either...
- Stop the event on the child level by handling it there and calling
stopPropagation
/use the event modifier with the same name for that. - Filter your logic at the parent by comparing the
event.target
withevent.currentTarget
, if they are the same, the event occurred at the parent's level. As noted in the comments, the event modifierself
also performs this function.
Also, using a click event on regular div
elements is not accessible. If something is clickable it usually should be a button
or an a
element, depending on its function. Styling can be adjusted to fit the context.