What is the best way to apply a class to a container when a component in AngularJS receives focus or is clicked?

I am trying to apply a class to the container when either the input field is focused or when the dropdown component receives focus or is clicked. The class should be removed when the focus is lost.

The requirement is for the input container to have the 'active' class when either the input field or the dropdownComponent is in focus or clicked. I managed to do this using ng-focus and ng-blur for the input field.

However, applying ng-focus and ng-blur directly to an included component did not work as expected. I tried wrapping the component in a div container, but still faced issues with ng-blur.

Here's the code snippet:

<div class="input-container" ng-class="{'active': focus}">
    <dropdownComponent ng-if="dropdownButton" element="dropdownElement">
    </dropdownComponent>

    <input type="text"
        id="{{inputElement.key}}"
        class="form-control"
        placeholder="{{inputElement.placeholder}}"
        ng-model="inputElement.values[0]"
        ng-readonly="{{::inputElement.readonly}}"
        ng-focus="focus=true"
        ng-blur="focus=false;"
        ng-required="{{::inputElement.required}}"
        novalidate />
</div>

Is there a way to add something like this?

<dropdownComponent ng-if="dropdownButton" 
                   ng-focus="focus=true"
                   ng-blur="focus=false"
                   element="dropdownElement">
</dropdownComponent>

Directly adding ng-focus and ng-blur to the component did not yield the desired results.

Although focus-within using CSS works, it is not supported in older browsers.

Answer №1

The functionality is not compatible with the component due to the limitations of the focus and blur events, which are specifically designed for form elements. For components like dropdowns, it is advisable to utilize the mouseenter and mouseleave events instead. Additionally, consider implementing the click event for handling clicks on the component.

Updated:

<div class="input-container" ng-class="{'active': toggleClass}">
    <dropdownComponent ng-if="dropdownButton" ng-click="toggleClass = !toggleClass" element="dropdownElement"></dropdownComponent>
</div>

In your .js file, initialize the variable as $scope.toggleClass = false;

REMOVE CLASS ONCLICK OUTSIDE:

var element = document.querySelector('.input-container');    
$window.onclick = function(event) {
        if(event.target !== element && element.classList.contains('active')) {
            $scope.toggleClass = false; 
        }
    }

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

Dynamic commenting with AJAX and jQuery

I've been working on implementing live comments on my website using AJAX with jQuery alongside PHP and HTML. Despite my best efforts, the code I'm using doesn't seem to be functioning properly. In this code snippet, comments.php is responsib ...

Starting data initialization using a property object within a Vue component

I am encountering an issue with two Vue components, EventTask and EventCard. Within EventTask, there is a currentEvent object in the data section, which I pass as a prop to EventCard using the following code snippet: <event-card :current-event="cur ...

Utilizing Gulp variables to create dynamic destination file names?

As a newcomer to gulp, I am curious about the feasibility of achieving my desired outcome. Here is the structure of my projects: root | components | | | component_1 | | styles.scss | | actions.js | | template.html | | ... | componen ...

Troubleshooting: Problems with AngularJS $http.get functionality not functioning as expected

I have a user list that I need to display. Each user has unread messages and has not created a meal list yet. I want to make two http.get requests within the main http.get request to retrieve the necessary information, but I am facing an issue with asynchr ...

The transformation of a class-based component into a functional one is proving to be ineffective

I am attempting to transform my class-based component into a functional one, but I am struggling with passing two parameters in one onClick function without relying on set state. Additionally, I want to avoid creating multiple extra functions as it would i ...

The choices in the cell table selection are obscured due to the select table's height when opened

I am experiencing an issue with a table where each row contains two cells with "select" options. The problem arises when I open them, as they load within the table and the available options are not clearly visible. I can only view all the options by scroll ...

Having trouble retrieving image using "image-to-base-64" in react?

Utilizing the package "image-to-base64" for converting images from URLs to base64 is resulting in an error when attempting to fetch images: TypeError: Failed to fetch at imageToBase64Browser (browser.js:11:1) at convertImage (mealPlanTablePDF.tsx:2 ...

Display various components using a dropdown selection

I am seeking guidance on how to display different components based on the selected option. I am unsure of how to write the code for displaying either component one or two. Can you provide any examples or references that may help? <template> <div ...

Challenges with uploading files using jQuery

Click here to upload a file I'm trying to create a feature where users can choose an image and have it displayed in place of the "trees" image. Feeling stuck, I could really use some guidance. Check out the code below: <div class="user-editab ...

Saving asp.net strings in different formats to datetime fields in a database

Can someone please assist me with saving the string value of textbox to the database as a datetime, and for updating/editing purposes, display it again in the textbox as a string? The reason for this is that the datetime input will be copied from Outlook a ...

Try utilizing the array find() method in place of a traditional for loop

Is there a better way to refactor this code using the Array.find() method instead of nested for loops? onLoadTickets() { const ticketsReq = this.ticketService.getTickets(); const tariffsReq = this.tariffService.getTariffs(); forkJoin([ticketsR ...

Determine the Number of Table Columns Using jQuery

I'm curious, with jQuery how can one determine the number of columns in a table? <script> alert($('table').columnCount()); </script> <table> <tr> <td>spans one column</td> <td ...

Emberjs: Developing a self-focusing button with Views/Handlebar Helpers

Currently, I am using a Handlebars helper view that utilizes Em.Button (although it's deprecated) to create a Deactivate Button. This button is designed to focus on itself when it appears and clicking it triggers the 'delete' action. Additio ...

Using React Bootstrap: Passing an array to options in Form.Control

I'm currently utilizing Form.Control to generate a dropdown list and I want the list to be dynamic. Here is my code snippet: render() { return ( <Form.Control as="select" value={this.state.inputval} onChange={this.updateinputval}> ...

Limit the Jquery selection specifically to elements on the modal page

Recently I encountered an issue with a webpage that opens a modal form. The problem arises when the validation function, written in JQuery, checks all fields on both the modal and the page beneath it. //validate function function validateFields() { v ...

Recognizing when a Bootstrap dropdown with multiple options is deselected through Jquery

I'm working with a dynamic bootstrap multiple drop-down selector and I need to execute some code when a user deselects an option. <select id="selectOptions" multiple> <option>Test1</option> <option>Test2</option> & ...

Why does my Javascript cross-domain web request keep failing with a Status=0 error code?

UPDATE: I've been informed that this method doesn't work because craigslist doesn't have an Allow-Cross-Domain header set. Fair point. Is there an alternative way to download a page cross-domain using Javascript in Firefox? It's worth ...

Substituting HTML checkboxes with highlighted images for consistent display across different web browsers

I am looking to transform a list of HTML checkboxes into clickable images for the user to select or deselect. My goal is to create a similar functionality as shown in this video using just CSS if possible. I have successfully implemented it in Chrome wit ...

The template literal expression is being flagged as an "Invalid type" because it includes both string and undefined values, despite my cautious use of

I am facing an issue with a simple component that loops out buttons. During the TypeScript build, I encountered an error when calling this loop: 17:60 Error: Invalid type "string | undefined" of template literal expression. In my JSX return, I ...

Setting up an Ubuntu Node.js server and deploying AngularJS websites: A step-by-step guide

Is there a way to properly deploy websites built on Angular (autogenerated with Yeoman) on an Ubuntu server? I have a project built in Angular, generated using Yeoman's basic example. I can run it and view it on my computer with "grunt serve," but I&a ...