How can I close the sidebar with a single tap anywhere outside of it?

Is there a way to hide the sidebar when clicking anywhere on the screen?

Can I show text when hovering over an image instead of having it always visible?

function openNav() {
  document.getElementById("mySidenav").style.width = "300px";
  document.getElementById("toggle").style.position = "static";
}

function closeNav() {
  document.getElementById("mySidenav").style.width = "0";
  document.getElementById("toggle").style.marginRight = "0";
  document.getElementById("toggle").style.position = "relative";
}
#toggle {
  position: relative;
  left: 400px;
  font-size: 1.2em;
  visibility: visible;
}

#toggle:hover {
  color: white;
  transition: 0.5s;
}

.sidenav {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  right: 0;
  background-color: transparent;
  overflow-x: hidden;
  transition: 0.5s;
  padding-top: 50px;
}

.sidenav a {
  text-decoration: none;
  font-size: 25px;
  color: #818181;
  display: block;
  transition: 0.3s;
}

.sidenav a:hover,
.offcanvas a:focus {
  color: #f1f1f1;
}

.sidenav .closebtn {
  position: absolute;
  top: 0;
  right: 25px;
  font-size: 36px;
  margin-left: 50px;
}
<div>
  <ul id="topBar">
    <li id="ixora">Ixora</li>
    <li class="lists">2014</li>
    <li class="lists">2015</li>
    <li id="toggle" onclick="openNav() ">&#9776;</li>
  </ul>
</div>

<div id="mySidenav" class="sidenav">
  <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
  <span class="textImage">Outing</span>
  <a href="#" class="images"><img src="outing.jpg"></a>

  <span class="textImage">Prom Night</span>
  <a href="#" class="images"><img src="prom.jpg"></a>

  <span class="textImage">PortDickson Trip</span>
  <a href="#" class="images"><img src="pd.jpg"></a>

  <span class="textImage">Merdeka</span>
  <a href="#" class="images"><img src="merdeka%20(2).jpg"></a>
</div>

Answer №1

In my opinion, utilizing jQuery for DOM manipulation is the way to go due to its efficiency. However, if you must resort to vanilla JavaScript, the process may become more challenging.

Integrating jQuery into your project is a straightforward task, and you can find detailed instructions on the jQuery site. Here's a comparison between selecting an element in JavaScript and jQuery:

Vanilla JavaScript:

document.getElementById("mySidenav")

jQuery:

$('#mySidenav')

When it comes to responding to events such as button clicks or menu interactions, setting up event handlers is essential.

Without proper CSS styling for #topBar in your code, visualizing your site might be challenging (here's your code running in jsfiddle).

For instance, if you have a button with the ID of #openToggle, you can configure your sideNav in CSS with the required dimensions and visibility set to 'none'. Then, you create an event handler like this:

//event handlers are typically placed at the end of your script
$('#openMenu').on('click', openMenu);

This example indicates that when the element with the ID 'openMenu' is clicked, the 'openMenu' function will be executed.

The openMenu function could be as simple as:

function openMenu() {
   var $menu = $('#sideNav');
   $menu.show();
};

Alternatively, a toggle function can be implemented to switch between opening and closing the menu:

function toggleMenu() {
  var $menu = $('#sideNav');

  if (($menu).is(':visible')) {
    $menu.hide();
  } else {
    $menu.show();
  }
};

// event handler for menu toggle button
$('#menuToggle').on('click', toggleMenu);

To close the menu when clicking away from it, you can utilize jQuery's .one() function along with a body click event handler:

// event handler for menu toggle button
$('#menuToggle').on('click', toggleMenu);
$('body').one('click', toggleMenu);

Another option is to have the menu close when the mouse leaves the menu area:

//event handlers
$('#menuToggle').on('click', toggleMenu);
$('#sideNav').mouseleave(toggleMenu);

The mouseleave handler triggers the toggleMenu function when the mouse pointer exits the element with the ID 'sideNav'.

As a beginner myself, my examples might not be perfect, but I hope they provide some assistance. Hopefully, experienced JavaScript developers will offer more insights or improved examples soon.

Cheers, Dave

Answer №2

JQuery Events

