What is the best way to move two divs left or right with jquery?

As a beginner in coding, I am experimenting with JQuery to achieve a specific functionality. I have two Divs where clicking on the first one displays content, and clicking on the second one hides the content of the first Div and shows its content instead (Toggling). However, my goal is to enhance this functionality by having the second Div slide to the right when clicking on the first Div, creating a drawer-like effect, and vice versa. I have included images to illustrate my idea further.

The default state for both contents is hidden. Despite trying various approaches, I am struggling to combine these two functionalities seamlessly.

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Test</title>
    <script
      src="https://code.jquery.com/jquery-3.5.1.js"
      integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
      crossorigin="anonymous"
    ></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>
  <body>
    <div id="box-container">
      <div id="div1">
        <h1>Title one</h1>
        <p>
          Lorem ipsum dolor sit amet consectetur, adipisicing elit. Inventore
          quidem ex tenetur ipsum dolore repudiandae molestiae mollitia! Dolore
          numquam.
        </p>
      </div>
      <div id="div2">
        <h1>Title two</h1>
        <p>
          Lorem ipsum dolor sit amet consectetur, adipisicing elit. Inventore
          quidem ex tenetur ipsum dolore repudiandae molestiae mollitia! Dolore
          numquam.
        </p>
      </div>
    </div>
    <div id="contentDiv1">
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Nulla voluptatem
      veritatis assumenda. Obcaecati veniam quo impedit tempora pariatur maiores
      ipsa voluptates commodi esse eveniet! Nihil corrupti illum at accusantium
      sit? Lorem ipsum dolor sit amet consectetur adipisicing elit. Ut veritatis
      et molestias? Reprehenderit distinctio sint provident ratione dolorem
      veritatis sapiente, fuga amet obcaecati. Laboriosam rerum consectetur nemo
      magnam saepe mollitia. Lorem ipsum dolor sit amet consectetur adipisicing
      elit. Excepturi sit perferendis earum debitis corrupti dolore commodi
      minima consectetur veniam itaque inventore et pariatur sapiente, maxime
      quis, in nulla, eos molestias! Lorem ipsum dolor sit amet consectetur
      adipisicing elit. Quasi, incidunt repudiandae perferendis ea praesentium
      blanditiis, voluptate accusantium, repellat molestiae quisquam eveniet
      earum officia sed assumenda maxime officiis sequi laboriosam! Tempore.
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Alias modi hic
      officia iste optio in delectus veniam obcaecati reprehenderit, voluptate
      ipsum! Incidunt ducimus animi, id quae blanditiis provident dignissimos
      harum?
    </div>
    <div id="contentDiv2">
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Nulla voluptatem
      veritatis assumenda. Obcaecati veniam quo impedit tempora pariatur maiores
      ipsa voluptates commodi esse eveniet! Nihil corrupti illum at accusantium
      sit? Lorem ipsum dolor sit amet consectetur adipisicing elit. Ut veritatis
      et molestias? Reprehenderit distinctio sint provident ratione dolorem
      veritatis sapiente, fuga amet obcaecati. Laboriosam rerum consectetur nemo
      magnam saepe mollitia. Lorem ipsum dolor sit amet consectetur adipisicing
      elit. Excepturi sit perferendis earum debitis corrupti dolore commodi
      minima consectetur veniam itaque inventore et pariatur sapiente, maxime
      quis, in nulla, eos molestias! Lorem ipsum dolor sit amet consectetur,
      adipisicing elit. Quasi, incidunt repudiandae perferendis ea praesentium
      blanditiis, voluptate accusantium, repellat molestiae quisquam eveniet
      earum officia sed assumenda maxime officiis sequi laboriosam! Tempore.
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Alias modi hic
      officia iste optio in delectus veniam obcaecati reprehenderit, voluptate
      ipsum! Incidunt ducimus animi, id quae blanditiis provident dignissimos
      harum?
    </div>
  </body>
</html>

CSS

