Vluis Vluis - 3 years ago 152
AngularJS Question

AngularJS / CSS - show/hide element on mouseover

This code only applies the

.current
class to my span, but the span is not hidden in the first place. I want it to be hidden, then on
hover + ctrl
- displayed, and on
mouseleave
- hidden again. How can I achieve that?

html:

<div class="portlet-titlebar" ng-mouseover="hoverIn()">
<span class="remove" class="hidden">
<clr-icon shape="times-circle" class="is-warning" size="16"></clr-icon>
</span>
</div>


directive:

scope.hoverIn = function(){
var res = document.getElementsByClassName('remove');
var result = angular.element(res);
if(event.ctrlKey){
result.removeClass('hidden');
result.addClass('current');
}
}


less:

.hidden{
display:none;
}

.current{
display: block;
border: 1px solid red;
}

Answer Source

Based on the question, this is my solution, on hovering the ng-mouseover($event) will track the hovering, then a if condition will check if ctrl key is pressed, you need to pass the $event through the function. Then on mouse leave you need the ng-mouseleave directive to detect this and call another function to hide it again.

Now coming to your question, if you want the span to be intially hidden then just add the class hidden to the span initially.

I have added the below CSS class so that the container does not become very small, to facilitate easy hovering.

.portlet-titlebar {
  border: 1px solid black;
  min-height: 50px;
}

Here is a working demo, let me know if there are any issues, we can sort it out.


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

app.controller('MyController', function MyController($scope) {

}).directive('clrIcon', function() {
  return {
    restrict: "E",
    link: function(scope, element, attrs) {
      scope.hoverIn = function(event) {
        if (event.ctrlKey) {
          angular.element(element[0].parentNode).removeClass('hidden');
          angular.element(element[0].parentNode).addClass('current');
        }
      }
      scope.hoverOut = function() {
        angular.element(element[0].parentNode).removeClass('current');
        angular.element(element[0].parentNode).addClass('hidden');
      }
    }
  }
})
.hidden {
  display: none;
}

.current {
  display: block !important;
  border: 1px solid red;
}

.portlet-titlebar {
  border: 1px solid black;
  min-height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller='MyController' ng-app="myApp">
  <div class="portlet-titlebar" ng-mouseover="hoverIn($event)" ng-mouseleave="hoverOut()">
    <span class="remove hidden">
          <clr-icon shape="times-circle" class="is-warning" size="16">asdf</clr-icon>
    </span>
  </div>
</div>

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