Tips on rearranging the location of a div element within a directive

I have created a custom directive that displays two divs, Div1 and Div2, with a splitter in the middle: Splitter Image

Now, I am looking for a way to swap the positions of these two divs dynamically using an Angular directive. I thought about using ng-switch, but it seems like there might be better ways to achieve this without relying on jQuery. Additionally, I would like to incorporate some animations during the swapping process to enhance the user experience.

You can check out a demo of the current implementation here: Demo Fiddle

Sample Code:

 angular.module("KendoDemos", [ "kendo.directives" ])
.controller("MyCtrl", function($scope){
  $scope.orientation = "horizontal";
  $scope.hello = "Hello from Controller!";
})

.directive('myDirective',function(){
    return{
    template:'<div kendo-splitter><div>1st pane</div><div>2nd pane</div></div>'
}
})

UPDATE: I have implemented a simple toggle functionality to switch between the two divs. However, it involves duplicating the view code for each scenario. Does anyone have suggestions on how to improve this approach?

<button ng-click='toggle = !toggle'>Switch View</button>
<div ng-if="toggle">
    <div>
        Left side 
    </div>
    <div>
        right side
    </div>
</div>

<div ng-if="!toggle">
    <div>
        right side 
    </div>
    <div>
        left side
    </div>
</div>

If you have any ideas or suggestions on how to optimize the code and achieve the desired functionality in a more efficient way, please let me know. Thanks!

Answer №1

To arrange the elements in a specific order, one approach is to utilize flexbox and set an order for each element. Another option is to use Angular to toggle a class on the container. While alternative methods like floats or other CSS techniques can also be used to manipulate the order, it is recommended to leverage CSS for this purpose.

Check out the demo below: http://codepen.io/jessegavin/pen/ZbWeNV

Template

<div ng-app="demo">

  <columns></columns>

  <script type="text/ng-template" id="columns.html">
    <div>
      <div class="columns">
        <div class="column column-one">Col 1</div>
        <div class="column column-two">Col 2</div>
      </div>
      <button ng-click="swap()">Swap</button>
    </div>
  </script>

</div>

CSS

.columns {
  display: flex;
}
.column-one { order: 1; }
.column-two { order: 2; }

.swapped {
  .column-one { order: 2; }
  .column-two { order: 1; }
}

.column {
  width: 50%;
  height: 200px;
  border: solid 1px red;
}

Directive

angular.module("demo", [])
  .directive("columns", function() {

    return {
      templateUrl: "columns.html",
      link: function(scope, element, attrs) {

        scope.swap = function() {
          element.toggleClass("swapped");
        }

      }
    }
  })

Answer №2

One option is to implement angular's ui sortable feature for this task. It allows you to effortlessly drag and rearrange items on the screen. Furthermore, you can add specific handlers to control which parts of the div are draggable.

Answer №3

There are various methods to achieve this task, some more efficient than others.

If there are no external factors impacting the resolution of this issue and switching positions is a straightforward process, you can designate the container div (the one containing both smaller divs) as a flexbox with:

display:flex

and

flex-flow: row nowrap, 

Then, during hover, scroll, toggle, or any other action, modify flex-flow to flex-flow: row-reverse nowrap.

If you desire an animation effect, you can include transition: .5 on the container div.

