feners feners - 1 year ago 165
HTML Question

Changing multiple elements with on mouse hover and Angular

How can I get all the elements within a wrap to change color when mouse hovers on the cube in http://codepen.io/Feners4/pen/KggAwg? Currently, I can only get it to change on a single side the mouse hover on. I want to do this strictly with Angular for learning purposes.

This is my HTML:




<body ng-app="App">
<div class="wrap">
<div class="cube"change-background colorcode=¨#f45642¨>
<div class="front" change-background>AAA</div>
<div class="back" change-background></div>
<div class="top" change-background></div>
<div class="bottom" change-background></div>
<div class="left" change-background></div>
<div class="right" change-background></div>

<div class="wrap2">
<div class="cube2">
<div class="front2" change-background colorcode=¨#f45642¨>AAA</div>
<div class="back2" change-background ></div>
<div class="top2" change-background></div>
<div class="bottom2" change-background></div>
<div class="left2" change-background></div>
<div class="right2" change-background></div>


This is my JS:

angular.module('App', [])
.directive('changeBackground', ['$animate', function($animate) {
return {
restrict: 'EA',
scope: {
colorcode: '@?'
link: function($scope, element, attr) {
element.on('mouseenter', function() {
element.css('background-color', $scope.colorcode);
element.on('mouseleave', function() {
element.css('background-color', '@red');

Answer Source

One way to do this is add your directive to the parent of the cube sides, then inside use .children() to apply your function to each child item. Also you will want to have your class change-color to be general as in have not :foo, otherwise the CSS will still only apply to the hovered element even if they all have the class.


<div class="wrap">
    <div class="cube" change-background colorcode=¨#f45642¨>
        <div class="front" >AAA</div>
        <div class="back" ></div>
        <div class="top" ></div>
        <div class="bottom" ></div>
        <div class="left" ></div>
        <div class="right" ></div>

<div class="wrap2">
    <div class="cube2" change-background>
        <div class="front2"  colorcode=¨#f45642¨>AAA</div>
        <div class="back2"></div>
        <div class="top2"></div>
        <div class="bottom2"></div>
        <div class="left2"></div>
        <div class="right2"></div>


  link: function($scope, element, attr) {
    element.on('mouseenter', function() {
      element.children().css('background-color', $scope.colorcode);
    element.on('mouseleave', function() {
      element.children().css('background-color', '@red');


.change-color {
  color: #fff;
  background-color: #f45642;
  cursor: pointer;

Pen Example

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download