body {
  display: inline-block;
  margin: 100px 100px 25px 100px;
  text-align: center;
}
#box-container {
  height: 300px;
  display: flex;
}
#div1 {
  background: linear-gradient(90deg, #f57350, #fa8282);
  width: 50%;
  height: 50%;
  cursor: pointer;
}

#div2 {
  background: linear-gradient(90deg, #a42e5a, #f57350);
  width: 50%;
  height: 50%;
  cursor: pointer;
}
#contentDiv1,
#contetnDiv2 {
  margin: 25px;
}

JQuery

jQuery(document).ready(function($){
    $('#contentDiv1').hide();
    $('#contentDiv2').hide();
    
    $('#div1').on('click', function(){
        $('#contentDiv1').slideToggle();
        $('#contentDiv2').hide();       
    });
   
    $('#div2').on('click', function(){
        $('#contentDiv2').slideToggle();
        $('#contentDiv1').hide();
    });
});

attached image

Answer №1

There are multiple ways to solve this problem, and the following method is one that I particularly enjoy using:

$('.tabs .tab').on('click', function () {
  if ($(this).hasClass('active')) {
    $(this).removeClass('active')
    .closest('.tabs').removeClass('active1 active2');
    $('.content').hide();
  } else {
    let i = $(this).index() + 1;
    $(this)
        .addClass('active')
        .siblings('.tab').removeClass('active')
        .closest('.tabs').removeClass('active1 active2')
        .addClass('active' + i);
    
    $('.content').hide();    
    $('.content' + i).fadeIn();
  }
});
.tabs,
.tabs .tab,
.tabs .content {
    border: 1px solid #000;
    border-collapse: collapse;
    box-sizing: border-box;
}
.tabs {
    display: flex;
    flex-wrap: wrap;
    text-align: center;
    position: relative;
}
.tabs.active1 {
    padding-left: 0;
    padding-right: 65px;
}
.tabs.active2 {
    padding-left: 65px;
    padding-right: 0;
}
.tabs .tab {
    padding: 15px;
    cursor: pointer;
    min-width: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
}
.tabs.active1 .tab,
.tabs.active2 .tab {
    min-width: 100%;
    width: 100%;
}
.tabs .content {
    padding: 15px;
    min-width: 100%;
    display: none;
}
.tabs.active1 .tab1:not(.active),
.tabs.active2 .tab1:not(.active){
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    min-width: 65px;
    width: 65px;
}
.tabs.active1 .tab2:not(.active),
.tabs.active2 .tab2:not(.active) {
    position: absolute;
    right: 0;
    top: 0;
    bottom: 0;
    min-width: 65px;
    width: 65px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tabs">
    <div class="tab tab1">div1</div>    
    <div class="tab tab2">div2</div>
    <div class="content content1">div content1</div>    
    <div class="content content2">div content2</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

Use jQuery to add additional text after an input element with the name "input"

Greetings! Below is an example of the code I am working with: <input name="name1" type="text"/> <div class="error"></div> <input name="name2" type="text"/> <div class="error"></div> <input name="name3" type="text"/ ...

Struggling to grasp the syntax, trying to invoke a JavaScript function using an input button

I'm really struggling to grasp the xhtml syntax involved in calling a function with an input button. Despite my efforts to find a clear explanation, this concept still eludes me. Within the snippet of code from my book that I've been referencing ...

Providing a tar.gz file for downloading in a node.js application

I have a tar.gz file stored on a nodejs server and I am trying to make it downloadable from another nodejs application. While I have been successful in downloading txt and jpeg files, I am facing issues with the tar.gz file as it appears empty once downloa ...

Using Jquery to Switch Pages

Recently, I've been experimenting with using hashes to create animated transitions between pages. Interestingly, the first page that loads (the home page) fades in and out seamlessly. However, when I attempt to navigate to another page, specifically t ...

Issues with posting incorrect values to ajaxurl when using jQuery's .each() function

Here is a modified version of pointer code that was originally sourced from this link. The original code was broken in the same way as shown here. I have multiple div elements on my web page that are generated using the given code snippet. Upon checking t ...

Custom validation utilizing bootstrap-validator and an AJAX request returning successful status/OK

I am using the bootstrap-validator plugin (available at ) and I want to display an error message if the ajax request is successful and returns a status of 'ok' (indicating that the customer already exists). How can I modify the code to handle th ...

Tips for aligning uploaded files with img tags

Is there a way to align the img tag with the file upload input without using position:absolute, since it doesn't work well in responsive design? Are there any text-align/align-items/justify-content properties that can help align them? .input-file{ ...

Testing Tools for AJAX Integration

Searching for AJAX testing resources. Are there any no-cost tools out there for conducting AJAX tests? Edit 2: Besides Firebug, are there any other tools available? ;) ...

