What is the best way to create a sliding menu that appears from the right side on a mobile device using HTML, CSS, and JQuery

Is there a way to have the menu slide in smoothly from the right side after clicking on the menu bar icon, including sliding the menu bar icon itself? The current code displays the menu directly upon clicking on the menu bar, but I would like it to slide in smoothly. This functionality needs to work on mobile devices. Can anyone assist me with this?

$(function() {
  var menuVisible = false;
  $('#menuBtn').click(function() {
    if (menuVisible) {
      $('#myMenu').css({
        'display': 'none'
      });
      menuVisible = false;
      return;
    }
    $('#myMenu').css({
      'display': 'block'
    });
    menuVisible = true;
  });
  $('#myMenu').click(function() {
    $(this).css({
      'display': 'none'
    });
    menuVisible = false;
  });
});
body {
  margin: 0;
  padding: 0;
  height: 100%;
}
.menu ul {
  list-style: none;
  float: right;
}
.menu li {
  float: left;
  margin: 10px;
}
.menu li a {
  text-decoration: none;
  color: #333;
  text-transform: uppercase;
}
.menu-bar {
  display: none;
}
@media only screen and (max-width: 768px) {
  .menu-bar {
    display: block;
    float: right;
    cursor: pointer;
    margin: 10px;
  }
  #myMenu {
    display: none;
    z-index: 999;
  }
  .menu ul {
    background-color: red;
    height: 100%;
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    padding: 0px;
    -webkit-box-shadow: 1px 1px 22px 0px rgba(50, 50, 50, 0.25);
    -moz-box-shadow: 1px 1px 22px 0px rgba(50, 50, 50, 0.25);
    box-shadow: 1px 1px 22px 0px rgba(50, 50, 50, 0.25);
  }
  .menu ul li {
    float: none;
    border-bottom: 1px solid #fff;
    width: 100%;
    margin: 20px;
    text-align: left;
  }
  .menu li a {
    padding: 20px;
  }
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="menu">
  <div class="menu-bar">
    <span id="menuBtn"><i class="fa fa-bars" aria-hidden="true"></i></span>
  </div>
  <ul id="myMenu">
    <li><a href="">home</a>
    </li>
    <li><a href="">about</a>
    </li>
    <li><a href="">service</a>
    </li>
    <li><a href="">contact</a>
    </li>
  </ul>
</div>
<div style="position: relative;top: 50px;">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque ut neque dignissim, lobortis nulla sed, tristique urna. Pellentesque placerat, nunc eu feugiat tincidunt, lacus turpis dictum elit, non viverra elit metus at purus. Morbi eleifend
    dui velit, sit amet pretium odio lacinia eget. Nullam mattis massa in nibh laoreet euismod. Phasellus ullamcorper elit quis neque fermentum, at vehicula dolor posuere. Quisque gravida arcu a metus dignissim, vitae convallis ipsum vestibulum. Aliquam
    mollis magna non velit convallis, ut eleifend mauris pharetra. Phasellus ac ipsum pulvinar, dignissim lacus ut, dapibus purus. Integer volutpat ullamcorper magna quis vehicula. Maecenas rhoncus, turpis ac aliquam hendrerit, purus velit pellentesque
    tellus, vitae scelerisque metus leo vestibulum leo. Duis ac vulputate tortor. Aliquam at diam ullamcorper, finibus purus ac, dictum sem. Nulla quis dignissim orci. Donec vel purus eget elit feugiat auctor eget eget odio. Praesent volutpat purus in
    dui aliquam dignissim. Curabitur bibendum lorem id rutrum congue. Nulla urna diam, malesuada ac nibh consequat, auctor egestas ipsum. In non ipsum augue. Maecenas at velit tempus, pellentesque dui non, volutpat tellus. Duis ullamcorper lorem vel blandit
    scelerisque. Etiam venenatis est non urna volutpat, nec commodo neque condimentum. Maecenas sed tortor lacinia, viverra ligula vel, maximus ex. Aenean ut vestibulum lectus. Donec l</p>
</div>

Answer №1

check out this demonstration using simple jQuery

