Why is the toggle functioning properly?

After much trial and error, I finally got my toggle functionality working with the following code. I was surprised that toggling the width actually changed the display settings, but it did the trick! It's still a bit mysterious to me how it all works together. Take a look at the code snippet below:


  <head>
    <link href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
    <style>
      .contact {
        list-style:none;
        display:inline;
        position:relative;
      }
      #contList{
        position:fixed;
        left:3.0%;
        bottom:1.1%;
        padding:0px;
        margin:0px;
        white-space:nowrap;
        display:none;
      }
      #contButton{
        width:2.9%;
        position:fixed;
        bottom:0px;
        left:0px;
      }
    </style>
    <script src='http://code.jquery.com/jquery-1.11.0.min.js'></script>
  </head>
  <body>
    <div id='contMenu' class='contMenu'>
      <a id='contButton'>
        <i class="fa fa-globe fa-3x"></i>
      </a>
      <ul id ='contList'>
        <li class='contact'><i class="fa fa-envelope fa-2x"></i></li>
        <li class='contact'><i class="fa fa-twitter fa-2x"></i></li>
      </ul>
    </div>
    <script>
      $(document).ready(init);

      function init(){
        slideToggle();
      }

      function slideToggle(){
        $('#contButton').click(function(){
          $('#contList').animate({width:'toggle'});
        });
      }
    </script>
  </body>

If you'd like to test out this code for yourself, check out the JsFiddle here: http://jsfiddle.net/mfedore1/Lf4k9/

Answer №1

The width property is set to 'toggle' as the target value. When the element contList was previously visible, the animation will shrink the width to 0 in order to hide it.

According to the documentation:

Along with numerical values, properties can also be assigned the strings 'show', 'hide', and 'toggle'. These options enable customized animations for showing and hiding elements while considering their display type. To utilize jQuery's built-in toggle state tracking, consistently use the 'toggle' keyword as the value of the animated property.

https://api.jquery.com/animate/

Answer №2

$(document).ready(initialize);

When the document is loaded, initialize the function.

function initialize(){
    slideToggle();
  }

Call the function slideToggle()

function slideToggle(){
    $('#contButton').click(function(){ // when contButton is clicked, this function starts
      $('#contList').animate({width:'toggle'}); // take #contlist and put width to "toggle-mode"(between 0 and value)
    });
   }

Take a look at this helpful question - it will guide you through! :)

.animate({ width: 'toggle' }) without messing up the content

Answer №3

Referenced from https://api.jquery.com/animate/

"Apart from just numerical values, properties in jQuery animate method can also accept strings like 'show', 'hide', and 'toggle'. These handy shortcuts make it easier to create custom hide and show animations that consider the element's display type. To leverage jQuery's built-in toggle state tracking feature, always use the 'toggle' keyword as the property value being animated."

I think the intention behind using the 'toggle' keyword in jQuery's animate method was to ensure a specific behavior that takes into consideration the element's display type.

My speculation is that when jQuery encounters animate({width: 'toggle'}), along with 'display: none', it assumes the appropriate animation should transition from width: 0 to the actual width of the element while altering the display property to make the animation visible.

Cheers!

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

Trouble with Rails partial refresh using Ajax feature

On the homepage, I would like to display article information to the user. When the user clicks on the My Articles link, the relevant information should be shown without refreshing the entire page: Here is the code for the ArticlesController: def index ...

The dropdown feature functions properly on Chrome but seems to be malfunctioning on

Dropdown list inside the HTML header table My query was addressed in the link above, however, the solution only seemed to work on Chrome and not Firefox. I specifically want the dropdown arrow header to be displayed next to the table header instead of bel ...

Code breaking due to Selenium locating element by class

When my application opens a login page, it looks for valid combinations. Initially, there is a button labeled as "check availability" that Selenium can locate and click on. If the username is already taken, a new button appears with the text "check anothe ...

Problem with responsive design on iPhone

I'm currently working on developing a responsive chatbot using CSS Bootstrap. However, I've encountered an issue where the header and footer are not fixed when I open the app on an iPhone. The keyboard header is also moving up the screen, which s ...

