JavaScript code that moves the active link to the top of the navigation when the window width is less than or equal to 800px

I'm working on a responsive navigation that is fixed at the top and switches from horizontal to vertical when the screen size is less than or equal to 800 pixels wide.

However, I'm facing an issue with moving the active link to the top of the navigation when the screen size is less than or equal to 800 pixels wide. I've tried using Javascript, but it doesn't keep the active link at the top because the page refreshes or changes when a link is clicked.

I attempted to implement a loop within an if-statement, but it didn't work as expected, so I removed the if-statement altogether.

If anyone could provide assistance in solving this problem, I would greatly appreciate it.

Below is the snippet of Javascript code:

/*------------------------move active link to top------------------------*/
function moveLink(){
var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var list = document.getElementById('nav').childNodes;
for (var i = 0; i < list.length; i++) {
    list[i].addEventListener('click',function() 
    {nav.insertBefore(this, nav.childNodes[0])});
}
}

Here's the HTML structure of the navigation:

<nav>
<ul id="nav" class="topNav">
    <li><a onclick="moveLink()" href="/">Placeholder1</a></li>
    <li><a onclick="moveLink()" href="Placeholder1.html">Placeholder1</a></li>
    <li><a onclick="moveLink()" href="Placeholder1.html">Placeholder1</a></li>
    <li><a onclick="moveLink()" class="active" href="licenses.html">Placeholder1 / FAQ</a></li>
    <li><a onclick="moveLink()" href="Placeholder1.html">Placeholder1</a></li>
    <li><a onclick="moveLink()" href="contact.php">Placeholder1</a></li>
    <li class="icon"><a href="javascript:void(0);" onclick="myFunction()">
    <img alt="open menu" src="graphics/menu.png" style="height: 30px; width: 30px;"></a>
    </li>
</ul>

Please note that there are two stylesheets used in this setup and the menu opening and closing functionality is handled via Javascript.

Here's the CSS for the mobile layout:

/*------------------------navigation------------------------*/
.topNav {
z-index: 1;
list-style-type: none;
margin: 0 auto;
padding: 0;
overflow: hidden;
position: fixed;
top: 0;
width: 100%;
font-size: 0px;
background-color: rgba(0,0,0,0.8);
box-shadow: 0px 0px 8px 0px rgba(0,0,0,0.75);
}
.topNav li {
display: inline;
}
.topNav li a {
font-size: 12px;
display: inline-block;
color: #fff;
text-decoration: none;
transition: color 0.2s ease-in-out;
line-height: 38px;
padding: 0px 0px 0px 20px;
}
.topNav li a:hover {
color: #777;
}
.topNav li a.active {
color: #999;
}
/*------------------------responsive navigation closed------------------------*/
.topNav li:not(:first-child) {
display: none;
}
.topNav li.icon {
float: right;
display: inline-block;
height: 38px;
vertical-align: middle;
transition: opacity 0.2s ease-in-out;
margin: 4px 5px 0px 0px;
width: 30px;
height: 30px;
padding-right: 20px;
}
.icon:hover {
opacity: 0.5;
}
/*------------------------responsive navigation opened------------------------*/
.topNav.responsive {
position: fixed;
top: 0px;
}
.topNav.responsive li.icon {
margin: 0 0 0 0;
position: absolute;
top: 4px;
right: 25px;
width: 30px;
height: 30px;
padding-right: 0px;
z-index: 1;
}
.topNav.responsive li.icon:hover {
opacity: 0.5;
}
.topNav.responsive li {
float: none;
display: inline;
}
.topNav.responsive li a {
display: block;
}

Thank you in advance, Ken

Answer №1

Using CSS with flexbox and the order property can accomplish this task.

@media (max-width: 800px) {
  nav ul {
    display: flex;
    flex-direction: column;
  }
  .active {
    order: -1;
  }
}

The order: -1 declaration will move the list item to the top of the column.

To simplify the process, I assigned the class active to the li instead of the a.

You can view a working example on CodePen.

Snippet:

body {
  font-family: sans-serif;
}

nav {
  background: grey;
  padding: 20px;
}

nav ul {
  list-style-type: none;
}

nav ul li {
  display: inline-block;
  margin-right: 8px;
}

nav ul li:last-child {
  margin-right: 0;
}

nav ul li a {
  text-decoration: none;
  color: white;
}

@media (max-width: 800px) {
  nav ul {
    display: flex;
    flex-direction: column;
  }
  .active {
    order: -1;
  }
}
<nav>
  <ul id="nav" class="topNav">
    <li><a onclick="moveLink()" href="/">BEATS</a></li>
    <li><a onclick="moveLink()" href="sounds.html">SOUNDS</a></li>
    <li><a onclick="moveLink()" href="services.html">SERVICES</a></li>
    <li class="active"><a onclick="moveLink()" href="licenses.html">LICENSES / FAQ</a></li>
    <li><a onclick="moveLink()" href="downloads.html">DOWNLOADS</a></li>
    <li><a onclick="moveLink()" href="contact.php">CONTACT</a></li>
  </ul>
</nav>

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

Transferring values from jQuery AJAX to Node.js

