Animate the smooth transition of a CSS element when it is displayed as a block using JQuery for a

I have implemented the collapsible sections code from W3 School successfully on my website. Now, I am trying to achieve a specific functionality where the "Open Section 1 Button" should slide down with a margin-top of 10px only if the first section "Open Section 1 Content" is hidden (display: none). This seems like a simple task, but as a newcomer to JavaScript, I am finding it challenging to dynamically apply CSS based on certain conditions (and revert it back to margin-top: 0 if display: block).

I have experimented with different approaches, but they interfere with the original W3 JS code, causing it to malfunction when anything related to display manipulation is added.

I am looking to target only one element and make changes to its status if there is a switch between display block and none. Furthermore, it would be great to incorporate some animation effects while the element moves up and down.

In addition, I want to activate another hidden div (not previously mentioned) with an image if all collapsible sections are set to display none. This hidden div should be hidden again if any of the sections are changed to display block.

Any assistance in solving this issue would be highly appreciated.

(I currently have three collapsible sections, each accompanied by three buttons, following a similar structure as the example provided by W3)

var coll = document.getElementsByClassName("collapsible");
var i;

for (i = 0; i < coll.length; i++) {
    coll[i].addEventListener("click", function() {
        this.classList.toggle("active");
        var content = this.nextElementSibling;
        if (content.style.display === "block") {
            content.style.display = "none";
        } else {
            content.style.display = "block";
        }
    });
}
.collapsible {
    background-color: #777;
    color: white;
    cursor: pointer;
    padding: 18px;
    width: 100%;
    border: none;
    text-align: left;
    outline: none;
    font-size: 15px;
}

.active, .collapsible:hover {
    background-color: #555;
}

