Apply a border to the navbar when it hovers over a selected element

export const NavBar = () => {
  return <div className="navbar">this is navbar</div>;
};

const Content = () => {
  return ( 
    <div className="main">
      <div className="background">
        some content
      </div>
    </div>
  );
};

const App = () => {
  return (
    <>
      <NavBar/>
      <Content/>
    </>
  );
}

ReactDOM.render(<App/>,document.body);
body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

code {
  font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", monospace;
}

.App {
  text-align: center;
}

.App-logo {
  height: 40vmin;
  pointer-events: none;
}

@media (prefers-reduced-motion: no-preference) {
  .App-logo {
    animation: App-logo-spin infinite 20s linear;
  }
}

.App-header {
  background-color: #282c34;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
}

.App-link {
  color: #61dafb;
}

@keyframes App-logo-spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.navbar {
  width: 100%;
  height: 64px;
  background: red;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 100000;
}

.main {
  height: 200vh;
  width: 100%;
  position: relative;
  background: blue;
}

.background {
  width: 100%;
  height: 200px;
  background: red;
  position: absolute;
  top: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

I'm having trouble finding a solution and don't know where to begin. Here's a simple codepen that showcases my issue:
Codepen

My objective is to have the navbar display a black border when it overlaps the "some content" section. Is there any solution that can assist me with this? Or should I simply set it like: When y scroll is between 247px and 453px change border. Something like this:

const [scroll, setScroll] = useState();
useEffect(() => {
    setScroll(window.pageYOffset)
}, [window.pageYOffset])

return <div style={{ borderBottom: `solid black ${(scroll >= 247 && scroll <= 453) && '2px'}` }}>navbar</div>

Is there a more efficient approach to achieving this?

Answer №1

When using React, you can utilize the onMouseEnter event to determine if the user is hovering over an element. First, we need to create a state to store this information.

const App = () => {
  const [isHover, setIsHover] = useState(false);

  return (
    <>
      <NavBar/>
      <Content/>
    </>
  );
}

We can then update the state based on whether the user is hovering over the element or not.

   <div className="main">
      <div className="background"
        onMouseEnter={() => setIsHover(true)}
        onMouseLeave={() => setIsHover(false)}>
        >
        some content
      </div>
    </div>

Next, we can change the className depending on the state.



export const NavBar = () => {
  return <div className={isHover? "navbar bordercss": "navbar"}>this is navbar</div>;
};

Answer №2

If you want to make a comparison, consider checking the

background.getBoundingClientRect().top
against
navbar.getBoundingClientRect().bottom
.
(Alternatively, if the navbar is positioned at the top of the page, you could use navbar.offsetHeight as well.)

Below is an example using pure JavaScript:

const
  navbar = document.getElementById('navbar'),
  background = document.getElementById('background');
window.addEventListener("scroll", toggleNavbarBorder);

function toggleNavbarBorder(){
  const method = (background.getBoundingClientRect().top <= navbar.offsetHeight)
    ? "add"
    : "remove";
  navbar.classList[method]("bordered");
}
body { margin: 0; }
#navbar { width: 300px; height: 40px; position: fixed; top: 0; left: 0; z-index: 1; background: red; }
#main { width: 300px; height: 120vh; position: relative; background: blue; }
#background { width: 300px; height: 60px; position: absolute; top: 60px; background: red; }
.bordered{ border-bottom: 2px solid black; }
<div id="navbar">navbar</div>
<div id="main">
  <div id="background">some content</div>
</div>

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

When the flex-grow property is set to 1, the height of the div extends beyond the space that

Here is an example of some HTML code: .container { height: 100%; width: 100%; display: flex; flex-direction: column; padding: 10px; background-color: aqua; } .box { width: 100%; height: 100%; flex-grow: 1; background-color: cadetb ...

Can you explain the owlItem feature found in owl carousel?

Does anyone have an idea about this? .data("owlItem") How can I find this in jQuery or the console log? I don't think this is a data attribute. .data("owlItem") .data("owlItem") $("#slider_thumb").on("click", ".owl-item", function(e){ ...

Click here to access the identical page

Longtime follower of stackoverflow but only my second time posting a question. Here is the code I am currently working on: echo "<td><a href = 'http://localhost/map/index.php' value='$id' >Delete</a></td>"; ...

What is the method for calling a function in a JavaScript file?

I am facing a challenge with reinitializing a JavaScript file named AppForm.js after a successful ajax post response. Within the file, there are various components: (function(namespace, $) { "use strict"; var AppForm = function() { // Cr ...

What is the best way to ensure jQuery loads before CSS code on a website

I am currently working on a blog project that allows visitors to customize the background color by simply clicking on one of five available buttons. $(function(){ //Checking if a color scheme has already been selected var chosenColor = ...

`Is it common to use defined variables from `.env` files in Next.js applications?`

Next.js allows us to utilize environment variable files such as .env.development and .env.production for configuring the application. These files can be filled with necessary environment variables like: NEXT_PUBLIC_API_ENDPOINT="https://some.api.url/a ...

The NgbTypeahead element is not able to scroll when placed within a scrollable container

Currently, I am utilizing the NgbTypeahead component from ng-bootstrap. The issue I am facing is that when I place the typeahead component within a scrollable element and proceed to scroll down, the position of the dropdown container remains unchanged. &l ...

Guide on converting JSON encoded data into a JavaScript array

I have a few web pages that display results in the following format: [{"id":"1","company":"Gaurishankar","bus_no":"JHA 12 KH 1230"}, {"id":"2","company":"Gaurishankar","bus_no":"BA 2 KH 2270"}] Now, I want to take this JSON encoded data and use it in a J ...

In nextjs, the page scroll feature stops functioning properly following a redirection

Currently, I am running on version 13.5.4 of Next.js In a server-side component, I am using the nextjs redirect function to navigate to another page. However, after the redirection, I noticed that the next page is missing the scroll bar and seems to be st ...

How can I display and utilize the selected value from a Rails select form before submitting it?

Currently, I am in the process of developing a multi-step form for placing orders. This form includes two dropdown selectors - one for shipping countries and another for shipping services. Once a country is selected, all available shipping services for tha ...

Error: The localStorage object is not defined within the context of a Next.js application

I am developing a Next.js application Here is an example of one of my pages/components: import React from "react"; import { SomeLocalStorageComponent } from "some-external-lib"; const MyComponent = () => { const isBrowser = typeof ...

Leveraging route configuration's scope in HTML

As a beginner in AngularJs, I am currently exploring the creation of a single page application. However, I am encountering difficulties in converting my initial code into more professional and efficient code. During this conversion process, I have separate ...

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 ...

What is the most effective method to ensure this layout is functioning properly?

Seeking a solution to an unexpected challenge, what initially appeared as a simple task has transformed into a complex dilemma. Balancing the vertical alignment of green DIVs while preventing absolute positioned elements from overlapping following content ...

Changing the state variable leads to an endless rendering cycle

I am working on creating a comment section using React. The component retrieves all comments and replies to each comment in one large dataset by performing an outer join, then it separates the results into two arrays (comment array and replies array). How ...

Is there a way to horizontally navigate a pallet using Next and Prev buttons?

As someone new to development, I am looking for a way to scroll my question pallet up and down based on the question number when I click next and previous buttons. In my pallet div, there are over 200 questions which are dynamically generated. However, th ...

Incorporate images into ReactJS Components without the need to save them locally as files

<img src={BASENAME+"/src/images/cabecera_CE.jpg"} id="idImgCabecera" alt="Universidad Politécnica de Cartagena" class="img-responsive"/> and I am looking to do the following: import PHOTO from './../images/cabecera_CE.jpg' <img src= ...

Do we need to use parseInt for the '*' operator in JavaScript?

I have an array where I am mapping it at some point to calculate the sum and percentages. However, when I tried implementing the logic, I noticed that using '*' directly works fine but using '+' adds the two strings together. For exampl ...

Is your custom login form in Web2py not submitting properly?

My attempt to customize the login form for web2py has hit a roadblock. Despite adding the necessary fields and submit button, nothing seems to be happening. Here's what the code in the form's view looks like: {{include 'web2py_ajax.html&apo ...

What are the steps for creating a new npm package based on an existing one?

I'm a newcomer to the node ecosystem and the npm package system. In my redux/react web app, I currently make use of the photoswipe package alongside react-photoswipe. Recently, I decided to extend the functionality of the photoswipe package by making ...