Is there a way to successfully pass a variable from jQuery to nodejs without getting the [object Object] response? I want to ensure that nodejs can return a string variable instead. $('.test').click(function(){ var tsId = "Hello World"; ...

CSS Flexibility in Action

Presently, my tab bar has a fixed look as shown here: https://codepen.io/cdemez/pen/WNrQpWp Including properties like width: 400px; etc... Upon inspecting the code, you'll notice that all the dimensions are static :-( Consequently, I am encountering ...

In JavaScript, the "this" keyword points to a different object

Here is a script that needs attention: Bla = function() { this.prop = 123; } Bla.prototype.yay = function() { console.log(this,this.prop); } X = new Bla(); $(document).ready(X.yay); // output: #document undefined --> why? $(document).ready(functio ...

Is there a way to display two cards side by side in mobile view?

On a desktop view, 2 cards are displayed in a row. I would like them to also appear in a row on mobile view. I tried using col-sm-4 but it's not working. How can I get the cards to display in a row on mobile view so that I can see both the product pho ...

Connect the dxSelectBox to the button click event

Currently, I am working with the DevExtreme MVVM architecture. In my specific situation, I am trying to bind a dxSelectBox (combo box) upon a button click event. Here is the HTML CODE snippet: <div data-bind="dxButton:{onClick:display,text:'Click ...

Utilizing the Twitter API with Next.js to automate tweets even when the website is not actively engaged

Currently, I am utilizing next.js for the development of a web application. My goal is to have this app automatically post to my Twitter account. I have already set up a developer account on Twitter and an API in nextjs. By calling the API, it will trigger ...

Issue encountered when attempting to alter the action attribute of a form: receiving an error message stating 'undefined is not a function'

I am attempting to dynamically set the action attribute of a form based on the button clicked in order to navigate away from a page. Once the action is updated, the form should be submitted and the new action carried out. Below is my jQuery function: fun ...

Using the ternary operator in a jQuery event

I am looking for a solution to have a button trigger different functions based on the value of a variable. It appears that the ternary operator does not work with a jQuery event trigger. var color = "blue"; $(document).ready(function(){ $('#bot ...

Change the marquee scrolling back to its original starting point

I am trying to implement a continuous image scroll (marquee) in HTML. My goal is to have the marquee stop scrolling when the mouse hovers over it, with the images returning to their initial position. Once the mouse moves away, I want the marquee to resume ...

Exploring deeply nested arrays of objects until a specific condition is satisfied

My array is structured in a nested format as shown below. const tree = { "id": 1, "name": "mainOrgName", "children": [ { "id": 10, "name": "East Region", "children": [ ...

Increasing a variable in MongoDB using Meteor.js based on the value of a variable in a separate document

I am facing an issue similar to this: I am struggling to modify multiple documents simultaneously. click: function() { var power = Meteor.user().power; var mult = Meteor.user().mult; Meteor.users.update({ _id: this.use ...

Issue with triggering the change event for <select> tag

Whenever the selected value of the drop down changes, the following code does not work as expected. Please make corrections if any errors are present. <!doctype html> <html lang="en"> <head> <meta charset="utf-8</scri ...

output a string from the write_html function in plotly

I am currently attempting to utilize plotly express to generate a string representation of a div object in HTML for integration with other packages. Although I have been following the documentation (Plotly v5.17.0), it seems that my attempts have not been ...

Overlapping Bootstrap cards conundrum

Does anyone know how to align Bootstrap cards and make them responsive? I have them centered, but they are overlapping and sticking to the left side. This is for email development with a maximum width of 680px. Any assistance would be greatly appreciated! ...

The CSS of the Sendgrid template is being overlooked

I have utilized Sendgrid to create the template mentioned below: In order to send this template using my Node server, I have developed the module provided in the code snippet: /* * Created by root on 6/6/16. */ var path = require('path'), ...

What is the proper way to import Axios in Vue 3 once you have created a new project using the CLI?

When starting a new project, I used the command: vue create hello-world This generated essential files like HelloWorld.vue, app.vue, and main.js. Next, I followed the documentation on Npm vue-axios to install Axios: npm install --save axios vue-axios In ...

Children divs unexpectedly showing up outside of their parent divs

I have reviewed similar questions on this matter, but none of them seem to provide a solution for the issue I am facing. Currently, my goal is to display a stylized list, but I am encountering more difficulties than expected. You can find a fiddle linked ...

simplest method to brighten the image in this specific instance

I have a simple question. We are looking to enhance some static images by adding a lightening effect with an overlay. For example, when hovering over an image like on this website: (just for the lightening effect). What is the best approach to achieve thi ...

Safely transmitting client-side encrypted information between individuals

I am developing a service that will keep personal information about a specific user, which should only be accessible by the author and the intended recipient. I want to encrypt the data on the client-side and store the encrypted version on the server. Res ...

Loading screen displayed while transitioning between routes within Angular

I have been struggling to implement a loading spinner in my project. How can I display a loading screen when changing routes in Angular? Here is the HTML code snippet: <div *ngIf="showLoadingIndicator" class="spinner"></div> ...