Sliding and stacking div elements using JavaScript

I'm currently working on my website and encountered a slight obstacle. This is how my code looks at the moment. My goal is to position the "About" box beneath the "Home" box, and have the upper box slide down with the description when you click on the "Home" box. Any suggestions on how I can accomplish this?

Below is the code from my JS file:

$(document).ready(function (event) {
    var clicked=false;

    $(".one").on('click', function(){
        if(clicked)
        {
            clicked=false;
            $(".two").css({"top": -40}); //Slides up 40 pixels       
        }
        else
        {
            clicked=true;
            $(".two").css({"top": 0});  //Slides right under "one"      
        }
    });

    var clicked2=false;

    $(".three").on('click', function(){
        if(clicked2)
        {
            clicked2=false;
            $(".four").css({"top": -100}); //Slides up 40 pixels       
        }
        else
        {
            clicked2=true;
            $(".four").css({"top": 0});  //Slides right under "one"      
        }
    });
});

On a completely different note, any tips on how I could make the boxes start from the top of the page and have the box be larger rather than just a small strip of color?

Answer №1

If you're looking for a solution, consider implementing the following CSS code:

.container {
    overflow:hidden;
}
.one {
    position: relative;
    top: 0;
    background-color: #FFC300;
    z-index: 1;
    cursor:pointer;
}
.two {
    position: relative;
    top: -40px;
    background-color: yellow;
    z-index: -1;
    -webkit-transition: top 1s;
    -moz-transition: top 1s;
    -o-transition: top 1s;
    transition: top 1s;
}
.three{
    position: relative;
    top: 0;
    background-color: #E9A1B9;
    z-index: 1;
    cursor:pointer;
}

.four {
    position: relative;
    top: -18px;
    background-color: #02C9C9;
    z-index: -1;
    -webkit-transition: top 1s;
    -moz-transition: top 1s;
    -o-transition: top 1s;
    transition: top 1s;
}

Check out the DEMO HERE

Answer №2

To achieve this effect, I recommend using negative margins along with a simple toggle of the .open class on the .one and .three divs:

$(".one, .three").click(function(){
    $(this).toggleClass('open');
});

Cascading Style Sheets (CSS):

.one, .three {
    margin-top: -30px;
    transition: margin-top 1s;
}
.open {
    margin-top: 0;
}

Check out the jsFiddle demo for more details.

Answer №3

If you want to simplify things, you can use the jQuery toggle() function to handle the task for you. (Note: slideToggle() is another option for a different animation effect)

$(selector).toggle(speed,callback);

The speed parameter in toggle() can be set as "slow", "fast", or specified in milliseconds.

You can also include a callback function that will run after the toggle operation is complete.

HTML

<div class="container">
     <div class="one">Main</div>
     <div class="two" style="display: none">Welcome to my page!</div>

     <div class="three">About</div>
     <div class="four" style="display: none">All about me</div>
</div>

CSS

.one {
    background-color: #FFC300;
    cursor:pointer;
}
.two {
    background-color: yellow;
}
.three{
    background-color: #E9A1B9;
    cursor:pointer;
}
.four {
    background-color: #02C9C9;
}

JavaScript

$(document).ready(function (event) {
  $(".one").on('click', function(){
      $(".two").toggle("slow");     
  });

  $(".three").on('click', function(){
      $(".four").toggle("slow");
  });
});

DEMO:

https://jsfiddle.net/qbuatjrm/4/

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

Create a div element within the parent window of the iFrame

I'm trying to figure out how I can click a button within an iFrame that contains the following code: <td class="id-center"> <div class="bs-example"> <a id="comments" href="comments.php?id=$id" name="commen ...

Delaying event listeners in Angular.js by using setTimeout within a factory or service

In order to delay the first iteration of the broadcast until the controller's $watchCollection is ready, I attempted using setTimeout() but it did not work as expected. Even trying with $timeout yielded the same result. What could be causing this issu ...

Arrange list items in a circular pattern

