I am noticing that my popover is causing my page to shift when I click it. It is expanding the width of my page more than I would

Upon clicking the user id popover on my page, it expands the page width instead of adjusting within the page boundaries.

This is the issue: https://i.stack.imgur.com/EqaMo.png

There's a small white space present that I want to eliminate. When the popover is closed, everything looks fine: https://i.stack.imgur.com/iM672.png

How can I correct this formatting?

Below is the popover component code snippet:

import * as React from "react";
import Popover from "@mui/material/Popover";
import Typography from "@mui/material/Typography";
import AccountCircleIcon from "@mui/icons-material/AccountCircle";
import { IconButton } from "@mui/material";
import navStyles from "../styles/Nav.module.css";
export default function BasicPopover() {
  const [anchorEl, setAnchorEl] = React.useState(null);

  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  const open = Boolean(anchorEl);
  const id = open ? "simple-popover" : undefined;

  return (
    <div>
      <IconButton
        aria-describedby={id}
        variant="contained"
        onClick={handleClick}
      >
        <AccountCircleIcon className={navStyles.pfp} />
      </IconButton>
      <Popover
        id={id}
        open={open}
        anchorEl={anchorEl}
        onClose={handleClose}
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "left",
        }}
      >
        <Typography sx={{ p: 0, m: 0 }}>
          <ul>
            <li>Login/Logout</li>
            <li>Account</li>
            <li>Your Trips</li>
            <li>Help</li>
            <li>Settings</li>
          </ul>
        </Typography>
      </Popover>
    </div>
  );
}

Here is the navigation component code snippet:

import Link from "next/link";
import navStyles from "../styles/Nav.module.css";
import AccountMenu from "../components/AccountMenu.js";
import { useAuth } from "./contexts/userContext";
import { useRouter } from "next/router";

const Nav = () => {
  const { logout, user } = useAuth();
  const router = useRouter();

  async function handleLogout() {
    try {
      await logout();
      console.log("logged out");
      router.push("/");
    } catch (err) {
      alert(err);
    }
  }

  return (
    <nav className={navStyles.nav}>
      <ul>
        <li>
          <Link href="/">
            <img
              className={navStyles.logo}
              src="/blue.png"
              style={{ cursor: "pointer" }}
            />
          </Link>
        </li>
        <li>
          <Link href="/Properties">Properties</Link>
        </li>
      </ul>
      <ul style={{ margin: "0px", padding: "0px" }}>
        {!user ? (
          <li style={{ margin: "0px", padding: "0px" }}>
            <Link href="/Authentication/Login">Login </Link>
          </li>
        ) : (
          <div>
            <div style={{ color: "green" }}>Welcome {user?.email} </div>
            <li>
              <Link href="/Account">Account</Link>
            </li>
            <div
              onClick={handleLogout}
              style={{ color: "black", cursor: "pointer" }}
            >
              Logout
            </div>
          </div>
        )}
        <li style={{ margin: "0px" }}>
          <AccountMenu className={navStyles.pfp} />
        </li>
      </ul>
    </nav>
  );
};
export default Nav;

Answer №1

https://codepen.io/michelle-m/pen/kOjAMXw

Here is a helpful solution!

/* Implementing a toggle function for dropdown menu */
function toggleDropdown() {
  document.getElementById("myDropdown").classList.toggle("show");
}

