Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular.js: Set CSS when Input is on Focus

Tags:

angularjs

Does someone knows how to get the following working:

If an user clicks inside "name" - Set CSS Class to XYZ on DIV ?

<div ng-class="???">Enter your Name here</div>

<input type="text" ng-model="user.name" required id="name"/>

Version: AngularJS v1.0.8

like image 815
opHASnoNAME Avatar asked Oct 09 '13 16:10

opHASnoNAME


People also ask

How do you set an element focus in CSS?

The CSS :focus psuedo-class selects an element in its focus state. This happens when you click on an element or select it with the tab button. :focus comes after the name of the element you want to select. You may want to apply a style to an element only when it has focus on the web page.

How do you know if an element is in focus angular?

hasFocus() : whether the document or any element inside the document has focus. document. activeElement : Property containing which element currently has focus.


1 Answers

If you're using Angular 1.2.x, see ng-focus and ng-blur:

<div ng-class="{xyz: focused}">Enter your name here</div>
<input type="text" ng-model="user.name" ng-init="focused = false" ng-focus="focused = true" ng-blur="focused = false" id="name" required>

If you're using a 1.0.x version, nothing is stopping you from defining your own focus and blur directives based on Angular 1.2.x's:

/*
 * A directive that allows creation of custom onclick handlers that are defined as angular
 * expressions and are compiled and executed within the current scope.
 *
 * Events that are handled via these handler are always configured not to propagate further.
 */
var ngEventDirectives = {};
forEach(
  'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  function(name) {
    var directiveName = directiveNormalize('ng-' + name);
    ngEventDirectives[directiveName] = ['$parse', function($parse) {
      return function(scope, element, attr) {
        var fn = $parse(attr[directiveName]);
        element.on(lowercase(name), function(event) {
          scope.$apply(function() {
            fn(scope, {$event:event});
          });
        });
      };
    }];
  }
);
like image 75
André Dion Avatar answered Oct 19 '22 03:10

André Dion