Clicking on the child element triggers a blur event

I have a situation where a parent element contains an input:

<div @blur="onLeaveSelect($event)">
    <div v-if="searchActivated" >
        <input type="text" placeholder="Search..." @mousedown.stop>
    </div>
    ...
</div>

When I click on the input child element, it triggers the blur event of the parent div. How can this behavior be prevented? Using click.stop to stop bubbling works for other elements, but not for this input.

        const onLeaveSelect = (evt) => {
            if (!evt.currentTarget.contains(evt.relatedTarget)) {
                open.value = false;
                showDescription.value = false;
                searchActivated.value = false;
            }
        }

By implementing this solution, I managed to prevent the dropdown from closing when clicking on the input. However, now the issue is that focusing on the input no longer registers as focusing on the parent div, causing the blur event not to be detected properly.

Answer №1

I was looking for a similar functionality, however, the focusout event is not available in React.

To tackle this issue, I utilized the onBlur event and included a condition to check if any child element is the relatedTarget:

  • If the value is null, it means a child element hasn't been clicked (thus, indicating that we need to hide the drop-down)
  • If the value is not null, it signifies that a child element has been clicked (hence preventing the drop-down from getting hidden)

Below is a code snippet demonstrating the parent div:

<div
    tabIndex='-1'
    onBlur={e => e.relatedTarget === null && setState(false)}
>
...
</div>

Answer №2

After searching for an answer to my issues, I discovered that the key was utilizing the focusout event. This event not only identifies when focus leaves an element but also detects focus within an input child element. For more information, you can visit this link: focusout event on Mozilla Developer Network

Answer №3

Events bubble up causing them to be passed along to parent elements.

I came across an interesting question on SO that I've encountered frequently in the past: How to stop propagating event from parent div to child div

There are multiple methods to prevent this propagation, but one of the simplest solutions is to add the CSS attribute on the child element:

pointer-events: none;

If you still need the input to trigger events, consider adding this check inside the event handler for the parent element:

if(event.target !== event.currentTarget) return;

If you're still unable to achieve your desired result, try using this line within the event handler to prevent it from bubbling up to the parent element:

event.stopPropagation();

Additionally, I noticed that div elements do not naturally have the blur event unless they have a tabindex="0" or contentEditable attributes. It's possible that this directive sets this behavior when rendering the actual HTML.

Answer №4

When events bubble up through the DOM, you can prevent them from propagating further by using the e.stopPropagation() method within the child element's onClick() function.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What steps should I take to link form inputs from various child components to an array that is set in a parent component?

I'm in the process of linking form input from various child components (item-input-component) to an array itemList[] that is defined in a parent component (add-invoice-component). The goal is to gather three inputs (itemName, quantity, price), create ...

employing document.write() specifically for a designated division

This is the coding: $(document).ready(function(){ var Jstr = { "JSON" : [ { "Eid" : 102,"Ename":"", "Ecode" : "<input type ='text'/>", "Eprops": {"name": "", "value":"", "maxlength":""}} ] } ; $(".search").click(funct ...

How can I activate the socket.io connection event in NodeJS?

I'm currently experimenting with socket.io on NodeJS and I am facing a challenge in figuring out how to activate the socket solely from NodeJS. Previously, I have been using socket.io by invoking it from the front end. However, I am curious if it is ...

Do parallel awaits in JS/TS work only on Chrome browsers exclusively?

Encountering a strange issue with promise resolution behavior in JS/TS. Using Node LTS. It seems that the difference lies in whether the promise resolves to a value that is later read in the code or if it's simply fire-and-forget (void response type). ...

Passing an image source as a prop to a child component in Vue JS

Hey there, I've been experimenting with Vue Js and running into an issue regarding displaying an image on a child component. Here's what it looks like: Parent component: <list> <post name="post 1" image="somePath"/> <post nam ...

What is the process for transforming a markdown image into a Vue component in Vue3?

When transforming a markdown string into HTML content, the img element will be converted to an actual <img> tag. What I am seeking is to enable users to click on that image and have a modal window pop up, where they can view a larger version of the ...

No response being received from Ajax request

Having some trouble with an ajax function I developed for a small project. The issue lies in running the code inside the .done() function. This function is supposed to receive a json object from php (which I am obtaining a response via cURL), but it appear ...

Ionic app encounters issue fetching local JSON data

I have been working on my Ionic application and I encountered an issue when trying to load local JSON data into it. I set up a http.get in my javascript to retrieve the data, but for some reason it's not showing up in the application. It seems like th ...

What is the best way to toggle the visibility of my menu using JavaScript?

I recently implemented a script to modify a CSS property in my nav bar as I scroll down, triggering the change after reaching 100px. $(window).scroll(function() { var scroll = $(window).scrollTop(); //console.log(scroll); if ...

What methods can we employ to prevent the GraphQL query from being triggered with every keystroke when using React?

Recently, I received a new task that requires me to implement input value debouncing to prevent backend requests on every keystroke. Additionally, I need to establish an internal useState for CollectionsAutocomplete, which is connected to the generalQuery ...

Creating an AJAX XML tree without the need for a backend server language

My goal is to create a nodes tree using the information from a data.xml file, similar to what is demonstrated in this example, all done through AJAX. Can this be accomplished without utilizing a server-side programming language? I have access to the enti ...

What is the accurate way to determine the total number of minutes elapsed from a specific point in time?

String representation of the process start date: '2020-03-02 06:49:05' Process completion date: '2020-03-02 07:05:02' Question: What is the optimal method for calculating the time difference (in minutes) between the start and end ...

Tips for adding a CSS marker to the Videogular timeline at a designated time

My HTML player application allows users to search for a term and then displays the results along with the time when those words appear. By clicking on a specific sentence, the HTML player will start playing from that location. However, I would like to enha ...

Exploring the functionalities of can-deactivate without incorporating routing

I'm facing an issue with a parent component and multiple child components. The parent component contains a form, while each child component also has its own form. Unfortunately, all child components share the same route as the parent component and hav ...

What is the best method for setting a session cookie securely while also using CSRF tokens?

In my express application, I am working on setting the session cookie to be secure. Here is the code snippet I have tried so far: app.use(express.cookieParser()); sessionOptions = definitions.REDIS; sessionOptions.ttl = definitions.session.expiration; app ...

What is the best way to choose all elements that fall between two specific elements?

Looking to grab content situated between two specific elements within an HTML structure. The HTML snippet in question is as follows... <h2>This is firsty</h2> <p>Some para</p> <ul> <li>list items</li> <li&g ...

Tips for dividing by a large number

I am currently attempting the following: const numerator = 268435456; const denominator = 2 ** 64; const decimalFraction = numerator / denominator; In order to achieve this, I have experimented with utilizing the code provided in this link: : const rawVal ...

The ES6 alternative to require() when not using exports

When I utilize require(./filename), I am able to include and run the code within filename without any explicit export being defined inside filename. In ES6, what is the equivalent of this using import ? Appreciate it ...

Is it possible to receive a unique value error even when providing the correct key value in a map?

I encountered an issue while using a map function with an array in my application. Even though I have provided a unique key, Google Chrome console is still showing an error related to the unique key. Error Each child in a list should have a unique "ke ...

Tips for adjusting the material ui Popper width to fit the container without disabling the portal

Currently utilizing the material-ui popper library. I am trying to allow the popper to extend outside of its container in the vertical direction. To achieve this, I have set disableportal={false}. However, upon setting disableportal to false, when assign ...