Press the identical button to return to the initial position with the help of jQuery

1) I am currently working on a vertical menu layout and have successfully placed an image in the top right corner that allows users to adjust the width of the menu. However, I am facing an issue where I have to click on the same image to restore the menu to its original position after resizing.

2) I am also looking for a solution to change the size of the menu image when the menu is in a smaller position. If you can help me with this, please refer to the code snippet provided below for reference. Thank you!

$(document).ready(function() {
  // Show hide popover
  $(".active-dropdown").click(function() {
    $(this).find(".left-menu-dropdown").slideToggle("fast");
  });
});
$(document).ready(function() {
  $('#slide-left-menu').click(function() {
    $(".left-menu").animate({
      width: '100px'
    }, 'slow', 'linear', function() {
      $('.left-menu-list ul li span').remove();
    });
  })
});
html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
}

.left-menu {
  background-color: #ff0000;
  width: 37%;
  height: 100%;
  z-index: 4;
}

.left-menu .inside-left-menu {
  padding: 20px 15px;
}

.left-menu .left-menu-logo img {
  width: 50px;
}

...(remaining CSS code)...
                    
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<div class="left-menu">
  <div class="minimize-left-menu">
    <img src="https://d30y9cdsu7xlg0.cloudfront.net/png/66344-200.png" id="slide-left-menu">
  </div>

  ...(remaining HTML code)...
                    

Answer №1

To revert its size back to original, you should create a new function for it. Instead of using .remove, you can simply use .hide on the span element so that you can display it again in a later event.

$(document).ready(function() {
  // Toggle display of popover
  $(".active-dropdown").click(function() {
    $(this).find(".left-menu-dropdown").slideToggle("fast");
  });
  
  $('#slide-left-menu').click(function() {
    $(this).toggleClass('active');
    if (!$(this).hasClass('active')) {
      $(".left-menu").animate({
        width: '37%'
      }, 'slow', 'linear', function() {
        $('.left-menu-list ul li span').show();
      });
    } else {

      $(".left-menu").animate({
        width: '100px'
      }, 'slow', 'linear', function() {
        $('.left-menu-list ul li span').hide();
      });
    }
  })
});
html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
}

.left-menu {
  background-color: #ff0000;
  width: 37%;
  height: 100%;
  z-index: 4;
}

.left-menu .inside-left-menu {
  padding: 20px 15px;
}

.left-menu .left-menu-logo img {
  width: 50px;
}

.left-menu .left-menu-logo-text {
  width: 100px;
  display: inline-block;
  color: #000;
  vertical-align: middle;
}
...
...

</div>
<!--left-menu-->

Answer №2