Is it possible to run concurrent PostgreSQL queries in NodeJS?

I'm unsure why, but the task is supposed to be run in parallel and should only take 2 seconds: const test = async () => { client.query("SELECT pg_sleep(2) FROM test", (err, result) => { console.log("DONE!"); }) client.query("SELECT pg ...

Tips for preserving the state of the Material-UI AutoComplete during component re-renders?

Currently, I am utilizing the Material-UI v4 AutoComplete component along with the renderOption prop in order to display a checkbox item option. The issue arises when the onChange event occurs and updates a hook in the parent component causing a re-rende ...

Guide on developing a CSS countdown timer

I recently came across an article discussing the creation of a CSS countdown timer. Intrigued by the concept, I decided to give it a try myself. However, my implementation seems flawed and the live demo link provided in the article is not working. Can some ...

Confirm that a certain input is correct using jQuery validation

Is there a way to use jQuery validation to check if a user inputs a value greater than or equal to 5 in a form field? If the value is indeed greater than or equal to 5, an error message should be displayed. How can this be implemented? <input type=&apo ...

Creating a tailored regular expression for validating email addresses

Up to this point, I have crafted a regex pattern as Pattern="^(?=.*[a-zA-Z].*)([a-zA-Z0-9._%+-]+@([a-zA-Z0-9-]+[a-zA-Z0-9-]+(\.([a-zA-Z0-9-]+[a-zA-Z0-9-])+)?){1,4})$" that meets the following criteria: Not all characters should be numbers, ...

HTML5 body content and footer area

I'm working on a website with the main content area set to 95% width, but I'm facing an issue - I want the footer to be 100% width even though it's a child of the main content, which limits its width. Is there a way to make the footer overr ...

Radiant Curvature Background Gradient

On my website, I'm trying to replicate the unique background gradient found here. Unlike a basic linear gradient that can be easily repeated as an image to fill any length, this one poses a challenge. Can anyone share a technique or method to help me ...

When Raphael Drag's iPhone met the camera app, it was a disappointing encounter

Check out our web app here. To access the main javascript, click here. If you're looking for relevant functions, they are located at the bottom of visualizer.js and are named "dragger," "move," and "up." A decade ago, I worked as a programmer and r ...

When using HTML5's checkValidity method, it may return a valid result even if

Consider the following scenario: <input pattern="[a-z]"/> If you run the command below without entering any input: document.querySelector('input').checkValidity() You will notice that it actually returns true. This seems counterintuiti ...

Using AJAX in PHP to submit checkbox values in a form without reloading the page

Recently, I delved into learning ajax and found it to be truly amazing and a major time-saver. However, I encountered a roadblock when attempting to send form data without having the page reload. Here is an excerpt of my HTML code. <form id="form ...

Integrating scripts in React Native applications

As I was exploring a third-party library, I came across some documentation detailing how to connect it with a website. However, the code provided includes a script tag and I am working on a React Native application. I'm unsure of how to incorporate th ...

How to disable scrolling for React components with CSS styling

When incorporating a React component into my HTML, I follow this pattern: <html> <body> <div id=app>${appHtml}</div> <script src="/bundle.js"></script> </body> </html> Within my application, th ...