Toggling the `toggleClass` on a fixed element when clicking a link (such as in an off canvas menu) can

As per the following markup code, there is a sticky navigation bar (menu-bar) that reveals an off-canvas menu using CSS transitions when the button is clicked by adding a class (slide-wrapper__open) to the HTML element.

HTML

    <div class="menu-bar">
    <div class="menu-btn">
        <a href="" class="menu-btn__toggle">
            <i class="fa fa-bars"></i>
        </a>
    </div>
</div>

<div class="slide-wrapper">
    <nav class="nav-menu">
        <ul class="nav-menu__menu">

        </ul>
    </nav>
</div>

CSS

@import "../modules/mixins";

.menu-bar {
  @include mobile {
    width: 100%;
    height: 50px;
    position: fixed;
    border-bottom: 1px solid $lightGreyBorder;
    background: white;
    z-index: 100;
  }
  @include tablet {
   display:none;
  }
  @include tablet-land {
    display:none;
  }
  @include desktop {
    display: none;
  }
}

.menu-btn {
  @include mobile {
    height: inherit;
    width: 50px;
    text-align: center;
    line-height: 50px;
    font-size: 1.4rem;
    float: right;
  }
}

.slide-wrapper {
  @include mobile {
    width:80%;
    position: fixed;
    top: 0;
    right: 0;
    height: 100%;
    z-index: 0;

  }
  @include tablet {
   display:none;
  }
  @include tablet-land {
    display:none;
  }
  @include desktop {
    display: none;
  }

  .nav-menu {
    @include mobile {
      position: absolute;
      background: rgba(0,0,0,0.65);
      width: 100%;
      right: -100%;
      height: 100%;
      transition: ease 0.5s all;
    }
  }
}

.slide-wrapper__open {
  .page {
    @include mobile {
      right: 80%;
      transition: ease 0.5s all;
      overflow: hidden;
    }
  }
  .slide-wrapper {
    right: 0;
    top: 0;
    height: 100%;
    z-index: 0;

    .nav-menu {
      @include mobile {
        right: 0%;
        transition: ease 0.5 all;
      }
    }

  }
}

.page {
  @include mobile {
    width: 100%;
    height: 100vh;
    position: relative;
    right: 0;
    transition: ease 0.6s all;
  }
}

JS

$(".class").click(function(e){ //stack overflow is giving me code errors but the class name i used was the correct one.
    e.preventDefault();
    $("html").toggleClass("slide-wrapper__open");
});

However, clicking the link causes the page to scroll all the way to the top of the page and opens the off-canvas menu. Removing the toggle class prevents scrolling but also hides the menu. The issue could be related to CSS transitions or the toggleClass function. Various attempts have been made to solve this issue, such as using return false, #! in the link, or scrolling back to the click position ($(document).scrollTop(SCROLL_POS);). However, these solutions only partially work when the menu is closed; if open (class added to html tag), it still scrolls to the top of the page.

If you have any advice or solutions to this problem, your input would be greatly appreciated.

Thank you

EDIT - Original

ORIGINAL JS FIDDLE

EDIT - Working

WORKING JS FIDDLE

Answer №1

It seems that the default behavior of the browser is causing this issue because of the href="". And considering that using preventDefault may not completely solve the problem, the best approach would be to simply return a void to DOM. Give this solution a try if you haven't already:

<a href="javascript:void(0);" class="menu-btn__toggle">
    <i class="fa fa-bars"></i>
</a>

Answer №2

To determine if the issue you're facing is related to a link, simply check to see if clicking on your div results in adding a hash to the URL. A lone hash functions similarly to "_top," so sometimes appending something to the anchor (even a dummy number) can resolve the problem.

However, if no hash is added (indicating that the default event is indeed being prevented), it may be due to a CSS issue such as the document's height scaling down below the window's height because of relative positioning.

If possible, adjusting the HTML slightly by placing a span tag within an a element and applying a click event with event.stopPropagation() to it could solve the problem. stopPropagation ensures the event does not propagate up to the a tag, preventing any default actions set on the a tag from triggering at all.

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

Cufon: Hovering on links causes them to resize and remain in that new size

I've encountered an issue with text links in a paragraph that are being replaced using Cufon. When I hover over the links, the text inside them expands and remains that way even after moving the cursor away. The color change applied to the hover state ...

Why is it that lists always begin outside of the enclosing element?

I've always found this incredibly frustrating. Why do lists behave this way? When you set the margin and padding to 0, you would expect them to align normally with the surrounding text on the left, right? But no. That's where the text within the ...