$( document ).onclick(function() {
    $("#mySidenav").slideUp();
}

Check out these helpful resources:

Answer №3

Utilizing javascript gives you the ability to perform the following actions:

document.onclick = function(e){
    if(e.target.id == "mySidenav"){
        return false;
    }

    closeNav();
}

Answer №4

Your sidebar already has functions for opening and closing it. Clicking "anywhere" is essentially the same as clicking on the body, but I understand if you don't want the sidebar to close when clicking on it.

Here's a solution for you:

var myNav = document.getElementById("mySidenav");

myNav.onclick = function(e) {
  e.stopPropagation();
}

document.body.onclick = function(e) {
  closeNav();
}

By implementing this code, clicking on the sidebar will not trigger the body event as we have stopped event propagation. Clicking elsewhere will still close your sidebar as intended.

Hope this explanation is helpful,

Warm regards

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

What could be causing the issue with this flexbox footer not functioning properly on a mobile device?

Currently, I am honing my skills in using flexbox to create footers. Although the footer layout I have designed looks great on a desktop screen, it unfortunately doesn't display correctly on mobile devices. You can view the footer layout I have been ...

Error during compilation in npm (symbol '_' is not recognized)

After updating all the dependencies in my JavaScript program without making any changes to my components, I encountered an error when running: npm run build The error specifically mentions a problem with one of my components: Failed to compile. ./src/c ...

Example using three.js showing issues with external resources failing to load on jsfiddle.net

Currently, I am endeavoring to make progress with this sample project: github.com/josdirksen/learning-threejs/blob/master/chapter-09/07-first-person-camera.html I have made attempts at replicating the code on my personal pages.github.io account and also m ...

Vuetify Autocomplete that allows for adding values not in the predefined list

I am utilizing a vuetify autocomplete component to showcase a list of names for users to select from. In the case where a user enters a name not on the list, I want to ensure that value is still accepted. Check out my code snippet below: <v-autocomplete ...

Error: Cannot run yarn dev because node_modules/node/bin/node is missing

While running Next.js on my Windows machine, I am noticing that the file path is displaying as if it were a Linux path. I have already configured the node file path in the environment variable, but I'm still encountering the following error: yarn run ...

From where was this color of the navigation bar derived?

As I delve into a site previously worked on by someone else, my task is to recreate the navigation they implemented. However, I am unable to locate in the source code what was used for the navigation background. The challenge lies in the fact that after m ...

Different methods for incorporating script-specific data into markup

How can we include extra meta data in HTML code to support client-side javascript functionality? Let's consider some straightforward examples: A list of contacts that, when clicked, displays their location on a map. For instance, how can we link la ...

Working with Typescript to map and sort the key values of a new datasource object

Managing a large datasource filled with objects can be challenging. My goal is to rearrange the order of objects in the array based on new values for each key. Whenever a new value for a key is found, I want the corresponding object to move to the top of t ...

Struggling to make vue-i18n function properly with nuxt generate?

In an effort to enhance my skills, I am creating a small Nuxt project from scratch. While the project runs smoothly on the local server, I have encountered an issue with the language switcher not updating the translation fields when using nuxt generate. U ...

Utilizing MongoDB for data transfers: uploading and downloading

I successfully configured my localhost to upload files to Mongo DB using server.js //I have configured my ID and PW const mongoURI = "mongodb+srv://myID:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a2cfdbf2f5e2c1ced7d1 ...

Creating a default menu within a specific route in Ember.js is a crucial step in

I have created a JSBin code for my Ember.js application which can be found here: When I click on Item A, I want the ABCD menu on the left to remain visible and not disappear. Thank you. ...

Consider using React Components as an alternative to implementing pagination dots within Swiperjs, as it may help resolve the issue displaying

I seem to be encountering a small issue and I believe I am making a mistake somewhere. How can I replace the default dots with custom elements for pagination in Swiperjs for React? The custom element should return an SVG from an array of icons. Initially ...

What could be the reason for PassportJS in Node failing to clear the session upon logout?

I am encountering an issue with my system not successfully logging out using PassportJS. The logout route appears to be triggered, but the session is not being removed as intended. I would like it to return a 401 error if the user is not logged in on a spe ...

Center and justify image inside flexbox using MUI

Can someone explain why my image appears centered but not justified? I'm feeling confused about this. <Box sx={{ display: 'flex', minHeight: '100vh', alignItems: 'center', flexGrow ...

passport.js and express: TypeError - Router.use() must be given a middleware function, but instead received a ' + gettype(fn)

I encountered an error while using passport.js with Express.js TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) This issue arose from the following code: passport/local.js var LocalStrategy = require("passport ...

Guide to integrating a static page with personalized CSS and JavaScript resources within a Rails project

Currently, I am developing a simple Rails application (using Rails version 4.1) and I am looking to incorporate a static page into it. The static page is structured as follows: | |- index.html |- css folder |-- (various css files) |- js folder |-- (some j ...

No response from jQuery's $.getJSON() function

I'm currently experimenting with jQuery by using a script that I wrote. As a beginner in learning jQuery, I am trying to read data from a .json file and display it in a div. function jQuerytest() { $.getJSON( "books/testbook/pageIndex.json", func ...

How to prevent table row from highlighting on hover in Angular Bootstrap

In my project, I have a table that showcases various details and allows users to select certain rows. Some of these rows have child rows which can also be selected. The requirement is for the parent rows to be selectable only if they do not have any child ...

Having trouble with your jQuery code not loading properly?

Currently working on debugging jQuery code and facing an issue where a particular section of the code is not being triggered upon clicking. The HTML/PHP in question: $cartlink .= "<a class='add_to_cart button' data-id='{$product->id} ...

What is the best way to extract the HTML input id using observeEvent in shiny?

How can I capture the HTML input id using observeEvent in shiny? shinyApp( ui = basicPage( HTML('<input type="button" name = "b1" value="Travel time"/>')), server = function(input, output, session) { o ...