Ways to initiate a transition upon clicking a button, causing it to switch from being hidden (`display: none`) to visible (`display: block`)

I'm attempting to create a smooth transition effect when a button is clicked, similar to a toggle function, where the content below it seamlessly shifts instead of abruptly moving. The classic example of this is the Bootstrap navbar hamburger menu, where clicking on the menu in mobile view causes the items below it to smoothly adjust to make space for the navbar items. Here are the code snippets I've implemented:

let box = document.querySelector("#box");
let seconddiv = document.querySelector("#seconddiv");
box.addEventListener("click", myfunc);
function myfunc() {
  if(seconddiv.style.display == "none") {
    seconddiv.style.display = "block";
  }
  else {
    seconddiv.style.display = "none"
  }
}
#box {
  height: 50px;
  width: 50px;
  background-color: red
}

#seconddiv {
  display: none;
}
<div id="box">
</div>
<div id="seconddiv">
  <p>whats up</p>
  <p>whats up</p>
  <p>whats up</p>
  <p>whats up</p>
  <p>whats up</p>
  </div>
<p>hello</p>

When I click on the red box, the "hello" text moves instantly when the "seconddiv" display is set. Is there a way to achieve a smoother transition for the movement of the "hello" text like in Bootstrap?

Answer №1

To achieve this, jQuery is the ideal solution. jQuery provides a more efficient and user-friendly way to handle this task. Be sure to include the jQuery file before implementing the following code:

$('#box').click(function(){
    $('#seconddiv').slideToggle();
});

If you prefer a slower speed for displaying and hiding the div when clicked, simply add the "slow" parameter to the slideToggle function.

$('#seconddiv').slideToggle("slow");

Answer №2

opacity:0 is not handled with transitions. However, you can use javascript to add a class to the button when clicked and then apply height:30px to the button with class '.clicked'

#seconddiv {
    height: 0;
    transition: height 0.5s
}

#seconddiv.clicked{
    height: 30px;
}

You can also work with width or opacity instead of height. The difference with opacity is that the element will still occupy space even when set to opacity:0

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

Using Node Express.js to access variables from routes declared in separate files

Currently, I am in the process of developing a website with numerous routes. Initially, all the routes were consolidated into one file... In order to enhance clarity, I made the decision to create separate files for each route using the Router module. For ...

When you zoom in or out, HTML5 elements styled with CSS will dynamically adjust

Hey everyone, I have a question about a problem I'm facing with my HTML and CSS page. The issue is that when I zoom in, the "Section" part moves underneath the nav bar, and when I zoom out, the footer moves next to the section part... Below is a sni ...

Dash that serves as a barrier between two words to avoid them from breaking onto

Is there a way to keep a dash ( - ) from breaking a word when it is at the end of a line? Similar to how &nbsp; prevents a line break between two words. The issue I am facing currently is with a dynamic blog post that includes the word X-Ray. Unfortun ...

Creating a distinctive vue form component from scratch

I have a requirement to develop a Vue component that enables users to create or edit a mailing address. The existing component structure is as follows: <template> <v-container> <v-form ref="form" lazy-validation> <v-text-field ...

Switch between Fixed and Relative positions as you scroll

Just a small adjustment is needed to get it working... I need to toggle between fixed and relative positioning. JSFiddle Link $(window).on('scroll', function() { ($(window).scrollTop() > 50) ? ($('.me').addClass('fix ...

bootstrap3 container alignment

I encountered a challenge while attempting to right-align multiple Bootstrap 3 containers in a straightforward manner. Despite my efforts, achieving this proved to be more complex than expected. In essence, I faced an issue where aligning the text box with ...

Show the current phone number with the default flag instead of choosing the appropriate one using the initial country flag in intl-tel-input

Utilizing intl-tel-input to store a user's full international number in the database has been successful. However, when attempting to display the phone number, it correctly removes the country code but does not select the appropriate country flag; ins ...

CSS3 transition applied to a jQuery direction-aware hover effect

I'm encountering difficulties making direction-aware hover and css transitions function correctly. Specifically, I am attempting to create a grid of elements with front and back faces, and on hover, have a css transition that flips the element to disp ...

Retrieve the value of the specific element I have entered in the ngFor loop

I've hit a wall after trying numerous solutions. Here is the code I'm working with: HTML: import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styl ...

Develop a list of findings from the search

Is there a way to extract the name from the image shown below? return testData.then((data) => { console.log(data) var results = []; var toSearch = params.suggestTerm; data = data["data"]["0"]; console.log(" ...

Identify Unintended Javascript Modifications in Ajax Request

We have developed a unique Javascript file for our clients to utilize. This innovative snippet captures a screenshot of the website it is executed on and then securely transmits it back to our server using jQuery.post() Given the sensitive nature of our i ...

Ways to transmit data from autocorrect to a higher-level class

Previously, I raised a question about passing state for React via props on Stack Overflow: Laggy TextField Updates in React. I have now revamped my code using ChrisG's approach, where I store states in the parent component FormSection and pass them a ...

Issue: Dynamic server is experiencing abnormal increase in usage due to headers on Next version 13.4

Encountering an error in the following function. It's a basic function designed to retrieve the token from the session. 4 | 5 | export async function getUserToken() { > 6 | const session = await getServerSession(authOptions) | ...

Using ajax to submit variables may not function properly

I have a set of data that has been processed using JavaScript and I am looking to save it to a database. I have been attempting to code something with AJAX, but so far, I have had no success... What I require: Two variables (id, name) need to be sent to a ...

How can I vertically align text in React-bootstrap Navbar Nav-items?

I have been struggling to find a solution to my problem without resorting to custom CSS classes. I'm wondering if it's possible to achieve what I need using only flex classes. Here is the code for a simple navbar component: <Navbar bg ...

Modify the array dynamically within the Factory

I am currently working on a simple app where I want to display embed videos with the click of a button. It was quite challenging for me to dynamically bind my embed players, but I managed to do it successfully. I created a factory that contains my data in ...

Animating HTML 5 canvas with keydown events

As a newcomer to programming, I've been experimenting with HTML 5 and canvas. My goal is to make a simple rectangle move when a key is pressed, but I'm facing difficulties in achieving this. I tried following the instructions provided in this gui ...

Removing elements in AngularJS using ngRepeat

Many have questioned how to implement item removal within the ngRepeat directive. Through my research, I discovered that it involves using ngClick to trigger a removal function with the item's $index. However, I haven't been able to find an exam ...

Encountering issues with installing packages while creating a new Angular 9 project

Recently I updated to node version 12.16.1 (LTS) and Angular CLI version 9.0.3. After creating a new project with the CLI, all files in the root folder are generated but it gets stuck during the installation of node packages. Has anyone else encountered t ...

Issues with jQuery Progress Bar Functionality

As a beginner in jQuery, I am currently working on creating an interactive progress bar using jQuery. My goal is to provide a set of checkboxes on a webpage so that when a visitor checks or unchecks a checkbox, the value displayed on the progress bar will ...