Is there a way to achieve the desired appearance for my navbar like this link? I have tried rotating the text, but the vertical text ends up too far from the horizontal. Any suggestions? .vertical { float:right; writing-mode:tb-rl;/*IE*/ w ...

The destroy method of Chart.js does not appear to have any impact on the

Hello, I've come across this issue in my react app that I need help with: this.chart = new Chart(node, options); // adding data to the chart ... this.chart.destroy(); this.chart = null; this.chart = new Chart(node, options); // adding data to the cha ...

Jenkins process encounters issues with sed execution

I am currently facing an issue where a script that runs successfully locally encounters difficulties during our Jenkins build process, specifically with the 'sed' command. Below is the code snippet I am using. I have double-checked the file path ...

Populate several input boxes with data derived from a single input field

I am facing an issue with three textboxes in my project. When I type something in the first textbox, the value is sent to state.jsp and displayed using out.println(firsttextboxvalue); on the response ID of the second textbox. However, I want to populate th ...

Is it possible to change the CSS of a parent element using a child element?

My current challenge involves altering the background-color of a parent <td> element, without being able to directly modify the HTML structure. The software system utilized at my workplace strictly relies on SQL queries for data manipulation and gene ...

Transforming into a serialized division

I am working on creating a custom WISYWIG editor that generates a div with specific inner elements. The goal is to design the div (along with its inner structure), serialize it, store it in a database as a string or JSON format, and later insert it into th ...

Making sure that the div elements are stacked vertically once the top div expands in size

I am dealing with a situation where I have two divs that showcase a list of elements for the user to interact with via a search bar. This is followed by a "Done" button to finalize their selection. <div class="dropdown col" id="dropdown-s ...

What's the best way to navigate to a different page using a function in React JS?

Hello there! I'm just starting out with React js and I've been trying to figure out how to navigate to the home page once a user successfully logs in using React. Below is the function I currently have set up, which allows me to redirect to the h ...

Finding the best way to transfer text between DIV elements?

I have a dilemma involving two DIV elements positioned absolutely on the sides of an HTML page, much like this EXAMPLE: <div class="left"> </div> <div class="right"> </div> These are styled using the following CSS: .left{ pos ...

`How can I incorporate personalized animations on Google Map V3 Markers as they are individually dropped on the map?`

This is a basic example of dropping markers one by one on Google Maps V3. I have implemented the drop animation when adding markers to the map. However, I am interested in customizing the drop with a fade animation. Is it possible using JavaScript or any ...

Adjust the width of the list items based on the specified condition

I need assistance with adjusting the width of items in a list. The list includes: <ul> <li>One</li> <li>One-One</li> <li>Two</li> <li>Two-Two</li> </ul> The display should be dyn ...

Navigating the landscape of European law and online payment regulations can be complex, especially when it

Currently, I am in the process of developing a website that integrates Stripe payments. Since it is based in Europe, I will be required to implement SCA 3D Secure authentication. According to the documentation provided by Stripe, it is recommended to handl ...

injecting the value of this.value into an HTML input markup using JavaScript's insertCell function

Having a bit of trouble with a JavaScript function that creates a table and inserts a cell using insertCell(0); In this cell, there's an HTML form input that triggers another function onKeyUp, where I pass in 4 parameters. However, the last parameter ...

What is the best way to incorporate data from a foreach method into a function call within an HTML string?

Having trouble calling a function with data from a foreach loop while generating HTML cards and buttons from an array. The issue seems to be in the renderProducts() method. /// <reference path="coin.ts" /> /// <reference path="prod ...

Interactions between JavaScript Event Listeners and concealed elements in the DOM

I'm in the process of developing a travel reimbursement form for my workplace. We have 4 distinct categories of travel, which led me to come up with a solution involving individual buttons for each category. Upon clicking a button, the corresponding f ...

Calculate a value within a MongoDB field

Hello everyone, I have a document in my collection that looks like this: { Player_Name: Sandeep Nair Player_TotalWeightedPoints: 80 Player_Rank: 23 } I have around 200 similar documents in my collection. The Player_Rank is determined by the total Weighted ...

Use ajax to send an object containing an array to a POST method in MVC

Is there a way to send an object with an array inside using Ajax to a HttpPost method in MVC? I am utilizing @Html.AntiForgeryToken() in my view, so Ajax is necessary. Below is the method in question: [HttpPost] [ValidateAntiForgeryToken()] public Redirec ...

Is it possible to use uglifyjs to merge multiple files into a single minified file?

I attempted to compress multiple javascript files into one using the uglifyjs tool, but encountered an issue. I ran $node uglifyjs.js to execute the file. Below is the content of the uglify.js file: var fs = require('fs'); var uglifyjs = re ...