Take a look at this practical demonstration:

  $(document).ready(function() {
    // Function to toggle popover visibility
    $(".active-dropdown").click(function() {
      $(this).find(".left-menu-dropdown").slideToggle("fast");
    });

    $('#slide-left-menu').click(function() {

      // Setting the width using a class
      // You can also directly define the width using the class itself
      // Customize the values as needed

      let width = $(".left-menu").hasClass('closed') ? '37%' : '100px' ;

      // Handling the visibility of text
      // Using 'hide' is preferred over 'remove'

      let methVisi = $(".left-menu").hasClass('closed') ? 'show' : 'hide' ;

      $(".left-menu").animate({

        // Transition from 100px to 37%, or 37% to 100px
        width: width

      }, 'slow', 'linear', function() {
        $('.left-menu-list ul li span')[methVisi]();
      });

      // Adding or removing the 'closed' class to the menu

      let method = $(".left-menu").hasClass('closed') ? 'removeClass' : 'addClass'
      $(".left-menu")[method]('closed');
    })
  });
  
      html,
      body {margin: 0;padding: 0;height: 100%;}
      .left-menu {background-color: #ff0000;width: 37%;height: 100%;z-index: 4;}
      .left-menu .inside-left-menu {padding: 20px 15px;}
      /* Other CSS styles go here... */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="left-menu"><div class="minimize-left-menu"><img src="https://d30y9cdsu7xlg0.cloudfront.net/png/66344-200.png" id="slide-left-menu"></div><div class="inside-left-menu">
    <div class="left-menu-logo"><img src="http://www.newgeography.com/files/imagecache/Chart_Story_Inset/bigstock-happy-smiley-25475741.jpg"><div class="left-menu-logo-text"<h2><span>Logo</span>name</h2><h3>by <span>slogan</span></h3></div></div>
    <div class="left-menu-list">
      <ul class="left-menu-main-list">
        <li><a href=""><img src="https://cdn4.iconfinder.com/data/icons/wirecons-free-vector-icons/32/add-128.png"><span>Example 1</span></a></li>
        <li class="active-dropdown"><a href="JavaScript:void(0);"><img src="https://d30y9cdsu7xlg0.cloudfront.net/png/30440-200.png"><span>Example 2</span></a><ul class="left-menu-dropdown">
        <li><a href=""><img src="https://d30y9cdsu7xlg0.cloudfront.net/png/30440-200.png"><span>Example 2/1</span></a></li>
        <li><a href=""><img src="https://d30y9cdsu7xlg0.cloudfront.net/png/30440-200.png"><span>Example 2/2</span></a></li></ul></li>
        <li><a href=""><img src="https://image.flaticon.com/icons/png/128/61/61391.png"><span>Example 3</span></a></li>
        <li class="menu-top-border"><a href=""><img src="https://cdn4.iconfinder.com/data/icons/wirecons-free-vector-icons/32/add-128.png"><span>Example 4</span></a></li>
        <li><a href=""><img src="https://cdn4.iconfinder.com/data/icons/wirecons-free-vector-icons/32/add-128.png"><span>Example 5</span></a></li>
      </ul></div></div></div>

Answer №3

To easily add an active class to the menu, consider utilizing jQuery.

Upon clicking the image, implement a click function to switch the active class on and off.

Here's an example:

$(document).ready(function() {
    $("img#toggle-menu").click(function(){
    $(".menu").toggleClass("active");
  });
});

https://jsfiddle.net/qrh3j0c8/1

Answer №4

Consider the following approach. One technique is to use a variable to keep track of the menu state and the original width of the menu.

$(document).ready(function() {
  // Toggle popover visibility
  $(".active-dropdown").click(function() {
    $(this).find(".left-menu-dropdown").slideToggle("fast");
  });
});
$(document).ready(function() {
  var menuState = true;
  var menuWidth = null
  $('#slide-left-menu').click(function() {
    if(menuWidth === null) {
      menuWidth = $(".left-menu").width();
    }
    if(menuState) {
      $(".left-menu").animate({
        width: '100px'
      }, 'slow', 'linear', function() {
        $('.left-menu-list ul li span').remove();
        menuState = false;
      });
    } else {
      $(".left-menu").animate({
        width: menuWidth + 'px'
      }, 'slow', 'linear', function() {
        $('.left-menu-list ul li span').remove();
        menuState = true;
      });
    }
  })
});
html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
}

/* CSS styles for the left menu */
.left-menu {
  background-color: #ff0000;
  width: 37%;
  height: 100%;
  z-index: 4;
}

.left-menu .inside-left-menu {
  padding: 20px 15px;
}

/* More CSS styles for the left menu... */