// Hide the dropdown menu if clicked outside
window.onclick = function(event) {
  if (!event.target.matches('.btn-dropdown')) {
    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}
.dropdown button {
     background: url('https://www.example.com/images/icon.png') no-repeat;
        cursor: pointer;
        width: 100px;
        height: 100px;
  background-size: contain;
        border: none;
}
.dropdown {
position: absolute;
  right: 0%;
}
.username_left {
  color: black;
  font-size: 16px;
  border: none;
  border-radius: 10px;
  background: none;
  cursor: pointer;
}

.username_left:hover, .dropbtn:focus {
  background-color: none;
  color: #ffcfcf;
}

.dropdown {
  display: inline-block;
  float: left;
}

.dropdown-content {
  display: none;
  position: absolute;
  min-width: 160px;
  background: #fffffff2;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
 right: 0%;
min-height: auto;
}

.dropdown-content a {
  color: black;
  padding: 16px;
  text-decoration: none;
  display: block;
  font-size: 14px;
  font-family: 'Roboto';
}

.dropdown-content a:hover {
  color: indianred;
}

.show {display:block;}
.container {
float: right;
  margin-right: 20px;
}
* {
  margin: 0;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  </head>
  <body>
<div class="container">
<div class="dropdown"> <button onclick="toggleDropdown()" class="username_left">
 
</button>

<div id="myDropdown" class="dropdown-content">
<a href="' . $v_user . '">My Profile</a>
    <a href="#">Switch Account</a>
    <a href="logout">Sign out</a>
  </div></div></div>
</body></html>

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

Simple integration of JSP, JSON, and AJAX

I need help testing a simple login functionality using AJAX. Here's the code snippet: <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Login Test Page</title> <script src="../js/j ...

Upon receiving the ajax request, the entire code page is called back

I'm having trouble saving data using a button in Laravel. When I use console.log, the entire code appears in the console and I don't understand why this is happening. Here is my input field and button: <form action="{{ url('sendcom& ...

Issue with horizontal navigation in CSS

I'm struggling with styling my CSS navigation bar. The last list item is moving to a second line, which really messes up the look of my website. Can someone take a look at my code and point out what I'm doing wrong? Thank you in advance. HTML: ...

In my attempts to retrieve specific statistics from the PokeAPI using Axios and Node.js, I encountered an error

Having an issue while trying to utilize the Pokemon API. Whenever attempting to access the attack, HP and speed stats, all Pokemons show up as undefined! Can someone please point out what might be wrong with my API call? const axios = require('axios&a ...

The svh/lvh units are experiencing unexpected issues when using Chrome on an iPhone

I'm facing an issue with my hero section that is supposed to take up the full height of the viewport. I recently tried using the new svh/lvh units, which seemed to work fine on desktop and Safari for mobile. However, when testing on Chrome for mobile ...

Activate the parent navigation link when on sub-pages

I want to ensure that the parent navigation item is highlighted when a user is on a child page based on the URL. For example, if the user is currently viewing foo1-child and the parent is foo1, I need to apply the active class to Foo 1: http://foo.com/foo ...

Invoking a JavaScript function within a different JavaScript function

Is there a way to ensure that the JavaScript function works properly even when using a text editor? var editor = $('#CKEditor1').ckeditorGet(); editor.on("instanceReady", function () { this.document.on("keydown", function (event) { ...

Thumbnail Carousel Caption in Bootstrap 3

Is it possible to create a Bootstrap 3 carousel where the image changes when the mouse cursor hovers over the thumbnail under the carousel? Currently, I have a setup with the carousel and thumbnails below it. Typically in Bootstrap, the image changes autom ...

Is there a method in VBA to access elements generated by javascript code?

After spending several hours conducting thorough research on Google (including browsing StackOverflow), I've been trying to find a method that would allow me to target HTML elements generated by JavaScript in VBA. For instance, using ie.Document.getE ...

Learn the art of generating multiple dynamic functions with return values and executing them concurrently

I am currently working on a project where I need to dynamically create multiple functions and run them in parallel. My starting point is an array that contains several strings, each of which will be used as input for the functions. The number of functions ...

The act of initiating a click on a radio button involves evaluating conditions prior to toggling

Apologies for the slightly ambiguous title, let me provide a clearer explanation. I have created a codepen to demonstrate an issue that I am facing. You can view it here. In my codepen, I have two toggle buttons labeled "Male" and "Female" for simplicity. ...

The conditional statement does not align with my Regular Expression

I'm experiencing a peculiar issue with my regular expression matching in the code snippet provided. Even though the alert confirms a match between the strings, the if statement fails to trigger. Any insights on why this might be happening? Appreciate ...

The Material UI 5 Autocomplete feature is not providing the expected filtered options

I am currently utilizing Material UI V5, Since the default filtering in Autocomplete does not provide the desired result array, I have implemented my own filterOptions function. const customFilter = (options, state) => { let result = options.filter(op ...

Transform Text into Numeric Value/Date or Null if Text is Invalid

Consider the TypeScript interface below: export interface Model { numberValue: number; dateValue: Date; } I have initialized instances of this interface by setting the properties to empty strings: let model1: Model = { numberValue: +'', ...

What is the best way to trigger an API call using AJAX whenever the page loads and at regular intervals using `setInterval()` function?

New to coding and seeking guidance: I have a basic AJAX feature in my project that triggers a GET API request every 3 seconds: <script> $(document).ready( function() { setInterval(function() { $.get(&apos ...

Modifying array elements in JavaScript without explicit instructions

I am relatively new to Javascript and seem to be encountering a rather puzzling issue that I'm unable to resolve. Currently, I have two classes: Country and PPM_Data. The Country class contains parameters such as name, area, ppm, etc., along with a f ...

Creating a personalized .hasError condition in Angular 4

I am currently in the process of modifying an html form that previously had mandatory fields to now have optional fields. Previously, the validation for these fields used .hasError('required') which would disable the submit button by triggering a ...

"Revealing the specific row and column of the selected element in each table when hovering over it

On my webpage, I have set up two tables positioned side by side like this: <!DOCTYPE html> <table> <tr> <td> <table> <tr><td>1</td><td>2& ...

Grouping various event listeners within a v-for loop

My Desired Outcome In my Vue component, I am displaying a list of actions using v-for. Each action should have a corresponding @click event handler that triggers the action method within the component. I need help declaring these actions in my data() fun ...

Is it possible to incorporate variables when updating an array or nested document in a mongodb operation?

Within the "myCollection" target collection, there exists a field named "japanese2". This field is an array or an object that contains another object with a property called "japanese2a", initially set to 0 but subject to change. My goal is to update this p ...