$(function(){
$('#menuBtn').on('click', function(){
if( $(this).hasClass('right_margin') ){
$(this).removeClass('right_margin');
$('#myMenu').removeClass('active');
}else {
$(this).addClass('right_margin');
$('#myMenu').addClass('active');
}


});
  
});
body {
margin: 0;
padding: 0;
height: 100%;
}
.menu ul {
list-style: none;
float: right;
}
.menu li {
float: left;
margin: 10px;
}
.menu li a {
text-decoration: none;
color: #333;
text-transform: uppercase;
}
.menu-bar {
display: none;
}
 @media only screen and (max-width: 768px) {
.menu-bar {
display: block;
float: right;
cursor: pointer;
margin: 10px;

}
#menuBtn {
transition-duration:1s;
-webkit-transition-duration:1s;
-ms-transition-duration:1s;
-moz-transition-duration:1s;
}
#myMenu {
z-index: 999;
transition-duration:1s;
-webkit-transition-duration:1s;
-ms-transition-duration:1s;
-moz-transition-duration:1s;
}
.menu ul {
background-color: red;
height: 100%;
position: fixed;
top: 0;
right: -300px;
bottom: 0;
padding: 0px;
-webkit-box-shadow: 1px 1px 22px 0px rgba(50, 50, 50, 0.25);
-moz-box-shadow: 1px 1px 22px 0px rgba(50, 50, 50, 0.25);
box-shadow: 1px 1px 22px 0px rgba(50, 50, 50, 0.25);
}
.menu ul li {
float: none;
border-bottom: 1px solid #fff;
width: 100%;
margin: 20px;
text-align: left;
}
.menu li a {
padding: 20px;
}
.menu .active {
right:0;
transition-duration:1s;
-webkit-transition-duration:1s;
-ms-transition-duration:1s;
-moz-transition-duration:1s;
}
.right_margin {
margin-right:150px;
transition-duration:1s;
-webkit-transition-duration:1s;
-ms-transition-duration:1s;
-moz-transition-duration:1s;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<div class="menu">
  <div class="menu-bar"> <span id="menuBtn"><i class="fa fa-bars" aria-hidden="true"></i></span> </div>
  <ul id="myMenu">
    <li><a href="">home</a> </li>
    <li><a href="">about</a> </li>
    <li><a href="">service</a> </li>
    <li><a href="">contact</a> </li>
  </ul>
</div>
<div style="width:100%; float:left">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque ut neque dignissim, lobortis nulla sed, tristique urna. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque ut neque dignissim, lobortis nulla sed, tristique
    urna.</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 

Answer №2

One way to add a sliding effect to your website is by utilizing the jQueryUI slide effect. Below is an example of how you can incorporate this feature:

$(function() {
    var menuBtn = $('#menuBtn'), myMenu = $("#myMenu");
    menuBtn.click(function() {
        if ( $("#myMenu").is(":visible") ) {
            menuBtn.removeClass("right_margin");
            myMenu.toggle("slide", {direction: "right"}, 400);
            
            return;
        }
        menuBtn.addClass("right_margin");
        myMenu.toggle("slide", {direction: "right" }, 500);
    });
    
    myMenu.click(function (){
       menuBtn.trigger("click");
    });
});
body{
    margin: 0;
    padding: 0;
    height: 100%;
}
.menu ul
{
list-style: none;
float: right;
}
.menu li{
float: left;
margin: 10px;
}
.menu li a{
text-decoration: none;
color: #333;
text-transform: uppercase;
}

.menu-bar
{
display: none;
}

.right_margin{
  margin-right: 150px; 
  transition-duration:.5s;
  -webkit-transition-duration:.5s;
  -ms-transition-duration:.5s;
  -moz-transition-duration:.5s;
}

@media only screen and (max-width: 768px) {

.menu-bar
{
display: block;
float: right;
cursor: pointer;
margin: 10px;
}
#myMenu
{
display: none;
    z-index: 999;
}
.menu ul{
background-color: red;
height: 100%;
position: fixed; 
    top: 0;
    right: 0;
    bottom: 0;
    padding: 0px;
     -webkit-box-shadow: 1px 1px 22px 0px rgba(50, 50, 50, 0.25);
-moz-box-shadow:    1px 1px 22px 0px rgba(50, 50, 50, 0.25);
box-shadow:         1px 1px 22px 0px rgba(50, 50, 50, 0.25);
}

.menu ul li
{
float: none;
border-bottom:1px solid #fff;
width: 100%; 
margin: 20px;
text-align: left;
}
.menu li a{
padding: 20px;
}


}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="menu">
    <div class="menu-bar">
        <span id="menuBtn"><i class="fa fa-bars" aria-hidden="true"></i></span>
    </div>
    <ul id="myMenu">
        <li><a href="">home</a></li>
        <li><a href="">about</a></li>
        <li><a href="">service</a></li>
        <li><a href="">contact</a></li>
    </ul>
</div>
<div style="position: relative;top: 50px;">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque ut neque dignissim, lobortis nulla sed, tristique urna. Pellentesque placerat, nunc eu feugiat tincidunt, lacus turpis dictum elit, non viverra elit metus at purus...Integer volutpat ullamcorper magna quis vehicula. Maecenas rhoncus, turpis ac aliquam hendrerit, purus velit pellentesque tellus, vitae scelerisque metus leo vestibulum leo. Duis ac vulputate tortor. Aliquam at diam ullamcorper, finibus purus ac, dictum sem.<br/><br/>...

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

Adjust the width of the Bootstrap 5 progress bar in Vue based on the progression of a countdown timer

I am looking to utilize a bootstrap 5 progress bar in order to display the remaining time of a countdown. I have set up the necessary markup within my vuejs component template. <div class="progress"> <div class="progress-bar&quo ...

Split a number in PHP into individual HTML tags for formatting

Is there a way to split the number 12345 into individual digits using PHP like this: <span>1</span> <span>2</span> <span>3</span> <span>4</span> <span>5</span> ...

Trying to access a frame with URL from JavaScript in the same domain in an unsafe manner

I am encountering an issue while attempting to access the URL of the parent window from an iFrame. The error message I received on my server is as follows: Unsafe JavaScript attempt to access frame with URL from frame with URL . The frame being acc ...

The error message "THREE is not defined" occurred while running mocha tests for a

I am attempting to execute a basic Mocha unit test for code that utilizes the Vector3 class from THREE.js: import {Vector3} from 'three'; const a = new Vector3(0, 0, 0); When running this test using Mocha (specifically mocha-webpack, with webpa ...

Utilize pivot to manage user roles and permissions in ExpressJS application using Mongoose

My user schema is structured as shown below const userSchema = mongoose.Schema({ username: { type: String, required: true, }, first_name: { type: String, required: true, }, last_name: { type: Stri ...

Differentiate between minimum and maximum values on ion-range sliders with discrete color options

I am currently working on customizing the theme of my ionic app, specifically trying to assign different colors to the min and max knobs on an ion-range component. At the moment, I am only able to apply a single HTML property called "color" to the selector ...

Tips for Resizing and Reviving Divs with jQuery

I have recently ventured into the world of web development to assist a family member with their website. My knowledge and experience are limited, but I am facing an interesting challenge. I am trying to manipulate certain divs as users scroll down the page ...

transferring a LatLng variable from one function to initialize Google Maps

I have a database in firebase that stores latitude and longitude values which I retrieve as the variable coords. function getCoords() { var place_data= firebase.database().ref("/place/name"); place_data.once('value').then(function(snaps ...

Switching the active className in React and Next.js based on selection status

My goal is to dynamically change the className of each Card component when clicked on. When one Card is selected, the others should revert back to their default className. This is my UserBookingData component: const UserBookingData = ({ bookings }: any) = ...

What could be causing my redux-observable to not be triggered as expected?

Currently diving into the world of RxJS and Redux Observables within Redux, attempting to grasp the concepts by implementing a basic fetch example. This is how I've configured my store: import { applyMiddleware, createStore } from 'redux' ...

Adjusting background-position-x while scrolling

I came across Ian Lunn's Parallax tutorial and found it really interesting. The tutorial can be accessed at . My goal is to enhance the effect by not only changing the y-position of the background but also adding horizontal movement based on scroll in ...

The functionality of string replacement is ineffective in the Safari browser

When using the code "MM/DD/YYYY".replace(/.?YYYY.?/, ''); , Chrome displays MM/DD, while Safari shows an empty string. Why does this difference occur? Is there a method that will produce consistent results across all browsers? ...

Utilizing Vue: Attaching click event to dynamically added elements

I am working on a Vue application that retrieves HTML content from an API. This HTML contains blocks with the class <div class="play-video">...</div> Using axios to call the API and a promise, I insert the content into the DOM like this: < ...

Regular expressions: Capturing characters that come after and before a designated symbol

Is there a way to extract all letters, both before and after an underline "_", in JavaScript using Regex while excluding specific words like "pi", "\Delta" and "\Sigma"? How can this be achieved in Regex JS? /\b([^e|_|\d|\W])&bso ...

Unsure about the approach to handle this PHP/JSON object in Javascript/jQuery

From my understanding, I have generated a JSON object using PHP's json_encode function and displayed it using echo. As a result, I can directly access this object in JavaScript as an object. Here is an example: .done(function(response) { var ...

Issue with cross-origin security when applying HTML5 video tag to a webGL texture

I am trying to link a remote video to a texture in WebGL. To allow the video source to be different from the document source, I added Access-Control-Allow-Origin:* to the http headers of the video source. Additionally, I set an anonymous origin for the vid ...

Creating a mobile-friendly navigation bar with Vuetify for optimal responsiveness

I am attempting to utilize a vuetify tab component as my navigation menu in order to create a responsive navbar using vuetify. The goal is to have a normal navbar that functions like usual, but when viewed on a mobile device, it should hide the menu and di ...

Pause the execution of an AJAX callback function after numerous AJAX requests

I have two separate Ajax calls in my code. Both of them have different callbacks that need to execute upon successful call. $.ajax({ type: 'POST', url: "url1", success: foo1 }); $.ajax({ type: 'POST', url: "url2", ...

Identifying the specific npm script command that was executed

My index.js file contains scripts that can be executed like the ones below: "scripts": { "lint": "eslint .", "serve": "firebase emulators:start --only functions", "inspect": "firebase emulators:start --inspect-functions", "deploy": "fire ...

Utilizing CodeIgniter to Retrieve Data Array within AJAX Success Callback

I'm facing an issue with accessing the array returned from the controller in the AJAX success function. Below is my controller code: function get_slot() { $fac_id = 1; $date = $this->input->post('date'); $this->load-& ...