Is there a way to adjust my navbar's height depending on the presence of a focused link?

Currently, I am utilizing React and JavaScript for styling on my website. One feature I have implemented is a skip link in the navigation bar that allows users to jump further down the page with a simple click. The challenge I'm facing is that this skip link only becomes noticeable when the tab key is pressed. It is positioned above the site logo in the navbar and requires more space when it appears. To address this, I aim to increase the height of the navbar when the link is visible. My approach involves using a boolean variable named linkHasFocus for conditional CSS styling. Additionally, I have created a function called checkFocus:

const TopNavbar = styled.div`
      ...
      height: ${props => (props.linkHasFocus ? '9rem' : '4rem')}; 
      ... 
`;

Here is an outline of the checkFocus function:

const checkFocus = () => {
      const elem = document.getElementById('skip-link');
      if (elem === document.activeElement) {
        this.linkHasFocus = true;
      }
      this.linkHasFocus = false;
      return this.linkHasFocus;    
};

I pass the checkFocus function to my TopNavbar component (the parent of the skip link component) in the return statement like this:

<TopNavbar linkHasFocus={checkFocus}>

However, I have encountered an issue where the checkFocus function does not update the linkHasFocus variable correctly. My grasp of props and JavaScript concepts may be lacking, so I apologize if there are glaring errors in my implementation.

Answer №1

After finding a helpful navbar example on w3schools.com (I recommend checking out their Top Navigation tutorial), I decided to enhance it with 3 additional examples using JavaScript and CSS.
By utilizing the .classList property, we can dynamically add, remove, or toggle classes on elements. This allows us to apply style changes (such as adjusting height and transitions for the top navigation) based on specific user actions.

Below are the 3 examples showcased in JavaScript:

  1. Expanding the Navbar when pressing the TAB key (keyCode == 9), and contracting it when the key is released;
  2. Toggling the expansion when the SPACE key is pressed (keyCode == 32);
  3. Expanding the Navbar when hovering over the Skip section, and shrinking it upon exiting the area.

// Example 1: Expand the navbar while tab key is pressed
document.body.addEventListener("keydown", function(e) {
  if(e.keyCode == 9) {
    document.getElementById("myTopnav").classList.add("expand");
  }
});
document.body.addEventListener("keyup", function(e) {
  if(e.keyCode == 9) {
    document.getElementById("myTopnav").classList.remove("expand");
  }
});

// Example 2: Toggle navbar expand with space key
document.body.addEventListener("keydown", function(e) {
  if(e.keyCode == 32) {
    document.getElementById("myTopnav").classList.toggle("expand");
  }
});

// Example 3: Expand the navbar while the mouse is over
document.getElementById("skip").addEventListener("mouseover", function(e) {
    document.getElementById("myTopnav").classList.add("expand");
});
document.getElementById("skip").addEventListener("mouseout", function(e) {
    document.getElementById("myTopnav").classList.remove("expand");
});
body {
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;
}

.TopNavbar {
  height: 4rem;
  overflow: hidden;
  background-color: #333;
  -webkit-transition: all .5s ease;
  transition: all .5s ease;
}
#myTopnav.expand {
  height: 9rem;
  transition: height 300ms;
}

.TopNavbar a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;  
  font-size: 17px;
}

.TopNavbar a:hover {
  background-color: #ddd;
  color: black;
}

.TopNavbar a.active {
  background-color: #04AA6D;
  color: white;
}

.pageContent {
  padding: 14px 16px;
}

li {
  margin: 10px 0;
}
<html>
<head>
</head>
<body>
  <div class="TopNavbar" id="myTopnav">
    <a href="#home" class="active">Home</a>
    <a href="#contact">Contact</a>
    <a href="#about">About</a>
    <a id="skip" href="#skip">Skip</a>
  </div>

  <div class="pageContent">
    <h3>Navbar extension example</h3>
    <ul>
      <li>Example 1: extend the navbar while <code>TAB</code> key is pressed.</li>
      <li>Example 2: press <code>SPACE</code> key to toggle the navbar extend.</li>
      <li>Example 3: extend the navbar while the mouse is over "Skip" option.</li>
    </ul>
  </div>
</body>
</html>

If this isn't what you're looking for, consider exploring CSS Selectors for more options that may better suit your needs.

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

Using Javascript to make API calls

I'm working with PHP functions that interact with a SQL database, retrieving data and encoding it into JSON format. For example: function getApiCall(){ $sql = 'SELECT * AS "Total" from tablename"'; try { $db = getConnectio ...

Created a custom function that includes a specific target href parameter

I have a website that implements role-based authentication, where the application displayed is dependent on the user's role. The code for this functionality is as follows: <asp:Repeater ID="ui_rprApp" runat="server" DataSourceID="odsApp"> ...

