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

Comparing getElementById with $('#element') for retrieving the length of an input field

Consider the following scenario: <input type="text" id="apple"> Why does the first code snippet work? $(document).ready(function () { alert($('#apple').val().length); }); However, why does the second code snippet not work as expecte ...

Utilizing jQuery to send AJAX requests and display the results on separate lines within a textarea

My form includes a text area where users can enter keywords, one per line. I would like to implement the following functionality: upon clicking a button, an ajax request will be sent to the server to retrieve the result for each keyword entered. The resul ...

Choose every fourth row in the table

Is there a way to alternate the background colors of selected groups of 4 rows in a table? I want to make one group red and the next group blue. Any suggestions or ideas on how to achieve this? <table> <tr style="background-color: red;"> ...

The fixed-top navigation bar in Bootstrap obscures the links within the #content

As a student studying software development, I am currently working on a web development project for my class. Utilizing Bootstrap, I have implemented a navbar-fixed-top and structured the body as a table-striped table with each row containing a <a href= ...

Sending Data from Clicked Button to Another Component as a Prop

I am struggling to figure out how to pass a value that is set inside a button to a child component. Essentially, I want the value of the clicked button that displays a percentage to be passed as a prop value. This prop value should update depending on whic ...

Adjust the Vue.js template based on the chosen publisher's preferences

I am working with two selectors, one for the publisher and one for the template. When I select publisher id=2, the second selector (for the template) only displays values related to that specific publisher. The template table includes a publisher_id fiel ...

Adding 2-dimensional text to a specified location with the help of three.js

let startPosition = new THREE.Vector3(-5,0,0); let targetPosition = new THREE.Vector3(-5,2,0); let directionVector = new THREE.Vector3().sub(targetPos,startPosition); let arrowHelper = newTHREE.ArrowHelper(directionVector.clone().normalize(),startPosition, ...

Strategies for passing a JavaScript variable to a JSP function

I'm dealing with a JavaScript code that has a value stored in its variable that I need to pass to my JSP function. However, I'm facing trouble passing it along. Take a look at the following code snippets: Javascript: $('button').on(& ...

Can you please tell me the name of this specific graph? And could you explain how I can recreate it on a

I am fully aware that this information is just a Google search away. However, I am unsure of the specific name of the chart I am seeking. Therefore, I am unable to conduct an effective search for suitable plugins or APIs. Your understanding is greatly appr ...

Reasons for the failure of file uploads from the React frontend to the backend system

Recently, I embarked on a new project that involves using React for the front-end and Node for the back-end. The main requirement of this project is to upload multiple images from the front-end, with the back-end handling the file uploads to Cloudinary. I ...

Can the layout created with JqueryMobile be used on both web and mobile platforms?

I develop websites using php for the backend and HTML/CSS for the frontend. Currently, the need to make my website mobile-friendly has arisen. I am contemplating utilizing JqueryMobile but I'm uncertain if the same layout will work for both desktop an ...

Most effective method to change a specific attribute in every element within a nested array of objects

Below is an example of my data object structure: const courses = [ { degree: 'bsc', text: 'Some text', id: 'D001', }, { degree: 'beng', text: 'Some text&apos ...

How can I add page transitions to my simple HTML website?

Working on an internal website project for my office using vue.js has been a rewarding experience. I appreciate how easily it allows me to manage multiple pages with dynamic content and seamless transitions. Unfortunately, my IT department is hesitating to ...

Having trouble retrieving the innerHTML of a span tag in a JavaScript function

I'm currently working on creating an email message that will have pre-filled text from an asp:Literal when a user clicks a link. The HTML code for this is structured like this: <tr> <td> <img src="../../images/Question.gif" ...

How to Animate the Deletion of an Angular Component in Motion?

This stackblitz demonstration showcases an animation where clicking on Create success causes the components view to smoothly transition from opacity 0 to opacity 1 over a duration of 5 seconds. If we clear the container using this.container.clear(), the r ...

MaterialUI makeStyles in NextJS causes custom css to revert back when the page is refreshed

Currently, I am working on a NextJS website with some unique styling applied through MaterialUI's makeStyles. Initially, everything looks perfect but then all the custom styling is reset on the second load. It seems to be related to the route, as it o ...

Decide on the javascript/jquery libraries you want to include

My app is experiencing slow loading times on the home screen and students using it from school district computers are running into ERR_CONNECTION_RESET errors due to strict firewalls. The excessive loading of javascript and jquery libraries in the head of ...

Exploring the iteration of objects utilizing underscore.js

Currently, I am diving into the world of backbone.js and encountering a slight issue while iterating over some models in a view. The first code snippet seems to be functioning correctly, but the second one, which is underscore.js-based, does not work as ex ...

Issue with Firefox-Android causing dropdown toggle to malfunction

When I manually trigger a dropdown, it closes when any click is performed outside of it (while open). This code works in all browsers except for Firefox on Android. Why does this happen? It seems like the event parameter doesn't reach the function ...

Transitioning React Hover Navbar Design

I'm currently revamping a click-to-open navbar into a hover bar for a new project. I have successfully implemented the onMouseEnter and onMouseLeave functions, allowing the navbar to open and close on mouse hover. However, I am facing an issue with ad ...