.content {
    padding: 0 18px;
    display: none;
    overflow: hidden;
    background-color: #f1f1f1;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<p>Collapsible Set:</p>
<button class="collapsible">Open Section 1</button>
<div class="content">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
<button class="collapsible">Open Section 2</button>
<div class="content">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
<button class="collapsible">Open Section 3</button>
<div class="content">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
</body>
</html>

Answer №1

To introduce animation effects to your elements, consider creating a function that smoothly adjusts the margin of the initial section. This function will specifically set the margin-top property to 10px if the next element's display is not set as block. It's advisable to activate this function on page load and whenever the content is displayed. For a sleek animated transition, include transition: margin 0.5s within the styling of the .collapsible class.

.collapsible {
    background-color: #777;
    color: white;
    cursor: pointer;
    padding: 18px;
    width: 100%;
    border: none;
    text-align: left;
    outline: none;
    font-size: 15px;
    transition: margin 0.5s;
}

.active, .collapsible:hover {
    background-color: #555;
}

.content {
    padding: 0 18px;
    display: none;
    overflow: hidden;
    background-color: #f1f1f1;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<p>Collapsible Set:</p>
<button class="collapsible">Open Section 1</button>
<div class="content">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
<button class="collapsible">Open Section 2</button>
<div class="content">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco loremipsum velit est excepteur sint occaecat cupidatat non proident sunt in culpa qui officia.
</div>
<button class="collapsible">Open Section 3</button>
<div class="content">
  <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia lorennial. Duis aute irure dolor in reprehenderit in voluptate velit esse meet dolore eu fugiat nullartur proundly reprenstinutore.</p>
</div>
<script>
var coll = document.getElementsByClassName("collapsible");
var i;

for (i = 0; i < coll.length; i++) {
    coll[i].addEventListener("click", function() {
        this.classList.toggle("active");
        var content = this.nextElementSibling;
        if (content.style.display === "block") {
            content.style.display = "none";
        } else {
            content.style.display = "block";
        }
        moveSection();
    });
}
function moveSection(){
  var section1 = coll[0];
  if(section1.nextElementSibling.style.display!="block"){
    section1.style.marginTop = "10px";
  } else {
    section1.style.marginTop = "";
  }
}
moveSection();
</script>
</body>
</html>

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

When using IE10/IE11 in compatibility mode 8, there is an issue with the jquery.fileupload.js (v9.5.2) where uploading a

We are facing a challenge where we need to use IE10/IE11 in compatibility mode IE 8 to support older online sites that utilize iframes and newer html5 applications built with technologies like jquery and angular. Specifically, we are encountering an issue ...

Tips for creating basic Jasmine and Karma tests for an Angular application to add an object to an array of objects

I have developed a basic Angular project for managing employee data and I'm looking to test the addProduct function. Can someone guide me on how to write a test case for this scenario? I am not using a service, just a simple push operation. Any assist ...

Having trouble implementing String.prototype in my factory

Currently, I am working on incorporating a function mentioned in this answer. String.prototype.supplant = function (o) { return this.replace(/{([^{}]*)}/g, function (a, b) { var r = o[b]; return typeof r === 's ...

Strange gray gradient background suddenly showing up on mobile devices

Encountering an issue with a login form displayed on a sliding modal. The design looks correct on desktop and even in responsive mode with dev tools, but when accessed through mobile Chrome or Safari on an iPhone, an unusual gray rounded box or shadow appe ...

Ensuring Consistent Height for Bootstrap Card Headers

I am currently working with bootstrap cards on two different web pages. The challenge I am facing is that on one page, the header text has a fixed height so I can easily match their card-header height using min-height. However, on the second page, the card ...

State in Vuex is not kept intact after redirection to another page

Inside my Vue.js application, I have created a method for logging in users. This method sends a POST request to the server with the username and password, stores the returned data in Vuex store, and then redirects the user to the home page: login: func ...

template strings receive null value

I am currently facing an issue with the execution of certain template literals in my jQuery functions. Although some are functioning as expected, there is a specific block that is not being executed. function viewUserDetails(data) { // retrieves integer v ...

A single feature designed to handle various elements

I currently have this HTML code repeated multiple times on my webpage: <form class="new_comment"> <input accept="image/png,image/gif,image/jpeg" id="file" class="file_comment" key=comment_id type="file" name="comment[media]"> <spa ...

Select2 eliminates every tag except the first one

I am currently utilizing Select2 in Django for handling many-to-many relationships. The best approach I have found to handle all validation constraints is to create related objects through an AJAX request as soon as they are entered into the Select2 tag fi ...

Customize CSS styles based on Angular material stepper orientation

Is it possible to change the CSS style of an angular material stepper based on its orientation? For instance, can we set a red background when the stepper is displayed vertically and a blue background when horizontal? ...

Guide to expanding the sidebar width

As I delve into the world of CSS, I find myself puzzled by the issue of expanding the sidebar to ensure that the "Gestion des utilisateurs" section appears on a single line. https://i.stack.imgur.com/xzFEA.png To provide context, I have included an illus ...

Error parsing data in the $.ajaxSetup() function of JQuery

Currently, I am coding a program using jQuery. It was functioning perfectly in Firefox 3.5 until I upgraded to Firefox 4.0. Since then, the dreaded 'parsererror' keeps popping up and causing me quite a headache. I've pinpointed the exact pa ...

Validate that the input is an array

Looking for a way to determine if a function parameter is an array or not, and then process it accordingly. If the parameter is not an array, convert it into an array before performing the desired function. For example: interface employee { first: st ...

"Upon submitting a form in React JS, the components will automatically trigger a

Within my application, there is a Mobx storage in conjunction with a modal window component. The form within the modal window allows me to collect all the properties and push them into an array named 'cart' within the storage as an object. Take a ...

Update a portion of a hyperlink using jQuery

Currently, I am utilizing Ransack for sorting purposes. However, I encountered an issue when attempting to modify the sorting links in cases where both search and sorting functionalities are implemented using AJAX. As a result, I have taken it upon myself ...

Response from JSON data through jQuery AJAX call includes key "d"

After sending a jQuery AJAX JSON request, the response includes an unexpected "d" attribute. What could be causing this unusual behavior? ...

Tips for creating animations with JavaScript on a webpage

I created a navigation bar for practice and attempted to show or hide its content only when its title is clicked. I successfully toggled a hidden class on and off, but I also wanted it to transition and slide down instead of just appearing suddenly. Unfort ...

Looking for a JavaScript code to create a text link that says "submit"?

Here is the code I have, where I want to utilize a hyperlink to submit my form: <form name="form_signup" id="form_signup" method="post" action="/" enctype="multipart/form-data"> ... <input type="submit" value="Go to Step 2" name="completed" /> ...

The npm http package exclusively includes a package.json without any accompanying JavaScript files

After installing an npm package that listed 'http' as a dependency, I also installed 'http'. However, all npm downloaded for 'http' was a package.json file that referenced a non-existent index.js file. Could it be that the ind ...

How can the top height of a jquery dialog be reduced?

Just starting out with jquery, I've got a dialog box and I'm looking to decrease the height of this red image: https://i.sstatic.net/BuyQL.png Is there a way to do it? I've already made changes in the jquery-ui.css code, like so: .ui-dia ...