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

Retrieving data from a JSON file depending on the selection made by the user in a dropdown menu

In my project, I have a JSON file named countries.json that contains country and regional information. Users are required to select a country using a Python-generated dropdown list from this file. However, due to the backend nature of Python, I am unable t ...

Tips for keeping the main section from scrolling while scrolling through the side navigation

Within my Angular application, I have implemented a sidenav and a main section. My desired behavior is to prevent any scrolling in the main section while I am scrolling in the sidenav, similar to the functionality seen on the Angular Material Design docume ...

Guide on populating a Vue.js input field with a value retrieved from a JSON object

Could someone please assist me with a problem I am encountering? I need to extract and display the values from an input form for "name" and "position", but the data is in JSON format. {"id":5,"name":"the name","pos":"the position"} This code snippet repr ...

Sort by user identifier

I'm having an issue trying to filter a list of posts and comments by userId. I've passed the userId params as postCreator and commentCreator, but something seems to be amiss. Can anyone help me identify what I might be doing wrong? // Defining ...

What is the best way to tally data-ids within an anchor tag using jQuery or plain JavaScript?

find total number of data-id attributes within tag a I am looking for a way to calculate the count of my id attribute, whether it is in data-id or another form, using JavaScript. Edit ...

Get hexa values from a colorpicker and use them as a background in an angularjs application

I'm currently working on an angularJS project and I've implemented an HTML color picker. My goal is to assign the selected color from the color picker to my div element, ensuring that the values are in hexadecimal format. Below is a snippet of my ...

Struggling with adding documents into mongoDB with the help of mongoose and node.js

I have a mongoose model defined below: module.exports = mongoose.model('vbDetail', { company_name: String, rowsdata: {vals: { date: Date, transaction_type: String, transaction_num: Str ...

The PHP Form submit button is unresponsive

My code is functioning correctly, but when I try to submit the form, it doesn't provide any response or error message. I even attempted to change the form action attribute and save the result in a different file, but still no output was displayed. &l ...

Utilizing ng-options to pass values rather than entire objects

Currently, I am parsing a .json file and displaying all available options in a select dropdown menu: <div bo-switch-when="dropdown"> <fieldset> <select ng-options="options.text for option in question.body.options" ng-model="question ...

extracting characters in php

Here's the HTML code I'm working with: <p style="color:red;font-size:12px;">This budget-friendly car offers great value, complete with air conditioning making it perfect for couples and small families. There is a ?500 excess, but it can be ...

Stop Google from indexing content that is loaded through ajax requests

Our website utilizes Ajax calls to load duplicate content. This method helps enhance user experience by avoiding the need to reload the entire page when users click on the menu. Although this technique works efficiently, the Ajax-loaded content is essenti ...

How can I toggle a clicked switch in React MUI instead of all switches?

This is the current state in my parent component: const [feedbackType, setFeedbackType] = useState({ manual: true, auto: false, }); I am passing this state as a prop to the child component. In the child component, I have the following code: co ...

Enforcing the autocompletion selection in jQuery UI

As I was working on my original question, I realized that I needed to ask a separate question because I didn't fully grasp what I was trying to achieve. I am currently utilizing the jquery Tag-it plugin available at https://github.com/aehlke/tag-it a ...

Issue with setting innerHTML of element in AngularJS app upon ng-click event

Look at this block of HTML: <div class="custom-select"> <div class="custom-select-placeholder"> <span id="placeholder-pages">Display all items</span> </div> <ul class="custom-select- ...

Coming back to the main script after executing a child node script within a parent node script

I am currently facing an issue where I am attempting to invoke a node script from another node script using execSync. Below is the code snippet illustrating my situation: scriptA.js function a () { for(i=0,i<names.length;i++){ var a = 'somes ...

Customizing the appearance of Indicators and Paginator in PrimeNG Carousel

I have integrated a carousel using PrimeNG which has the following design here Take note of the style of the carousel indicators and navigators. I want to achieve the default style of indicators/navigators for the carousel as shown here I have included t ...

Stop Gmail from Removing Attached HTML Files

I successfully developed an HTML file with its own CSS styling and custom HEAD tags to ensure it displays well in mobile browsers. I managed to make it work with PHP as a file attachment. However, the issue arises when Gmail distorts the view of the file ...

Tips for displaying a close icon after completing a file upload

I need to implement a feature where once a user uploads a file, a cross sign should be enabled on the file. I attempted to use javascript for this functionality, but it seems to not be working as expected. There are more than 8-10 different file types that ...

creating a distinct angular service for every controller

Lately, I've been utilizing Angular services to store my commonly used codes that are required across different parts of my project. However, I have encountered an issue where variables in the service are shared between controllers. This means that if ...

Trouble with displaying my three.js 3D model

I've tried multiple solutions I found, but none have fixed the issue of not being able to display 3D models. Many have suggested that it could be a problem with the camera, but so far I haven't been able to resolve it. Any assistance would be gre ...