/* HTML and JavaScript code */
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<div class="left-menu">
  <div class="minimize-left-menu">
    <img src="https://d30y9cdsu7xlg0.cloudfront.net/png/66344-200.png" id="slide-left-menu">
  </div>

  <div class="inside-left-menu">
    <div class="left-menu-logo">
      <img src="http://www.newgeography.com/files/imagecache/Chart_Story_Inset/bigstock-happy-smiley-25475741.jpg">
      <div class="left-menu-logo-text">
        <h2><span>Logo</span>name</h2>
        <h3>by <span>slogan</span></h3>
      </div>
    </div>
    <!--left-menu-logo-->

    <div class="left-menu-list">
      <ul class="left-menu-main-list">
        <li>
          <a href=""><img src="https://cdn4.iconfinder.com/data/icons/wirecons-free-vector-icons/32/add-128.png"><span>Example 1</span></a>
        </li>
        <li class="active-dropdown">
          <a href="JavaScript:void(0);"><img src="https://d30y9cdsu7xlg0.cloudfront.net/png/30440-200.png"><span>Example 2</span></a>
          <ul class="left-menu-dropdown">
            <li>
              <a href=""><img src="https://d30y9cdsu7xlg0.cloudfront.net/png/30440-200.png"><span>Example 2/1</span></a>
            </li>
            <li>
              <a href=""><img src="https://d30y9cdsu7xlg0.cloudfront.net/png/30440-200.png"><span>Example 2/2</span></a>
            </li>
          </ul>
        </li>
        <li>
          <a href=""><img src="https://image.flaticon.com/icons/png/128/61/61391.png"><span>Example 3</span></a>
        </li>
        <li class="menu-top-border">
          <a href=""><img src="https://cdn4.iconfinder.com/data/icons/wirecons-free-vector-icons/32/add-128.png"><span>Example 4</span></a>
        </li>
        <li>
          <a href=""><img src="https://cdn4.iconfinder.com/data/icons/wirecons-free-vector-icons/32/add-128.png"><span>Example 5</span></a>
        </li>
      </ul>
    </div>
  </div>
  <!--inside-left-menu-->
</div>
<!--left-menu-->

Answer №5

