How to change a CSS class when clicking with AngularJS

I want to implement a feature where the CSS class of a div element changes when clicked. The default class should be 'input-large', and on click, it should change to 'input-large input-active'. This change should occur when clicking on the username field and revert back when clicking elsewhere.

<div class="input-large">
    <label class="input-label">Username</label>
    <input class="input-field" type="text">
</div>

<div class="input-large input-active">
            <label class="input-label">Username</label>
            <input class="input-field" type="text">
</div>

Can someone guide me on how to achieve this div change on click?

Answer №1

Make sure to incorporate ng-click and ng-blur by following the code snippet below:

http://jsfiddle.net/atXAC/11/

<div ng-controller="MyCtrl">

<div ng-class="{'active':hasFocus==true,'inactive':hasFocus==false}">Enter your Name here</div>
<input type="text" ng-model="user.name" ng-click="hasFocus=true" ng-customblur="onBlur()" required id="name"/>

</div>

Include this JavaScript code in your project:

var myApp = angular.module('myApp', []);

myApp.directive('ngCustomblur', ['$parse', function($parse) {
  return function(scope, element, attr) {
    var fn = $parse(attr['ngCustomblur']);      
    element.bind('blur', function(event) {        
      scope.$apply(function() {
        fn(scope, {$event:event});
      });
    });
  }
}]);

function MyCtrl($scope) {
    $scope.onBlur = function(){        
        $scope.hasFocus = false;
    }
}

Adjust it accordingly for your form - it should work seamlessly.

Answer №2

A different strategy is to dynamically add the CSS class within the onClick function in your controller.

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

The compatibility issue between Angular's ngModel and Value in input components

Encountering a challenge with the angular form. My objective is to create a form pre-filled with default values that can be edited. Upon validation, the form should submit the data to the MySQL database. Below is the component.html code: <form #adopt=& ...

Struggling to deploy my Laravel application with Tailwind CSS on the frontend. However, running "npm run dev" results in an error

While running the npm command `npm run dev` in cmd, I encountered an error stating that I require PostCSS v8 even though I already have PostCSS v8.3 installed. Could it be possible that Tailwind CSS specifically needs version 8 despite newer versions being ...

Dynamically attach data to the state.go function and access it in the resolve property

In my application, I have a parent state that defines the schoolyears route and its views. It also resolves the schoolyears data before loading the SchoolyearsController: .state('schoolyears', { url: '/schoolyears', views: { ...

Switching the active className in React and Next.js based on selection status

My goal is to dynamically change the className of each Card component when clicked on. When one Card is selected, the others should revert back to their default className. This is my UserBookingData component: const UserBookingData = ({ bookings }: any) = ...

What could be the reason behind the varying outcomes browsers provide for the JavaScript expression new Date(-105998400000)?

When I use ASP.NET MVC 3 with the default Json serializer, I notice that dates from my JsonResults come back in the format /Date(-105998400000)/. To handle this, I extract the number and create a new Date object with this value. However, I am experiencing ...

Exploring the capabilities of referencing MongoDB documents with the populate method in Node.js

I have been working on referencing in Node.js using the populate method, but I am unsure about how exactly it works. In my code, I am creating a reference to the user collection from my child collection. I have two collections - one for children and anothe ...

The JQuery datepicker fails to display the current date

I am experiencing an issue with the datepicker on my webpage. While it is working correctly, the default date being displayed is '01/01/2001' instead of '11/23/2012', as I intended. Here is the jquery code I am using: $(":inpu ...

Utilizing JavaScript to verify the presence of a div element within dynamically injected HTML code

While working on a website, I have implemented an embed function which involves calling a javascript from my server to inject HTML on another remote server. To ensure that these embeds also benefit from Google ranking, I have included a piece of HTML in t ...

What is the best way to widen each tab so they fill up the entire width of the content block?

As a newcomer to both programming and this website, I've been exploring various codes for creating vertical and horizontal tabs. I have a specific query about this particular example found at https://jsfiddle.net/eu81273/812ehkyf/: My goal is to adju ...

How can I add a character at a precise location while keeping the existing tags intact

Latest Update After further testing, it seems that the code performs well with a faux spacer, but runs into issues with the regex. The following scenarios work correctly: Selecting words above or below the a tag Selecting just one line directly above or ...

What could be causing the html.fromstring function to malfunction in my code?

In my current code, I am utilizing html.fromstring: import html import sys url = "https://tokcount.com/?user=totallynotbenandoliver" response = requests.get(url) try: response = requests.get(url) except: print ('Sorry bad url') s ...

Exploring the process of logging large objects in Node.js 11 using the console command

When working with Node.js 11, I've noticed that when I use console.log to output a large object, it sometimes throws a stack trace error or logs the full object including all of its inheritance. In my Jest tests, I encountered an error when trying to ...

Delivering a static Angular app through an Express Server

In my current setup, I have an Angular app being served as static content in an Express Server. When Express serves static files, it automatically adds an ETag to them. Subsequent requests will then check if the ETag matches before sending the files agai ...

Are asynchronous promises thenable for chaining?

Can someone explain to me how asynchronous chaining works with thenable? I am new to using promises in Node.js and I am a bit confused about the concept. In the code example provided below, it seems like the promise returned from the previous Promise.the ...

Creating a dynamic object with JavaScript using two arrays

Can anyone assist me in constructing an array of objects by combining data from two different arrays? const parent =[ { Id: 1, Cate: 'Accommodation', p_id: null }, { Id: 4, Cate: 'National Travel', p_id: null } ] const child =[ { ...

Getting data before the Router is loaded following authentication with Angular 2+ - A comprehensive guide

I'm hoping this isn't a repeat. Within my login component, I have a feature that allows users to log in, which calls a service and retrieves a Token. Upon successful login, the token is saved to localStorage. Subsequently, I use the getUserData ...

What is the best way to ensure the dropdown box in a Bootstrap navbar automatically adjusts its width to fit within the

When I click on the dropdown menu, the box extends beyond the width of the page and a horizontal scroll appears. How can I make the dropdown box automatically adjust its position if it reaches the edge of the page without needing a scroll (as shown in the ...

Is there a way to submit a form without displaying the values in the URL?

For quite some time, I've been attempting to solve this issue, but none of the answers I've found seem to apply to my specific situation. The front end of my webapp consists of a very simple HTML page. It features two forms - one for creating an ...

Which is better for handling events - jQuery delegation or function method?

Which approach is quicker and has broader browser support? 1. Utilizing a JavaScript function such as: function updateText(newtext) { $('div#id').text(newtext); } and incorporating it into an element's onclick event: <button onc ...

Retrieve the ID value of the paragraph that was clicked on using the right-click function

If I have text with this specific html markup: <p id="myId">Some text <span>some other text</span></p> Is there a way to retrieve the value of the id upon right-clicking on any part of the paragraph? Update: I'm simply pass ...