When the user clicks, position a div directly below another div

Can anyone help me figure out how to center a div underneath another one when a specific div is clicked using programming? I've tried multiple solutions but nothing seems to work. Below is the code snippet that I have written. You can also check out the implementation on JSFiddle here.

<div ng-app>
  <h2>Todo</h2>
  <div ng-controller="TodoCtrl">
    <div class="box" ng-click="do($event)">
        <p> HEY THERE </p>

    </div>
    <div class="box2" ng-show="show">

    </div>
  </div>
</div>

function TodoCtrl($scope) {
    $scope.show = false;

   $scope.do = function(evt) {   
        var $this = $(evt.target); 
        var offset = $this.offset();
        var width = $this.width();
        var height = $this.height();

        var centerX = offset.left;
        var centerY = offset.top + height; 

       $('.box2').css({
            'position': 'absolute',
            'top': centerY,
            'left': centerX 
       });
        $scope.show = !$scope.show;

        console.log(evt);
        console.log(centerX, centerY);
    };
}

Answer №1

Applying position: relative to the .box2 element will provide the desired effect. Additionally, include margin: 0 auto; to center it horizontally.

By using these CSS properties, you can minimize the need for JavaScript code to position the element.

Check out the demo here

function TodoCtrl($scope) {
  $scope.show = false;

  $scope.do = function(evt) {
    $scope.show = !$scope.show;
  };
}
.box {
  top: 10px;
  right: 400px;
  width: 150px;
  height: 150px;
  background: orange;
  color: white;
  z-index: 10;
  margin: 0 auto;
}
.box2 {
  position: relative;
  width: 300px;
  height: 150px;
  background: green;
  opacity: 1;
  z-index: 9;
  margin: 0 auto;
}
.box2.ng-hide-add {
  transition: all linear 5.5s;
}
.box2.ng-hide {
  opacity: 0;
}
.box2 {
  animation: slideDown .5s;
}
@keyframes slideDown {
  0% {
    transform: translateY(-20%);
  }
  100% {
    transform: translateY(0%);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<div ng-app>
  <h2>Todo</h2>

  <div ng-controller="TodoCtrl">
    <div class="box" ng-click="do($event)">
      <p>HEY THERRE</p>
    </div>
    <div class="box2" ng-show="show"></div>
  </div>
</div>

Alternatively, you can simplify your controller with the following approach:

View simplified demo here

.box {
  top: 10px;
  right: 400px;
  width: 150px;
  height: 150px;
  background: orange;
  color: white;
  z-index: 10;
  margin: 0 auto;
}
.box2 {
  position: relative;
  width: 300px;
  height: 150px;
  background: green;
  opacity: 1;
  z-index: 9;
  margin: 0 auto;
}
.box2.ng-hide-add {
  transition: all linear 5.5s;
}
.box2.ng-hide {
  opacity: 0;
}
.box2 {
  animation: slideDown .5s;
}
@keyframes slideDown {
  0% {
    transform: translateY(-20%);
  }
  100% {
    transform: translateY(0%);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<div ng-app>
  <h2>Todo</h2>

  <div>
    <div class="box" ng-init="show=false" ng-click="show=!show">
      <p>HEY THERE</p>
    </div>
    <div class="box2" ng-show="show"></div>
  </div>
</div>

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

Make the div come to life by animating it as its

I'm currently working on a project involving three boxes that change position when clicked. I want to be able to switch the selected box with another box, but I am struggling to add an animation to show the transition between them. I would greatly ap ...

Vue messaging application fails to display data upon mounting

Recently, I've been experimenting with different Vue chat libraries and encountered this interesting piece of code: <template> <p>{{ this.users[0] }}</p> </template> <script> export default { data() { return ...

The jquery function will only run on the second click of the button, not the first one

I am struggling to create a JavaScript function that hides divs after clicking a button. The problem is, it only works after the second click, nothing happens on the first one. There are three buttons: #1, #2, and a button with the id #hide_ico. When I cl ...

Extracting information from JSON and presenting it in a structured table format

I've hit a wall with this JavaScript issue on my website. I'm trying to convert API JSON data into a table, and it's working fine when the data is on separate lines. However, when I introduce nested arrays in the JSON data, everything ends u ...

What is the process for transferring a JSON data object to the server with JavaScript XMLHttpRequest?

When I attempt to send an XMLHttpRequest to a PHP server, I am encountering difficulties in getting the $_POST or $_REQUEST object to be filled with the data I am sending using JavaScript: var r = new XMLHttpRequest; r.open("POST", "http://url.com", true ...

Interested in retrieving the dynamically changing value of LocalStorage

Hopefully I can articulate my issue clearly. I am implementing a feature where CSS themes change upon button clicks. When a specific theme button is clicked, the corresponding classname is saved to LocalStorage. However, since the key and value in LocalSt ...

Manipulating and Parsing HTML files locally using Node.js

Hey there! I have a bit of an odd question that might be on the basic side. I'm diving into web development and front-end work, so I'm still fairly new to it all. The Scenario To give you some background, my experience with JS is mainly from usi ...

What is the best way to create a loop with JSON data?

My challenge is to showcase json data using a loop. I have received the following results, but I am unsure of how to display them with a loop. [ {"latitude":"23.046100780353495","longitude":"72.56860542227514"}, {"latitude":"23.088427701737665"," ...

When using expressjs and typescript, you may encounter an error stating that the type 'typeof <express.Router>' cannot be assigned to the parameter type 'RequestHandlerParams'

Working on my project using expressjs with the latest typescript definition file and typescript 2.3.4 from https://github.com/DefinitelyTyped/DefinitelyTyped. I've set up a router and want to access it from a subpath as per the official 4.x documentat ...

Creating a POST Endpoint in Express JS

Hey there! Can someone help me out with creating a basic login script for an app using Express JS? I've been working on a POST function to handle this task, but unfortunately, when I try to echo back the parameters being passed (testing via Postman), ...

Response from Vimeo's AJAX API

I am having trouble retrieving the AJAX response from Vimeo to extract a thumbnail without using JQuery. Even though I can see the response data in JSON format when I type the response query (http://vimeo.com/api/v2/video/30408418.json) into the browser an ...

Ways to expand the `Array.prototype` from an external library in a Node.js environment

While enjoying my time on hackerrank with pure JavaScript, I decided to steer clear of extra arrays or math libraries, unlike the convenience of using python. My approach is robust, but now I'm considering utilizing sugar.js or underscore. I came acr ...

What are the best strategies for enhancing the performance of the jQuery tag:contains() selector

My goal is to extract all elements from a webpage that contain a specific set of words. For example, if I have an array of random words: words = ["sky", "element", "dry", "smooth", "java", "running", "illness", "lake", "soothing", "cardio", "gymnastic"] ...

Numerous lists conveniently consolidated within a single navigation bar

I am currently exploring the functionality of StumbleUpon's navigation bar by attempting to replicate it. My approach involves using 3 lists within 1, structured like this: <nav role="navigation"> <ul id="rightnav"> & ...

Customize input box type based on JSON data using ng-repeat directive in AngularJS

Looking to implement a dynamic form using angular JS. I can successfully use ng-repeat to iterate through JSON fields and display an input box for each. Now I need to customize the input type based on field data from JSON, whether it's 'input&a ...

Exploring the use of jQuery/JS for parsing and working with JSON

Hi everyone, I need some assistance with displaying data from an array created by a PHP file using JS/jQuery. Currently, I am working on implementing a points system for ZetaBoards which you can check out here. The points will be shown below the user' ...

Tips for preventing the occurrence of numerous instances of braintree.setup in Angular

I am encountering an issue with a Braintree payment form displayed in a modal window: $scope.displayModalBraintree = function () { $scope.modal = 'modal_payment_form.html', $scope.$on('$includeContentLoaded', function () { ...

Dynamic count down using JavaScript or jQuery

I am looking for a way to create a countdown timer that I can adjust the time interval for in my database. Basically, I have a timestamp in my database table that might change, and I want to check it every 30 seconds and update my countdown accordingly. H ...

What is the significance of static in react?

export class NavMenu extends Component { static displayName = NavMenu.name; constructor (props) { super(props); this.toggleNavbar = this.toggleNavbar.bind(this); this.state = { collapsed: true }; } I attempted to research the ...

Can you explain the role of [Yield, Await, In, Return] in EcmaScript syntax?

EcmaScript production rules often include the use of "modifiers" such as: [Yield, Await, In, Return] Here are a couple of examples: ArrayLiteral[Yield, Await]: ... ElementList[Yield, Await]: ... AssignmentExpression[+In, ?Yield, ?Await] I have look ...