Alter the placement of two bootstrap rows based on the button that is selected

I have a webpage with two bootstrap rows and two buttons positioned at the top of the screen. I want to achieve a functionality where clicking the second button will bring the second row on top of the first row, and vice versa.
Here are my two rows:

<div class="row mothers_day-row mothers_day-row-share">
    <div class="col-xs-12">
           Text
    </div>
</div>

<div class="row mothers_day-row mothers_day-row-create">
    <div class="col-xs-12">
          Text 2
    </div>
</div>

Below is the code for my buttons:

 <button class="regular mothers_day_first_button" id="mothers_day1">First row on top</button>

 <button class="regular mothers_day_second_button" id="mothers_day2">Second row on top</button>

Answer №1

One approach is to use special data-* attributes on buttons to indicate which div should be moved to the top. When a button is clicked, the corresponding div specified in its data-target-div attribute is cloned and then removed from the DOM. The cloned div is then inserted at the beginning of the main div using prepend

$(function(){
  $('button.regular').on('click',function(){
     var $div = $($(this).data('target-div'));
     var clonedDiv = $div.clone();
     $div.remove();
     $('#mainDiv').prepend(clonedDiv);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mainDiv">
<div id="firstDiv" class="row mothers_day-row mothers_day-row-share">
    <div class="col-xs-12">
            Text 1
    </div>
</div>

<div id="secondDiv" class="row mothers_day-row mothers_day-row-create">
    <div class="col-xs-12">
          Text 2
    </div>
</div>
</div>


 <button class="regular mothers_day_first_button" id="mothers_day1" data-target-div="#firstDiv">First row on top</button>

 <button class="regular mothers_day_second_button" id="mothers_day2" data-target-div="#secondDiv">Second row on top</button>

Answer №2

Hey there! Since your question mentioned the topic of Changing position, I wanted to share a solution with you. Please have a look at this demo: https://example.com/demo

HTML Code:

<button class="btn primary-btn" id="btn1">Button 1</button>

 <button class="btn secondary-btn" id="btn2">Button 2</button>

<div class="row row-share">
    <div class="col-xs-12">
           Content 1
    </div>
</div>

<div class="row row-create">
    <div class="col-xs-12">
          Content 2
    </div>
</div>

CSS Styles:

.row-share , .row-create{
    height:100px;
    margin:10px;
    border:1px solid grey;
    width:100px;
    position:relative;
    color:#fff;

}

.row-share {
   background:red;
} 

.row-create {
   background:blue;
} 

jQuery Scripts:

$(document).ready(function(){
    $('#btn2').on('click', function(){
        console.log('Clicked button 2');
        $('.row-share').animate({top: "110px"}); 
        $('.row-create').animate({top: "-110px"});
    });

    $('#btn1').on('click', function(){
        console.log('Clicked button 1');
        $('.row-create').animate({top: "0px"}); 
        $('.row-share').animate({top: "0px"});
    });
});

Answer №3

To easily rearrange elements, you can simply utilize the Element: before() method.

var element1 = document.getElementsByClassName('element')[0]
var element2 = document.getElementsByClassName('element')[1]

element2.before(element1);

Visit this link for more information.

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

Unable to invoke the jQuery datetimepicker function within a personalized directive

I have created a unique time picker directive in AngularJS to display a datetimepicker. app.directive("timePicker", function() { return { restrict: "A", link: function(scope, elem, attrs) { / ...

The class in my CSS is currently impacting all the menu bar items, but I specifically want it to only affect my photo gallery

<div class="gallery"> <a tabindex="1"><img src="images/smile.jpg"></a> <a tabindex="1"><img src="images/smile.jpg"></a> <a tabindex="1"><img src="images/smile.jpg"></a> ...

Pattern for ensuring testability in JavaScript

I have come across two different JavaScript testable patterns, but I am struggling to understand the distinctions between them and which one would be more suitable for my needs. Pattern 1: function MyClass () { this.propertyA = null; this.methodA ...

React Application Issue: Unable to successfully redirect to the homepage upon logging in

Attempting to create a web application with the MERN stack is causing some trouble when trying to redirect users to the home page post-login. Here's how it should ideally function: User inputs login details The server validates these details and gene ...

Trouble with vertical alignment and height in a floating division

After scouring through numerous discussions on Stackoverflow regarding vertical alignment and 100% height issues, we have not found a solution. Some of the topics we explored include: Vertical-align middle not working in CSS How to fill height of a float ...

Creating a Chrome extension that opens multiple tabs using JavaScript

Currently, I am working on a chrome extension that includes several buttons to open different tabs. However, there seems to be an issue where clicking the Seqta button opens the tab three times and clicking the maths book button opens the tab twice. Below, ...

What is the best way to utilize getInitialProps specifically during the building process of a NextJS site?

When I am developing a static site using NextJS, I need the getInitialProps method to run specifically during the build process and not when the client loads the page. During the build step, NextJS executes the getInitialProps method before generating the ...

Passing parameters from the client-side to the code behind using ASP.NET AJAX

I could use some assistance as I am struggling with my code. I am trying to follow a tutorial from here. Here is the code behind: public static string HelloName(string name) { return "hello, " + name; } And here is my jQuery: $('#Name').c ...

What is the reasoning behind the presence of hidden elements on the Google Search Result Page?

While using the debugging feature, I stumbled upon some hidden elements on the page. Can anyone shed some light on why these elements are present with a display attribute of none? The first one on the left is an iframe, followed by multiple text areas. ...

Although XPath works in Chrome, it is not compatible with Selenium

My current task involves finding an element based on its content that includes single quotes. I have successfully achieved this using vanilla JS as shown below: singleQuotes = document.evaluate("//div[contains(text(), \"'quotes'\")]" ...

How to convert DateTime to UTC in TypeScript/JavaScript while preserving the original date and time

Consider the following example: var testDate = new Date("2021-05-17T00:00:00"); // this represents local date and time I am looking to convert this given Date into UTC format without altering the original date and time value. Essentially, 2021-0 ...

Finding it difficult to grasp the concept of asynchronous functions in NodeJS

I've been grappling with this NodeJS challenge for a good 6 hours already. Currently, I'm working with NodeJS along with Express and MongoDB. In my database, there are two collections - Listings and Categories. Each listing is linked to a categ ...

The JavaScript function is returning a value of undefined

I encountered an issue where my Javascript function is returning undefined even though it alerts the correct value within the function itself. I have a setup where I call the function in my 1st controller like this: CustomerService.setName(data.name); A ...

Recreating a JavaScript function in real-time upon updating

My C# code is dynamically constructing a javascript function on my asp.net page: string addresses = "function doAddresses() {" + Environment.NewLine; addresses = addresses + "var hostAddress = new Array();" + Environment.NewLine; ...

The most efficient method for handling a vast amount of data in NodeJS

My database consists of 4 million numbers and I need to quickly check if a specific number exists in it. Example of the database: [177,219,245,309,348,436,...] I initially tried using a MySQL table for this task, but it took a lengthy 1300ms just to chec ...

Javascript dynamically generates CSS animations

I need assistance creating a div with a CSS3 animated timer inside it when a button is clicked. Here is the code I have been working on: http://jsfiddle.net/arcco96/y5nov6rz/1/. Unfortunately, the div is not being created as expected. I believe the code sh ...

Node.js Error: RegEx Pattern Does Not Match

Here is a regex pattern to consider: ^[^-\s][a-zA-Z\sàèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇßØøÅåÆæœ\d!@#$\+%&\'*]{1,20}$ I tested this regex on w ...

What is the process of embedding a string with pug code into a pug file?

How can I interpolate a string with pug formatted code in a pug file? Here is what I have tried: - var text = "i.home.icon" div= text div !{text} div #{text} div ${${text}} div {{text}} div {text} div \#{text} div \{text} div ${text} div # ...

Uncertain about the request path that is being transmitted to my Express server via AJAX

I have a simple Node.js Express server setup My goal is to serve html files by using res.sendFile with this route handler: router.get('/:run_id/:test_num',function(req,res,next){ var runId = req.params.run_id; var testNum = req.params. ...