Toggle display of menu using jQuery

My webpage has a layout where the content is on the left and the sidebar is on the right. When the screen width is less than or equal to 480px, the two divs are stacked one under the other at 100% widths. There's a "Show/Hide" button that appears to toggle the visibility of the sidebar when clicked. To achieve this, I'm using the code:

$(".sidebar .box").slideToggle(200);

You can see everything in action on this jsfiddle link.

The issue I'm facing is that when I switch from wide screen to narrow screen (width <= 480px) and click the button again, it causes a back and forth bug.

I'm trying to figure out where I've gone wrong. Any help would be appreciated!

Answer №1

It seems that the issue lies in this particular code snippet:

$("a.expander").click(function () {
    $(this).toggleClass('close');
    $(".sidebar .box").slideToggle(200);
});

Every time the showSidebar function is triggered, which happens whenever the window is resized, the above code gets executed. JQuery's click function actually adds a new event handler each time, leading to multiple executions of all handlers upon window resize.

To resolve this problem, the click handler registration should be moved outside of the function.

Answer №2

It seems like the issue you are facing is that the slide function is being triggered repeatedly when the window is resized. To prevent this from happening uncontrollably, consider using an event handler to manage it more effectively:

Try using .one():

$('#your_element_id').one("click", function () {     
    $('.your_css_style_class').slideToggle(200); 
});

Additionally, if you plan on initially displaying the element as hidden and then revealing it later, consider using .slideDown() instead of .slideToggle() at the outset.

For further information on the 'one' function in jQuery, refer to: http://api.jquery.com/one

Answer №3

Is this the kind of solution you were looking for? http://jsfiddle.net/jqdvj42u/3/

$(document).ready(function() {
     $("a.expander").click(function () {
        $(this).toggleClass('close');
        $(".sidebar .box").slideToggle(200);
    });
});

function showSidebar() {   
    if ($(window).width() <= 480) {
        // Close sidebar when window width <= 480px
        $(".sidebar .box").removeClass('open');
        // Click expander button to show/hide sidebar

    } else {
        $("a.expander").removeClass('close');
        // Open sidebar when window width > 480px;
        $(".sidebar .box").addClass('open');
    }
}
showSidebar();

$(window).resize(showSidebar);

It is important that your click event is not called within the showSidebar() function to avoid binding the click event multiple times whenever the function is executed. The resize method can trigger showSidebar() multiple times, leading to multiple bindings of the click event. Additionally, it is recommended to use jQuery version 1.11 or higher for better compatibility, especially if support for IE<9 is required. If compatibility with IE<9 is not necessary, jQuery version 2.0 or higher can be used.

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

Saving content with the CKEditor BalloonEditor using Ajax

I've been experimenting with CKEditor5, but I'm having trouble making it work. Here's the code I'm using: <div name="content" id="editor" onblur="saveOnBlur(1,'alias')"> <p>Here's the initial content of the e ...

Create a function that is determined by a specific hyperlink

I am looking to create a universal function that can work with all types of links on my pages. For example: If I click on a .pdf link, it should open a PDF viewer. If I click on a .mp3 link, it should open an audio player, and so on. However, I want to ...

Retrieve the value and attribute of a checkbox using jQuery, then send the data to the server

I need to extract the value and attributes of each selected checkbox in my multiple checkbox setup. <input type="checkbox" name="access[]" id="configuration" value="configuration" data-text="Configuration&quo ...

What is the reason for the inclusion of [Circular] in the hash?

Below is the code snippet: db.query(str, arr, function selectCb(error, results, fields) { if (error) { return proceed(false, {errno:'010',message:error.message}, request); } var q = async.queue ...

An issue arising from code in Python, JavaScript, HTML, and CSS

I am currently studying JavaScript and Python and have encountered an issue with my code. I wrote a script that is supposed to create a file and input data into it, but the recv_data function is not functioning correctly - the file is not being created. Ca ...

Add United States as an additional attribute to the countries retrieved from the API

I am working with an API that provides data in a specific format: [ { "id": 12, "acf": { "address": { "city": "Bandar Penawar", "state": "Johor", "country ...

Stop the jQuery addon from being loaded multiple times

Utilizing AJAX allows me to update my page content without the need to refresh the entire page, which means that specific scripts and addons for each page are also loaded via AJAX. The issue I am facing involves the Google Maps API. I have had to include ...

The issue of selecting multiple classes simultaneously is not being resolved

Here is my JavaScript code snippet: $('.normal-box').click(function(){ //unique row id var id = $(this).data('row-id'); //its index according to the content array var index = $(this).data('index'); //which car ...

When a single column is achieved, aligning with justify-content space-between

I'm working on styling a div that has two children using flexbox and flex-wrap. I want the layout to adjust without needing media queries - so that when it reaches a certain width, the children are spaced evenly (justify-content: space-between), but w ...

Preventing Component Duplication in Vue.js: Tips to Avoid Displaying Two Instances on the Screen

After developing a Vue app in VS Code, I encountered an issue where the home component was rendered twice on the screen when attempting to run the application. Below is a screenshot of the resulting homepage: Here is the code from Home.vue: ...

Ensure that clicking on an element closes any currently visible elements before opening a new element

Take a look at my code snippet below. I am working on creating multiple clickable divs that reveal different content when clicked. However, the issue I am facing is that currently, both content blocks can be displayed simultaneously. My goal is to have onl ...

"Create a dynamic HTML newsletter utilizing tables similar to the responsive design principles

Looking to create a mobile-responsive newsletter using my style.css <table cellpadding="0" cellspacing="0" border="0" align="center" width="600" bgcolor="#fff"> <tbody> <tr> <td style="padding-bottom:5px" valign="top"&g ...

CSS Priority - determining the ultimate winner

I have an upcoming exam and I'm reviewing the previous exam paper that was given to me. The question is: When multiple style sheet rules are applied to the same element, which type of rule takes precedence? a. Any declaration from the browser b. ...

Is it possible to implement an automatic clicking function on a bootstrap navigation bar similar to a carousel?

I am working on a website with a bootstrap navigation bar similar to the one shown in this image : bootstrap nav <ul class="nav nav-tabs" id="tab_home" role="tablist"> <li class="nav-item" role="pres ...

Adding a Key Value pair to every object within an Array using TypeScript

I have two arrays - one contains dates and the other contains objects. My goal is to include the dates as a key value pair in each object, like this: {"Date": "10-12-18"}. dates: ["10-12-18", "10-13-18", 10-14-18"] data: [ {"name":"One", "age": "4"} ...

How can I create a customized placeholder effect for the Paytm login page text box?

Looking to create a placeholder effect on the text boxes for a Paytm login page? https://i.sstatic.net/sox0a.png ...

import the JSON file into a variable object

I am currently working with a jquery function that is structured like this: <script type="text/javascript"> var doubleEliminationData = {} $(function () { $('div#doubleElimination').bracket({ init: doubleEliminationData }) ...

Javascript error when attempting to add leading zeros

Is there a way to utilize JavaScript or JQuery in order to prepend a zero to this script? for (im=1;im<=31;im++){ days[im]=everyDay[im]; } ...

Sharing JSON data between two Backbone views

Could you provide some guidance on how to pass dynamic JSON data from one view to another? In the initial view, I am creating the JSON object using the following syntax: json.push({ first: value, second: value }); ...

Retrieve a non-existent property from an object using the forEach method

Within my data array, I have a collection of objects with varying properties. Some objects may have all the properties while others might be missing certain ones. const data = [ { car: 12, airplane: 42, peoples: 2, }, ...