Press on a specific div to automatically close another div nearby

var app = angular.module('app', []);
app.controller('RedCtrl', function($scope) { 
  $scope.OpenRed = function() {
    $scope.userRed = !$scope.userRed;
  }
  $scope.HideRed = function() {
    $scope.userRed = false;
   }  
});
app.directive('hideRed', function($document) {
  return {
    restrict: 'A',
    link: function(scope, elem, attr, ctrl) {
      elem.bind('click', function(e) {
        e.stopPropagation();
       })
      $document.bind('click', function() {
       scope.$apply(attr.hideRed);
      })
    }
   }
});

app.controller('BlueCtrl', function($scope) { 
  $scope.OpenBlue = function() {
    $scope.userBlue = !$scope.userBlue;
  };
  $scope.HideBlue = function() {
    $scope.userBlue = false;
  };  
});
app.directive('hideBlue', function($document) {
  return {
    restrict: 'A',
    link: function(scope, elem, attr, ctrl) {
      elem.bind('click', function(e) {
      e.stopPropagation();
    });
       $document.bind('click', function() {
        scope.$apply(attr.hideBlue);
     })
    }
  }
});
body {
  position: relative;
   display:flex;
}
a
{
margin-right:20px;
}
.loginBox 
{
  z-index: 10;
  background: red;
  width: 100px;
  height: 80px;
  position: absolute;
}