Using jQuery to update a specific item in a list

My current project involves developing an Image Gallery app. It uses <img> tags within li elements. The code snippet is as follows: var $slideR_wrap = $(".slideRoller_wrapper"); var $slidesRoller = $slideR_wrap.find(".slidesRoller"); var $slideR ...

Display information on the console from any location

I'm working on a Node.js project where I need to display text at specific locations, such as the top right corner. Is there a Node.js module available that can help me achieve this? Something like: var displayModule = require('display_module&ap ...

Dial the Google App Scripts hotline

After successfully testing the query string in the browser for my published app script, I attempted to send an XMLHttpRequest to the script. However, upon doing so, I encountered the following error message: XMLHttpRequest cannot load https://script.goo ...

Best practice for spreading computed values in Angular 2

I am struggling to make computed values work with @Input properties. Unfortunately, the initial value propagation is not functioning correctly. https://plnkr.co/edit/1MMpOYOKIouwnNc3uIuy I have two components: App (the root component with a template-dri ...

Guide to releasing an independent Angular component (njsproj) alongside a web application using Visual Studio 2017

We are in need of publishing our website locally to test it on Sitecore. Our special component for this purpose is called webapp. Recently, we introduced a new component (njsproj file) that contains our Angular application. However, when I publish webapp, ...

"Assigning an array as a value to an object key when detecting duplicates in a

Let's assume the table I'm iterating through looks like this: https://i.stack.imgur.com/HAPrJ.png I want to convert each unique value in the second column into an object, where one of the keys will hold all values from corresponding rows. Here& ...

Each element is being adorned with the Ajax success function class

Currently, I am in the process of creating an Ajax function to integrate search features into my project. The search function itself is functioning properly; however, within the success: function, I am encountering an issue. Specifically, I am attempting t ...

In what way should a React hook's state be updated when it includes a Map data structure?

In my project, I have a collection of more than 15 div tags displayed as tiles. One of the requirements is to highlight each tile when the user hovers over it. To achieve this, I implemented the following code for each tag: <div key={key} onMou ...

Determine the closest parent using jQuery

When using jQuery, the closest function can be called to locate the nearest parent element. For instance, if there is an a within a li within a ul within a td within a table, determining whether the ul parent is closer than the table parent may not always ...

Tips for rendering the stencil as invisible and disabled while still allowing other features (such as rotating and flipping) to remain enabled within the react-advanced-cropper

I am facing a challenge where I need to hide and disable the stencil and overlay in react-advanced-cropper, while keeping all other features like rotation and flipping enabled. Is there a specific property in this library that allows me to disable the st ...

Modify the color of the text input by the user in an AJAX-enhanced text box

After successfully implementing an autocomplete textbox using AJAX Autocomplete, I decided to enhance the feature with some Fuzzy logic. Now, as the user enters 3 characters, my database returns a list of records that match those characters. The search re ...

Use PHP code to echo a clear division after every third result in MySQL

I am currently displaying results in descending order from a MySQL table using a while loop. I have already set up a pagination system that displays 9 records per page. However, I am facing an issue when trying to implement a CSS break every 3 records in ...

Issue with the dropdown selection menu

I've been customizing a paid template based on this original design: The dropdown menu is causing issues - it doesn't open on mouseover and requires a click to access. Additionally, once the menu is open, there's a problem with closin ...

What is the process of inserting information into a json file?

My current challenge involves managing a JSON file that acts as a database for users. Below is the mock object structure: [ { "id": "0", "username": "aaaaaaaaa", "password": "xxxxxxxxx" }, { "id": "1", "username": "bbbbbbbbb", ...

Error message in React YouTube: Unable to access 'playVideo' property of null object

An unexpected error occurred during runtime: TypeError: Cannot read properties of null (reading 'playVideo') Call Stack eval node_modules/react-youtube/node_modules/youtube-player/dist/index.js (65:0) new Promise exports.default node_modules/re ...

Preventing duplicate entries in a LocalStorage JSON array by saving data

Recently, I wrote a small script to experiment with localStorage. It's quite basic - you can add items to a JSON array and they will be stored under the key "saved". However, I encountered an issue where duplicate entries were not being prevented in ...

Delaying CSS Keyframe animations

I'm having trouble getting the color squares in my table to appear one by one. I want each color to show up, then disappear, followed by the next color appearing and disappearing, creating a light sequence effect. Any advice or assistance would be gre ...

Steps for sending a POST request to myjson

I've previously stored some data in json format on myjson.com. My goal is to utilize this data for my project. I am aware that I need to use axios.get(url) to retrieve the data and integrate it into my code. However, once I have made modifications to ...