Utilize jQuery animations without the need for using display: block in your

I've been experimenting with .slideToggle() in jQuery to toggle a hidden div from display: none to display: grid. However, it seems like this animation is forcing display: block inline onto the HTML and overriding any other CSS classes.

CSS

.grid {
    display: grid;
}

jQuery

$('#nav-toggle').click(function() {
    $('.nav-menu').slideToggle(500, function() {
        $(this).toggleClass('grid')
    });
});

I managed to find some success by using

$('#nav-toggle').click(function() {
    $('.nav-menu').slideToggle(500, function() {
         if ($(this).is(':visible')) {
             $(this).css('display','grid');
         }
    });
});
.nav-menu {
    display: none;
    grid-template-columns: repeat(3, 1fr);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=nav-toggle>
    Toggle
</div>

<div class=nav-menu>
    <div>Item 1</div>
    <div>Item 2</div>
    <div>Item 3</div>
</div>

However, during the initial animation, it still shows using display: block, and only after the animation finishes does jQuery recognize the element as visible and switch it to display: grid.

Subsequent animations work smoothly with display: grid. Is there a way to make the initial animation display correctly too?

Answer №1

If you want to create a responsive navigation menu that works even for users with JavaScript disabled, consider setting the nav-menu to display:grid; and using JQuery to hide and show it.

Give this code a try:

$('.nav-menu').hide(); // easier to understand than display none
$('#nav-toggle').click(function() {
  $('.nav-menu').slideToggle(500, function() {
    if ($(this).is(':visible')) {
      $(this).show(); // clearer than displaying previous (in this case grid)
    }
  });
});
.nav-menu {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="nav-toggle">
  Toggle
</div>

<div class="nav-menu">
  <div>Item 1</div>
  <div>Item 2</div>
  <div>Item 3</div>
</div>

For more information, visit:

Answer №2

Instead of making responsive CSS media queries messy, I found a cleaner solution by wrapping the nav element in a div and toggling between display: none and display: block.

I was still able to align the menu items properly since the child of the block is the nav, maintaining the grid property. Even within a more complex parent layout using display: grid, I could still apply CSS techniques to expand and center the block.

Although it's not a perfect solution, it gets the job done until jQuery evolves to support more than just display: block for its animations.

$('#nav-toggle').click(function() {
    $('.nav-menu-container').slideToggle(500, function() {
        if ($(this).css('display') == 'none') {
            $(this).css('display', '');
        }
    });
});
.nav-menu-container {
    display: none;
}

.nav-menu {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=nav-toggle>
    Toggle
</div>
<div class=nav-menu-container>
    <div class=nav-menu>
        <div>Item 1</div>
        <div>Item 2</div>
        <div>Item 3</div>
    </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

Having difficulties in loading the CSS file for my real-time chat application built with Express and Socket.io

Hi everyone, I've been struggling with an issue for the past couple of days where I can't seem to load my CSS for my Express app. If anyone has a solution, I would greatly appreciate the help. Below is my server.js code: const express = requir ...

Are there any web browsers that automatically switch to a non-SSL connection if an attempt to connect with SSL

I regularly utilize jQuery along with jQuery.ajax to make connections between pages. I am interested in establishing a connection from a non-SSL page to an SSL page using ajax. Are there any web browsers that will attempt to connect via non-SSL if the con ...

Combining all string elements in an array while preserving objects - here's how to do it

As I ponder the complexity of my question, I find myself wondering how to condense an array by merging adjacent strings while keeping objects intact. For example: array = ["I","want","to",[Obj],"come","together"] The desired output would be: ["I want to ...

Summing up various results from promises [Protractor]

On my webpage, I have set up two input text boxes and a label. My aim is to extract the numbers from these elements, sum up the numbers in the text boxes, and then compare the total with the number in the label. Does anyone know how I can achieve this? He ...

Animating components when they first mount in React

I'm attempting to implement an onMount animation in React (and Tailwind if relevant). The code I currently have is as follows: const Component = () => { const [mounted, setMounted] = useState(false) useEffect(() => { setTimeout(( ...

Text Parallax Effect

For my website, I am interested in incorporating a unique parallax effect. Instead of just fixing a background image and allowing scrolling over it, I want to apply this effect to all of the content on my site. The website consists of a single page with m ...

"Unlocking the Power of jQuery: A Guide to Customizing CSS with Scroll Effects

Many CSS examples include a scrollbar for editing the CSS code. Click here to see an example of the scrollbar I haven't been able to find any instructions on how to do this. Can someone please explain? ...

Guide to extracting the values associated with a specific key across all elements within an array of objects

My goal is to retrieve the values from the products collection by accessing cart.item for each index in order to obtain the current price of the product. const CartSchema = mongoose.Schema({ userId: { type: mongoose.Schema.Types.ObjectId, ...

Ensuring Consistency in Object Size When Switching Between Perspective and Orthographic Cameras

Struggling to toggle between Perspective and Orthographic cameras in my script. I need objects at certain depths to maintain their projection size. I've reached a point of confusion when trying to understand the geometry... Can anyone recommend a sim ...

Post a message utilizing javascript

Can a client-side tweet be generated using JavaScript, a text box, and a submit button? This involves entering the tweet text into the textbox, clicking the button, and then tweeting it with an authenticated account all within the client's browser. ...

CSS navigational sprite technology

Can three images be used in CSS sprite navigation? Something like this perhaps: Check out my image here: http://img710.imageshack.us/img710/1429/navigx.jpg If it is possible, what would the outcome look like? ...

The responsive grid in bootstrap-vue can sometimes cause content to be concealed

I am in the process of creating a vue application using bootstrap-vue. Here is a snippet of my template and styles: <template> <div> <b-container class="p-0 mt-3" fluid> <b-row style="height:110px"> ...

Invoking a nested method within Vue.js

I am facing an issue in my vuejs application with 2 methods. When I define method1 a certain way, it does not run as expected. method1: function(param1, param2){ // I can log param1 here thirdLib.debounce(function(param1, params2){ // It d ...

Tips for sending images as properties in an array of objects in React

I've been experimenting with various methods to display a background image underneath the "box" in styled components. How can I pass an image as a prop into the background image of the box with the image stored in the array of objects? I'm unsure ...

"Exploring the Possibilities with WordPress and Waypoint Js

After exploring various resources and tutorials online, I am struggling to implement Waypoints with WordPress. Despite placing the necessary files like waypoints.min.js and waypoints.js in the designated download folder within the js directory of my templa ...

Alert: An error message is displayed despite completing the required field

My apologies in advance as I am new to coding and there may be a glaring mistake in my current project. I am creating a survey that requires participants to enter their age. The demographic data questions are organized in a table format, with code borrowed ...

Leveraging Selenium Basic with Excel Version 16 to Manipulate Arrays within "div" Tags

Currently, I am extracting data through Web scraping from a Chrome web page in Excel v.16 with the help of Selenium Basic. Due to the sensitive nature of patient information, I must be cautious about disclosing too much detail. (Initially, I developed the ...

Having trouble utilizing JQuery to toggle the visibility of the div closest to a checkbox

Currently, I am utilizing Ruby on Rails along with the Cocoon Gem for generating dynamic forms. Specifically, users are able to add or remove their Education details using this form. Here is an example of how my form appears: <div class='nested-fi ...

Using CSS to showcase div elements with varying dimensions

How can I arrange divs with varying heights to be positioned close together, regardless of their height, and with a specific margin similar to buildings? I am aiming for a layout like the one on this website . I tried using float:left but it only float ...

The CSS Accordion seems to be the culprit behind the missing margin or border at the top of my page

Although everything on the page is functioning as desired, there seems to be a missing margin or border that is not causing much trouble. If there is a simple solution or an easy way to identify why this is happening, it would be greatly appreciated. Take ...