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

Adjust the sliders according to the current time

I am looking to display different sliders based on the time of day. For instance, 'slider set 1' from 0-9am, 'slider set 2' from 9am-12pm, and so forth. I am new to java script and need assistance in solving this challenge. Below is the ...

What are the differences in using ng-controller versus data-ng-controller?

When working with Angularjs, how do I determine whether to use data-ng-controller or ng-controller? In terms of current best practices for good software design, when is it appropriate to use each one? The information cited suggests that data-ng-controlle ...

Using the Object.assign technique will modify the original object's properties in JavaScript

Recently delving into ReactJS, I stumbled upon an interesting revelation regarding the Object.assign() method: const B = { k1: 'b', k2: 'bb', treedata: [{ children: ['g'] }] } var A = Object.assign( ...

Node.js can provide a reusable email framework that can be used across

When it comes to sending emails based on specific business functions in nodejs, I have been following a particular approach. However, I am exploring the possibility of improving this method by composing email content more efficiently. Instead of hardcoding ...

Arrange documents according to the final two characters

My method for collecting files from a folder involves using some Smarty code: {assign var=files value="uploads/Documenten/GPS-Tracks/*.html"|glob} {if count($files)} <ul> {foreach from=$files item='file'} {assign v ...

Discovering instructions on locating Material UI component documentation

I'm having trouble locating proper documentation for MUI components. Whenever I attempt to replicate an example from the site, I struggle to customize it to fit my requirements. There are numerous props used in these examples that I can't seem to ...

When a number is added to an array containing strings, the result is a string rather than a number

Currently, I am attempting to change my array key value from a string to a number within my JSON object: form["price"] == "23" console.log(typeof form["price"]) // string form["price"] == Number(parseFloat(this.formObject[field.fieldName])) The issue aris ...

I'm encountering an issue with the dropify plugin where the data-allowed-file-

While using the dropify library to style file upload elements in my form, I ran into an issue with the data-allowed-file-extensions parameter not working as expected. Despite specifying allowed file extensions like "png jpg jpeg", the validation for input ...

Error: The property 'querySelector' cannot be read because it is null

I've been grappling with this issue for some time now, but haven't had any luck in getting it to work. My goal is to integrate material-ui into my Gatsby project, but I keep encountering a null querySelector error when working with the JavaScript ...

Stop procrastinating and take action before the JavaScript function concludes

Currently, I am experimenting with onkeydown events to capture the input value in a textarea, process it through a PHP file using Ajax post method, and display the result in an external div. However, the issue is that whenever a key is pressed, I am unable ...

AngularJS is experiencing delays when processing subsequent $http delete requests, leaving them stuck in a

I am currently working on a project where I have a table displaying a list of objects, with each object having multiple child objects associated with it. The technologies I am using include Angular 1.2.20, Express 4.6.1, and Node 0.10.25. In the table, the ...

What information is transferred when the submit button on a form is clicked?

Currently, I am utilizing node.js along with the jade templating engine. Within my jade file, I have a form structured like this: form.form-signin(style="padding-left:10px", action='/update', method='post') table.table.table-hove ...

"What could be the reason for web3.eth.getAccounts() method returning an empty array when used with console.log

Upon executing web3.eth.getAccounts().then(console.log);, I encountered an empty array and also received a warning stating ./node_modules/web3-eth-accounts/src/scrypt.js Critical dependency: the request of a dependency is an expression. The project began w ...

Implemented an HTML hyperlink element precisely positioned

I have the following HTML code. I am trying to fix the position of an anchor tag called "View All" so that it stays in a specific location. However, whenever the value in the dropdown menu changes, the anchor tag moves according to the length of the new se ...

Re-rendering components using arrow functions

Using an arrow function, I have implemented a feature to toggle a div and show/hide a button based on the div's visibility. toggleDeliveryDiv = () => { document.getElementById('btn_collapse_delivery').click(); this.s ...

What is the best way to prevent caching of pages that are using a local JSON file in Next.js static generation?

After deploying my Next.js app as static on my cPanel traditional hosting, I encountered an issue. Some pages are consuming a local JSON file that I fetch using getStaticProps, with the "revalidate" option set. However, when I make edits to the JSON file ...

Looking to make a custom loaded dice using 3D physics? Considering using the Cannon physics engine, but open to any other physics engine examples as well

I am exploring the idea of creating a dynamic dice throw animation that lands on a specific number, chosen randomly from random.org and then incorporated into the animation code. Initially, I considered generating multiple pre-made animations for each pos ...

Choose not to alter the display value during keyup and keydown events, while still triggering the change event

$(function(){ $(".cls_user_details select").keyup(function(){ $(".cls_user_details select").val("Profile"); }) }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="cls_user_setti ...

Unable to retrieve image: status code 402 - payment required

When trying to fetch my Facebook page's posts using the Facebook graph API and nextjs with vercel, I encountered an error: GET imageurl 402 payment required. Oddly enough, this works perfectly fine in localhost: I suspect there may be a problem with ...

What steps should I take to host my Vue js single page application on my Django server?

At present, I am in the process of following a tutorial to integrate my Vue.js frontend with my Django backend. You can find the guide here: https://medium.com/@williamgnlee/simple-integrated-django-vue-js-web-application-configured-for-heroku-deployment-c ...