What is the best way to implement a dropdown in MUI and React that displays functional components as items?

Here is a list of dummy components: const OwnerList = () => { return ( <Box sx={{ display: 'flex', }} className="owner-container" > <Avatar src='https://hips.hearstapps.com/hmg- ...

Editing the content of a div in real-time by dynamically updating the innerHTML

Looking for a way to dynamically change the innerHTML of a contentEditable div using pure JavaScript, without relying on the Rangy library. I want the change to occur on keyup without losing cursor position or focus. Here is an example setup: <div id=" ...

Experiencing issues with exporting <SVG> file due to corruption

I received some downvotes on my previous post, and I'm not sure why. My question was clear, and I provided a lot of information. Let's give it another shot. My issue is with exporting <SVG> files from an HTML document. When I try to open t ...

What could be causing my ng-grid footer to refuse to align with the bottom border?

Currently utilizing ng-grid and various AngularJS UI Bootstrap components on my website, I have encountered a recurring issue. By diligently investigating, I have successfully replicated the problem. Access the Plunker demonstration through this link. The ...

Ways to create a clickable red button

I'm working with bootstrap, CSS, and particle.js for this project. I have also linked a custom CSS file here. However, when I apply bootstrap and particle.js, the red color generate password button becomes unclickable. After checking in Chrome dev too ...

Rendering images in Next.js version 10

Just recently, Next.js version 10 was launched featuring the latest Image element, making it a great asset for websites that heavily rely on images! When I receive an HTML response from the server, it looks something like this: HTML = "<div> &l ...

creating tabulations and charts across various while loops

My goal is to create Tabs using information from the first while loop, and then populate a table within each Tab using data from the second while loop. The data is fetched date-wise from my 'treatment' table to generate the Tabs. The line items ...

Strange symbols keep appearing in my output from PHP

My current task involves generating a SQL query based on some inputs. I have a predefined SQL statement, in which I perform certain replacements, that will use these inputs to generate the required SQL through an ODBC connection. For now, I have stored th ...

Learn the steps for inserting or updating data in a local JSON file solely through JavaScript

Currently, I am in the process of reading a JSON file and removing an element once it finds an exact match. My goal is to then push the remaining data back into the JSON file after deletion. readJsonFile("./objects.json", function(jsonData){ let parsedD ...

HTML/CSS: There is a sentence that has no spaces that is exiting outside a div

HTML: <div> bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb </div> CSS: div { width: 150px; border: 1px solid blue } DEMO: http://example.com QUESTION: How can we solve this issue? ...

What causes certain divs to protrude when the parent div has overflow:hidden property enabled?

Issue: I am facing difficulty aligning all elements within one div without any overflow issues. Even with the parent div set to overflow:hidden, some child divs are protruding out of the container. How can I resolve this problem? Example: http://jsfiddle. ...

Developing dynamic 3D cubes

In my latest project, I am attempting to construct a unique structure composed of 3D cubes arranged in a stacked formation. Each of the individual cubes within this structure is designed to be interactive for users. When a user hovers over a cube, it trigg ...

Ensure that any relevant information is placed adjacent to a floated image

I am currently designing a responsive webpage featuring images of people's faces placed next to descriptive text. At smaller screen widths, everything looks perfect. However, as the page widens, the text for one person starts next to the image of the ...

Merge information from various sources using ajax

Currently, I have a single ajax request that retrieves data from an API and uses it to generate a table. Now, I'm looking to modify the code so that it can retrieve data from two different URLs and merge them into the same table (retTable). Below is ...

Enhance your Zara shopping experience with the dynamic image zoom-in

I am currently exploring ways to replicate the image zoom-in feature seen on Zara's product pages. To see this effect in action, visit their site: Upon clicking on the image, it opens up in a popup window where it is enlarged to fit the entire screen ...

Retrieving details of a row in Codeigniter using a link with a foreach loop

After nearly a month of trying, I am still unable to figure out how to extract the "details" for each row from my table in the view. The table is populated using a foreach loop and I want to display these details on another page when clicking the link labe ...