Adsense ad unit is not responsive and fails to display properly at dimensions of 320x50 px

I have a unique banner ad that I want to display as the footer on my responsive website. Using media queries recommended in the advertising documentation, I am adjusting the size based on different screen widths. Check out the CSS code below: <style&g ...

Can onerror be triggered on an HTML Image onload event?

Having an html image labeled as follows: <image src = 'image.png' onerror = "handleError(this)" onload = "handleLoad(this)"> function handleError(n){ getFirstChild(n.parentNode).style.display = '',n.style.display ...

The hover indicator in Highcharts donut pie chart is not displayed when the slice color is white

My problem lies with the white slice of the donut chart. To better understand the issue, take a look at my code and screenshots below: Here is the code snippet: document.addEventListener("DOMContentLoaded", function() { var chart1 = new Highcharts.Char ...

Issue with Foundation6 popup form: Unwanted loss of focus on field when revealed (possibly due to jQuery

While developing a popup form using Foundation6 reveal, I encountered a JavaScript issue that seems to be related to event binding or handling in jQuery.js / Foundation.js. https://i.stack.imgur.com/MIWUS.png When I click on any field within the reveal w ...

Choose an option with JavaScript once the request is successful

Choose the day, month, and year using JSON data success: function(jsondata){ var data=JSON.parse(jsondata); var list_html="<div id='editrelation'><label id='dateLabel' style='display:none&apo ...

When the window width increases, the image within a flexbox causes the flexbox to break

I'm currently working on designing a responsive splash page that covers most of the page (90vh). The layout includes a logo at the top and a simple paragraph at the bottom. I've experimented with using flex-shrink and flex-basis, but it's n ...

Is it acceptable to store HTML in a content database?

I am considering storing HTML in a database, but I want to ensure it is safe. If I restrict who can submit the content, do you think it would be secure enough? My question is quite straightforward. I run a platform that provides video tutorials and variou ...

Retrieve postal code using longitude and latitude data from Google's API

I am currently working on a project that requires obtaining a postcode from longitude and latitude coordinates. Utilizing the Google Maps API, I'm able to retrieve the longitude and latitude based on a search term like 'Manchester'. After t ...

Adjusting AngularJS scroll position based on key presses

I am currently working on an autocomplete feature using AngularJS. I seem to be experiencing a problem with the scrollbar behavior. In the interactive gif provided, you can observe that the scrollbar remains stationary when navigating with the arrow keys. ...

Keep running PHP code following an Ajax request

I am dealing with a block of HTML code that needs to be replaced by an Ajax call. Here is the initial HTML code: <div class="box-body" id="mcontent"> <?php if (isset($_POST["id"])){ $id = $_POST["id" ...

Price Table with Unique CSS3 Design Shapes

I'm currently working on designing a price table that resembles a bone shape. I stumbled upon some code on CodePen that could help me achieve this look, but I'm unsure of how to tweak and merge it. I'm facing difficulties when it comes to s ...

Unable to eliminate the border gaps in the table

I'm having trouble getting the picture and grey area in the example attached to stay together and be the same height. The border-spacing seems to be causing an issue. Any suggestions on how to fix this? Apologies for the messy style sheet. Here' ...

Accordion section appears on the webpage as it is loaded

I am currently working on implementing an accordion feature for my webpage. Everything is functioning correctly when I click the button, but there is one issue - the div opens automatically when the page loads. My goal is to have the div closed initially a ...

Ways to retrieve AJAX variables from outside the AJAX function

$(document).ready(function() { var items; $.ajax({ url: 'item/getProducts', dataType: 'json', success: function(data){ items=data; ...

Utilizing the Masonry jQuery plugin for optimizing empty spaces

Recently, I came across the Masonry plugin and I'm considering using it in a project. One question that intrigues me is whether there is a way to detect empty spaces that occasionally show up in the layout when divs are positioned. Being able to ident ...

Dealing with a Jquery/Javascript Dilemma

As a beginner in query/javascript, I am encountering an issue with the code below when trying to calculate gross value and tax amount based on the net amount entered by the user. The input is expected to be a double amount, with gross and VAT amounts defin ...

Error in onchange event due to incorrect index variable

My goal is to add onchange events to select tags within a div that contains multiple tags. To achieve this, I am using a for loop to attach events to each tag. The purpose of these events is to update a select tag in another container by removing the "disa ...

Is there a way to add a background image similar to that?

Take a peek at the following site: . Notice how, as you scroll down, the background image appears to be fixed. It's almost like one of the pages acts as a window allowing you to see the background image. How can I achieve this cool effect? ...