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

Why isn't the default value displayed in MUI AutoComplete?

import * as React from "react"; import TextField from "@mui/material/TextField"; import Autocomplete from "@mui/material/Autocomplete"; export default function MovieComboBox() { const [movieList, setMovieList] = React.useSt ...

Attempting to crack the code within body-parser and Node.js

I am just getting started with Node.js & Express and trying to follow a tutorial at https://github.com/jw84/messenger-bot-tutorial. I have a good understanding of most parts, but I'm confused about the use of "entry" and "messaging" in this code snipp ...

What is the best way to inject a service instance into the implementation of an abstract method?

In my Angular application, I have a service that extends an abstract class and implements an abstract method. @Injectable({ providedIn: 'root', }) export class ClassB extends ClassA { constructor( private service : ExampleService) { s ...

Acquire feedback from PHP using SweetAlert notifications

I need to update my HTML form to function like this: <script> function getName() { var name = $('#name').val(); var url_send = 'send.php'; $.ajax({ url: url_send, data: 'name=' + name, ...

Variable not accessible in a Typescript forEach loop

I am facing an issue with a foreach loop in my code. I have a new temp array created within the loop, followed by a nested foreach loop. However, when trying to access the temp array inside the nested loop, I encounter a "variable not available" error. le ...

Position the left floated element at the top, with all preceding siblings floated to the right

Is there a way to rearrange the HTML structure using CSS only to move Content 3 Div (div3) to the top? The sequence of elements cannot be changed. I attempted to use negative margin, but it only works if the height of Div 1 and 2 is fixed. However, the co ...

Having trouble with v-model not updating the data value on a dropdown in Vue.js?

When I set the initial value on the data property, the dropdown option is correctly displayed. However, if I select a different value from the dropdown, the data property does not update accordingly. <select class="form-control" ...

The pseudo class before is experiencing issues with background color in Safari and not functioning as

Issue with Pseudo class before not displaying background colour in Safari browser To view the code, please visit the following link here HTML <div id='test'> <p>Test </p> </div> CSS #test { position: relative; per ...

Creating a CSS triangle that smoothly transitions between two different colors

Is it possible to create a triangle in CSS that smoothly transitions between two colors without relying on a hover state? .arrow-down { width: 0; height: 0; border-left: 20px solid transparent; border-right: 20px solid transparent; b ...

Preserve data across all pages using sessions

On my website, I have a pagination system where each page displays 10 data entries. Whenever a user clicks on the pagination buttons, it triggers a request to the database to fetch the corresponding records. Each data entry also includes a button that can ...

What steps should I follow to create a versatile table component?

Can you please advise me on how to create generic data in a table using Typescript? I encountered this error message while trying to useTable({ at line data The error states: Type 'T[]' is not assignable to type 'readonly object[]'. ...

What is the best way to create a website where images align perfectly with stacked cards?

Having trouble aligning the image on the right side of my website with two cards on the left side. Here is an example of what I'm aiming for: (https://i.sstatic.net/fBvTQ.jpg)](https://i.sstatic.net/fBvTQ.jpg) This is the current code: <!doctyp ...

Require help with personalizing a jQuery horizontal menu

I recently downloaded this amazing menu for my first website project By clicking the download source link, you can access the code Now, I need your kind help with two issues: Issue 1: The menu seems to be getting hidden under other elements on the page ...

Navigating through elements in the hidden shadow DOM

Can elements within the Shadow DOM be accessed using python-selenium? For example: There is an input field with type="date": <input type="date" name="bday"> I want to click on the date picker button located on the right and select a ...

Center the div and make it position fixed

Is there a way to position a div in the center of the screen or its parent div, and have it fixed so that it does not shift when its width changes? I have a div containing a table, as shown below: I'm unsure if the outer div is needed. My goal is to ...

Ensure that bulleted lists and numbered lists are aligned to the left side

Check out this website where the ordered and unordered lists are not aligned correctly. The ideal alignment would have the bullets (or numbers) left aligned. For instance, the number "1." should be aligned to the left on the same line as the heading "Per ...

techniques for utilizing dynamic variables with the limitTo filter in AngularJS

<div class="container"> <div class="row" ng-repeat="cmts in courCmt.argument" ng-init="getUserInfo(cmts)"> <div class="col-sm-1 col-xs-2"> <div class="thumbnail"> &l ...

The button should only be visible when the input is selected, but it should vanish when a different button within the form is

Having an issue with displaying a button when an input field is in focus. The "Cancel" button should appear when a user interacts with a search bar. I initially used addEventListener for input click/focus to achieve this, but ran into a problem: on mobile ...

To begin utilizing Node.js modules, you must use the `#` symbol as the starting point

Quoting the Nodejs documentation, available at this link require(X) from module at path Y 1. If X is a core module, a. return the core module b. STOP 2. If X begins with '/' a. set Y to be the filesystem root 3. If X begins with './ ...

The issue encountered with the Material UI Autocomplete component is that it is not displaying the values

I'm currently attempting to extract a value from the state to be used in materialUI's autocomplete component. However, I've encountered an issue: The autocomplete feature works perfectly when selecting a value and saves it to the state wit ...