I apologize if my explanation is unclear :(

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

Error: Material-UI prop type validation failed. Please specify either children, image, src, or component prop for CardMedia component. This error occurred at

I encountered an issue while trying to utilize the CardMedia component from Material-ui. The error message received was 'Failed prop type: Material-UI: Either children, image, src, or component prop must be specified. at CardMedia'. I attempted v ...

The case of the elusive Firefox overflow: hidden glitch

Recently, I integrated an image slider into my web design and it displayed perfectly on Internet Explorer and Chrome. However, when viewed on Firefox, I encountered a strange problem where the images in the slider were being pushed towards the right side o ...

The 'SVGResize' or 'onresize' property is not available on the 'SVGProps<SVGSVGElement>' type

Using React with SVG I'm facing an issue with handling the resizing event of an svg element. I have looked into using the SVGResize and onresize events, but encountered compilation errors when trying to implement them: const msg1 = (e: any) => co ...

Angular Reactive Forms may not properly update other inputs when binding a control to multiple inputs

While working with reactive forms, I encountered an issue where accessing the same control in multiple inputs seemed to result in one-way data binding (input-to-model). If I make edits in one input, it updates the model correctly but does not refresh the o ...

Using CSS and JavaScript to hide a div element

In my one-page website, I have a fixed side navigation bar within a div that is initially hidden using the display:none property. Is there a way to make this side nav appear when the user scrolls to a specific section of the page, like when reaching the # ...

Having trouble running Protractor with the Angular Seed Basic app in AngularJS?

After cloning the angular-seed to my basic setup, I attempted to run protactor using the command below and encountered an error: npm run protractor npm ERR! node v5.0.0 npm ERR! npm v2.10.1 npm ERR! code ELIFECYCLE npm ERR! [email protected] protr ...

React.js encountered an error: Unexpected "<" token

My journey with react.js has just begun. I am currently using Webstorm for development. I have encountered an error that I am struggling to solve. It seems like React is not being recognized even after trying to install various npm react packages. Synta ...

Enhancing an existing node by adding a new node with jQuery functionalities at the same time

Is it possible to append a node to a parent node while also manipulating the node being added? I initially believed this could be done in one step: //I though this was possible: $('#master').after('<div id="test" style="border:solid 1px ...

What could be the reason behind PHP not picking up my AJAX request string?

I'm encountering an issue where PHP is not recognizing my request string as defined. When I include $_GET['ask'] in my PHP file, it triggers the error message - Notice: Undefined index: ask. Interestingly, when I manually input the query in ...

Crockford's system for safeguarded entities

Despite the abundance of questions and resources related to "Javascript: The Good Parts," I am struggling to comprehend a specific sentence in the book. On pages 41-42, the author defines the serial_maker function as follows: var serial_maker = function ( ...

Remove an object based on its unique identifier with the help of mongoose

I am working on developing an API to delete a document in MongoDB using Mongoose. Below is the route I have created: router .route("/tasks") .delete('/:id', function (res, err) { taskSchema.findByIdAndRemove(req.params.id, (err, ...

The background size cover feature is not functioning properly on mobile devices, especially on longer pages

In my Next.js project, I am encountering an issue with the background image not displaying on longer pages when viewed on a Google Pixel 3a device. Here is how it looks on shorter pages that do not exceed the viewport height: https://i.sstatic.net/jJBTy.pn ...

Struggling to break free from the confines of an overflow-hidden container in swiperjs due to

I have a slider that utilizes swiperjs and I want to incorporate a dropdown menu within each swiper-slide. However, I've encountered an issue where the dropdown menu is unable to escape the root container due to the positioning constraints. For a dem ...

Prevent Border Around Images within a Child DIV

Currently, I am in the process of designing a Tumblr theme and facing the challenge of making my pages visually appealing. One particular issue that is causing me trouble is my desire to have images on individual pages bordered in green with a maximum wid ...

Solving the error message: "Objects cannot be used as a React child (found: object with keys {})"

I am currently in the process of developing a full stack website that utilizes React, Express, Sequelize, and mySQL. The site is operational with features like registration and login implemented successfully. However, I encountered an issue when trying to ...

What could be causing the JavaScript array to not successfully transfer to PHP?

Despite searching for solutions, I am unable to get the desired outcome. When I check my JavaScript array in the console, it appears like this: [] 0:Object stock:27 createdtime:"2016-04-08T04:00:00+0000" id:"693852404037393999" units:438 ...

Retrieve no data from Firebase using Cloud Functions

I am a beginner with Google Firebase and Cloud Functions, and I recently attempted a basic "hello world" program: Established a connection to Cloud Firestore [beta], which contains over 100,000 records. Retrieved the top record from the database. Below ...

Identifying the presence of node.js on your system

After installing node.js, I found myself at a loss on how to run applications. Despite the lack of instructions, I was determined to test if it was working by executing a script named hello.js: console.log('hello world'); I couldn't help b ...

Common Error for Novice HTML/CSS Learners

I am currently enrolled in an introductory web design course on Treehouse, and I have encountered a problem with centering a class in HTML using CSS. Despite following the instructions closely, my code is not displaying correctly. Can someone please review ...

How can I change an array from OData into JSON format?

I've been working on finding a solution to properly handle an OData response in JavaScript. The issue I am facing is that the response comes back formatted as an array rather than JSON, preventing me from using JSON.parse(mydata) with the current data ...