.fontSize 
{
  font-size: 30px;
}
.loginBoxBlue
{
  z-index: 10;
  background: blue;
  width: 100px;
  height: 80px;
  position: absolute;
  display:flex;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="app">
  <body>
    <div ng-controller="RedCtrl">
      <a href="#" ng-click="OpenRed()" hide-red="HideRed()"  ng-class="{'fontSize': userRed}">Show Red</a>
      <div hide-red="HideRed()" class="loginBox" ng-show="userRed"></div>
    </div>
    <div ng-controller="BlueCtrl">
      <a href="#" ng-click="OpenBlue()" hide-blue="HideBlue()"  ng-class="{'fontSize': userBlue}">Show Blue</a>
      <div hide-blue="HideBlue()" class="loginBoxBlue" ng-show="userBlue"></div>
    </div>
  </body>
</html>

Hey there! By clicking on Show Red or Show Blue, you can show red and blue boxes respectively. These boxes can be closed by clicking outside of them or clicking on the text again. If both texts are clicked, both divs will be shown.

Now, the question is, how can we make it so that when you click on Show Red, the blue box is hidden and vice versa? Essentially, we want only one box to be visible at a time.

Answer №1

Is there a specific reason for implementing two controllers in your code? It seems to add unnecessary complexity to your app. Consider using just one controller, such as RedCtrl, to simplify communication between variables.

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

app.controller('RedCtrl', function($scope) {
  $scope.OpenRed = function() {
    $scope.userRed = !$scope.userRed;
    $scope.userBlue = false;
  }
  $scope.HideRed = function() {
    $scope.userRed = false;
  }
  $scope.OpenBlue = function() {
    $scope.userBlue = !$scope.userBlue;
    $scope.userRed = false;
  };
  $scope.HideBlue = function() {
    $scope.userBlue = false;
  };
});

app.directive('hideRed', function($document) {
  return {
    restrict: 'A',
    link: function(scope, elem, attr, ctrl) {
      elem.bind('click', function(e) {
        e.stopPropagation();
      })
      $document.bind('click', function() {
        scope.$apply(attr.hideRed);
      })
    }
  }
});

app.directive('hideBlue', function($document) {
  return {
    restrict: 'A',
    link: function(scope, elem, attr, ctrl) {
      elem.bind('click', function(e) {
        e.stopPropagation();
      });
      $document.bind('click', function() {
        scope.$apply(attr.hideBlue);
      })
    }
  }
});
body {
  position: relative;
  display: flex;
}

a {
  margin-right: 20px;
}

.loginBox {
  z-index: 10;
  background: red;
  width: 100px;
  height: 80px;
  position: absolute;
}

.fontSize {
  font-size: 30px;
}

.loginBoxBlue {
  z-index: 10;
  background: blue;
  width: 100px;
  height: 80px;
  position: absolute;
  display: flex;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="app">

<body ng-controller="RedCtrl">
  <div>
    <a href="#" ng-click="OpenRed()" hide-red="HideRed()" ng-class="{'fontSize': userRed}">Show Red</a>
    <div hide-red="HideRed()" class="loginBox" ng-show="userRed"></div>
  </div>
  <div>
    <a href="#" ng-click="OpenBlue()" hide-blue="HideBlue()" ng-class="{'fontSize': userBlue}">Show Blue</a>
    <div hide-blue="HideBlue()" class="loginBoxBlue" ng-show="userBlue"></div>
  </div>
</body>

</html>

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

Tips for handling an InvalidSelectorException in Selenium when logging into a website

I've been working on automating website logins using Selenium and here is the code I have written: from selenium import webdriver driver = webdriver.Chrome() driver.get("https://abcde.com") assert "xxx" in driver.title user = driver.find_element_by ...

Experience the power of Kendo UI Date Picker combined with AngularJS. When the datepicker is initialized, it starts

Check out my code snippet below: When the datepicker loads initially, it appears empty. However, if you remove ng-model from the directive template, the datepicker displays its initial value correctly. Yet, changing the selected date does not mark the fo ...

Utilizing Angular to Refine Arrays

I am currently working on filtering an array called courses by a property known as FacilityId. In my controller, I have set up $http calls that return responses for the following: function holeIndexController($scope, $http) { $scope.facilities = []; ...

Utilizing React Native to Query, Filter, and Save a Single Document Field Value from Firestore Database into a Variable/Constant

My current task involves setting up a Firebase Firestore Database in order to filter it based on a specific field value within a document. The collection I am working with is named "PRD" and consists of thousands of documents, each sharing the same set of ...

Creating a custom vehicle with interactive controls, including buttons to accelerate and steer using HTML, JavaScript, and jQuery

Here is the task for my assignment: Your challenge is to replicate an animation in Canvas using any object of your choice, such as a truck, car, cycle, or airplane. Sample codes are available on Blackboard for reference, and hints have been provided duri ...

Regular expression for eliminating the local path from a website address

I am facing a scenario where different formats of relative paths can occur, such as: const URL1 = "./hello-world" const URL2 = "../hello-world" const URL3 = "../../hello-world" const URL4 = "../../../hello-world" con ...

Is there a way to sort a table using a dropdown menu selection as a filter?

I am currently working on a project that involves a table with three columns, which are typically populated from a SQL database. My goal is to filter the third column based on the value selected from a dropdown menu. I came across a helpful tutorial on W3 ...

Locate the Next Element Based on its Tag Name

CSS <div> <a href=''> Red </a> </div> <div> <div> <a href=''> Blue </a> </div> </div> <a href=''>Green</a> JavaScript $(document).ready(f ...

Is there a way for me to verify if I have already made an AJAX data request

I have an image gallery with thumbnails. When a user clicks on a thumbnail, an ajax request is fired. I want to prevent the ajax request from firing again if the user clicks on the same thumbnail and instead use the existing data. $.getJSON(url, function( ...

Check for the presence of a horizontal scrollbar on the page for both computer and mobile devices

Is there a way to determine if a web page has a horizontal scrollbar using jQuery or pure JavaScript? I need this information to dynamically change the css of another element. I initially tried function isHorizontalScrollbarEnabled() { return $(docum ...

Spinning a point around the center on a canvas

My friend and I are in the process of creating a game, and we've reached the point where we want to implement a radar system. While we have successfully designed a basic radar that displays everything in the correct positions, our next challenge is to ...

Reference now inactive in an array object no longer exhibiting reactivity

After implementing the following code successfully, we noticed that changing the language updates the text correctly thanks to the ref: const mainNavigationLinks = computed(() => [ { label: context.root.$t('navigationMenu.home') }, { labe ...

How can I append a hash to a URL using JavaScript without causing the page to scroll?

Is it possible to add a hash to the URL without scrolling the page using JavaScript? I navigate to the page I scroll down I click on a link that adds a hash (for example: http://www.example.com/#test) The page should not scroll back to the top. What is ...

Exploring techniques to query a Mongoose/Express array generated from a select multiple option

I am currently working on a search form that utilizes the select multiple attribute. Below is the code snippet for the form. <form action="/search" method="get"> <select name="q" multiple> <optgroup label="Fruit"> <option ...

Ways to dynamically update template URL in AngularJS during runtime

In my code located in app.js var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope) { // Fetching data from API calls var empDept = GetEmployeeData(); var marFin = GetFinanceData(); var x = ...

Looking for a solution to a problem with your vertical CSS/jQuery dropdown menu

My web app features a vertical CSS menu that is working correctly except for one minor issue. When I mouse out on all elements with the class a.menutoggle, the last dropdown menu remains open. I am struggling to find a solution to hide it. Can someone plea ...

The styling of the CSS is tailored to various breakpoints

source: Display helpers How can I dynamically change CSS styles based on the current breakpoint size? For example, can I set different sizes, positions, and colors for elements when the window is on xs compared to md or other breakpoints? ...

JavaScript failing to accurately measure the length

Currently experiencing a Javascript issue where the length of an element is not displayed correctly when using .length, even though it shows up in Chrome console. Here is what it looks like in Chrome console <html xmlns="http://www.w3.o ...

Display a specific element only if another element exceeds a specified height

A snippet of HTML code is given below: <span class="day-number">{{day-number}}</span> <div class="event-box"> <div class="event-container"> </div> <div class="more-events">more ...</div> </div> The .e ...

Trigger callback function when user selects a date on the calendar using Material UI X Date Picker

I am currently utilizing the DateTimePicker component in material ui, version 5. I am looking for a way to intercept the callback triggered when a user clicks on a day in the calendar selector: https://i.stack.imgur.com/0Tlogm.png Although the DateTimePi ...