If you want to toggle the state of a menu, you can create a temporary class like open to keep track of its status:

 $('#slide-left-menu').click(function() {

   if ($(".left-menu").hasClass("open"){
        $(".left-menu").removeClass("open");
        $(".left-menu").animate({width: '50px'}, 'slow', 'linear'); //you can add your additional callback codes here
  }

   else {
    $(".left-menu").addClass("open");
    $(".left-menu").animate({width: '100px'}, 'slow', 'linear');
   }

});

Additionally, instead of using remove() to temporarily hide elements, it is recommended to use hide() instead.

Answer №6

A different approach, inspired by the solution from @user3416331, incorporating all the requirements and more:

  • Adjust menu width
  • Resize logo
  • Conceal menu items
  • Additionally, reduce the width of the "Logoname" to fit the new layout

(Simply enclose 'name' in a span tag)

  $(document).ready(function() {

    $(".active-dropdown").click(function() {
      $(this).find(".left-menu-dropdown").slideToggle("fast");
    });

    $('#slide-left-menu').click(function() {
      $('.left-menu').toggleClass('collapsed');
    })
  });
 Insert CSS code here 
Insert HTML code here 

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

Jumping CSS dropdown menu glitch

I'm facing an issue with a dropdown menu. The main problem is that the "parent" link is moving when hovered over. HTML: <ul id="nav"> <li><span>Page 1</span> <ul> <li><a>Extralong Pag ...

Track when a user modifies a <select> dropdown list generated using the Jquery method ".html()"

Is it possible to detect a change in the value of a select list when that select list has been added using either the .html(htmlString) or .append(content[,content]) jQuery function? HTML CODE: <ul class="htmlClass"> <!-- Populated via JS --& ...

I am encountering a "TypeError: topics.forEach is not a function" error when attempting to retrieve metadata for topics using my kafkajs client in Node.js/express.js. Can anyone help me understand why

I am attempting to retrieve the metadata of my Kafka brokers' topics using the kafkajs admin client within my Node.js + express.js server. Here is the content of my index.js file, serving as the main entrypoint for npm: 'use strict'; cons ...

What are the best methods for maintaining the appearance of my website when resizing my browser window?

I am replicating the Twitter profile page, but I am facing an issue where the text and images get jumbled together whenever I resize my browser. This results in a messy appearance of the page. How can I ensure that the text and images stay in the same rela ...

Utilize WebGL to incorporate a mesh as a background image mask

Currently, I am faced with a challenge in WebGL that involves the following scenario: Picture a mesh positioned in front of the camera. This mesh does not have traditional shading, but its outline, or "silhouette," is utilized to display a background imag ...

Import information from a website into MATLAB, including embedded internal frames (iframes)

Recently, I've been using MATLAB's urlread function to fetch website content for further analysis. However, I encountered a specific site where the data I'm looking for is housed within an internal frame embedded in the main index.php file ...

Strategies for Ensuring Ember JS Waits for Asynchronous Functions to Respond Prior to Rendering

Currently, I'm tackling a project that came to the company through an outsourced channel. My query concerns the rendering of an image src. In the past, images were served from the filesystem. However, we've now transitioned to using AWS S3 bucke ...

When you use jQuery's serialize() method on a form element, it will only serialize one form element at a time

Consider the form below: <form id="form" name="form"> <input name="name"/> <input name="version"/> <input name="template"/> <textarea name="elements"></textarea> <textarea name="features"></textarea> <tex ...

What adjustments need to be made on either the client-side or server-side in order to enable the functionality of getJSON()?

I recently encountered a challenge while working with web services that are hosted on a different domain from the site I am developing. This led me to explore calling these services using ajax, which introduced me to the complexities of the same-origin pol ...

Retrieve a file from an Express API using React with the help of Axios

When working with a React client and an Express API, how can the React client download a file sent by the Express API? Issue: If I manually enter the URL into my browser's address bar and hit enter, the file downloads successfully. However, when I ...

Node.js and Socket.IO: Managing responses

In a unique scenario, the web page is initially served using HTTP. When the submit button is clicked, data is sent to the server and multiple web services are executed, which may take some time. The challenge is to quickly display the response page and the ...

Using the video-js feature to play multiple videos simultaneously

Is it possible to play multiple videos using video-js functionality simultaneously? The answer is yes! Check out Fiddle 1 However, an issue arises when wrapping a trigger, such as a button, around the function that invokes playVideo(). This causes the v ...

The edit form components (dropdown and date input) are failing to load properly

I am currently facing a challenge with my project, specifically with the edit form that opens through a modal. This form consists of 8 text fields, 4 dropdowns (2 of which are dynamic dropdowns as discussed in my previous issue), and a single standard date ...

Encountering an error message stating "Please enable JavaScript to run this application" when making React API calls after deploying a ReactJs app on the Firebase server

I'm currently working on a React JS app that calls various APIs. The backend of this application is a NodeJs server deployed in GCloud. While everything runs smoothly when I test the React app locally, I encountered an issue after deploying it to Fir ...

PHP Query Composer/Reporter

As I work on fine-tuning a web application, the support and explanations from members of this community have been incredibly valuable. I appreciate the assistance in simplifying complex concepts. One feature I wanted to include in my app was the capabilit ...

Automatically formatting text upon entering it in Vue.js

I need assistance with auto-formatting the postal code entered by the user. The rule for the postal code is to use the format A0A 0A0 or 12345. If the user inputs a code like L9V0C7, it should automatically reformat to L9V 0C7. However, if the postal code ...

Switching CSS styles - seeking a smoother integration

I have successfully implemented a JS CSS switcher, which works brilliantly. However, I would like it to function more seamlessly. When opening a new page on the site, the default CSS style sometimes flickers briefly before the selected CSS style is reappli ...

Is there an equivalent of numpy.random.choice in JavaScript?

The Numpy.random.choice function is a handy tool that allows you to select a sample of integers based on a specific probability distribution: >>> np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0]) array([3, 3, 0]) Is there a similar feature in Java ...

Issue with RegisterClientScriptCode function following a partial postback

In a SharePoint website, the code below is contained within a user control: ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "jquery144", "<script type=\"text/javascript\" src=\"/_layouts/Unicre.Web.RUOnline.Controlos/Script ...

Limiting the displayed portion of a table and implementing scrolling instead

I am currently working with a static HTML template that contains the following code: <table> <thead></thead> <tbody></tbody> </table> Using jQuery and AJAX, I am dynamically adding and removing rows and columns ...