The CSS styling for an active link is not functioning correctly on a single page when using sections

I recently received a zip file containing a template purchased from themeforest, with a request to make modifications. The template includes a horizontal navigation bar with links to various sections on the page. In the original template, when you click on a link, it changes the background color of the active navigation link depending on which section you are in. However, after modifying the page and using my version, this feature seems to be not working.

I've tried changing the class name from .active to .viewing in case there was a naming conflict, but it didn't resolve the issue. It appears that I might not be familiar with some scripts or bootstrap CSS used in the page.

The code for the navigation bar is as follows:

<div class="span9 nav-wrapper">
                        <nav>
                            <ul>
                                <li><a href="#section-home" id="nav-home" class="active">Home</a></li>
                                <li><a href="#our-team" id="nav-team">Team</a></li>
                                <li><a href="#our-services" id="nav-services">Services</a></li>
                                <li><a href="#contact-section" id="nav-contact">Contact</a></li>
                            </ul>
                        </nav>
                        <div class="header-phone-number"><span>Call us on</span> <i class="icon-phone"></i> 1800 25 1800</div>
                    </div>

The CSS styling applied to the links is given below:

nav a {
    color: #fff;
    text-transform: uppercase;
    display: inline-block;
    padding: 26px 20px;
    font-size: 12px;
    font-family: 'Open Sans',sans-serif;
}

nav a:hover {
    background: #616a73;
}

nav a:hover, 
nav a:visited {
    color: #fff;
    text-decoration: none;
    outline: none;
}

nav a.active {
    background: #4c5660 url(../img/banner-bg.jpg);
    color: #fff;
    outline: none;
}

I am seeking guidance on how the ".active" class functions within this specific navigation bar and how it applies to other links when clicked. Is it related to jQuery? Why does my modified page appear to be malfunctioning even though I only changed the colors of the navigation bar from the original template?

Your assistance would be greatly appreciated.

Answer №1

Seems like there's an issue with the JQuery implementation.

The following code snippet is supposed to toggle the 'active' class on navigation links:

$('nav a').click(function(){
      $('nav a').removeClass('active');
      $(this).addClass('active');
      var href= $(this).attr('href');

      if ( guardianIsMobile === true ){
          $('.nav-wrapper').hide();
      }

      $.scrollTo( href, 800, {
          onAfter : function(){
              //add function to do after the animation here if required
          } ,
          offset: -30 //use this to position the window exactly where you want
      });

      return false;
   });

If you check the console on your website, you'll see the error message:

Uncaught TypeError: Cannot read property 'offsetWidth' of null 

This error seems to be related to a line in custom.js at line 148:

var map = new google.maps.Map(document.getElementById("contact-map"),myMapOptions);

Possibly the issue lies with the map setup causing this problem?

Answer №2

When it comes to incorporating classes without the use of javascript or php, it can be a bit tricky. However, here are some snippets I was able to come up with:

Using jQuery

$("a").click(function() {
    $("nav").find("a.current").removeClass("current");
    $(this).addClass("current");
});

Using PHP (not tested)

<?php
    $nav = "<nav><ul><li>";
    $links = array(
        '#home' => 'Home',
        '#serv' => 'Service',
        '#con' => 'Contact',
        '#about' => 'About'
    );

    if(isset($_GET['link'])) // link = integer
    {
        $i = 1;
        foreach($links as $key => $val)
        {
            if($_GET['link'] == $i)
            {
                $nav .= "<a class =\"current\" href=\"".$key."\">".$val."</a>";
            }
            else
            {
                $nav .= "<a href=\"".$key."\">".$val."</a>";
            }
            ++$i;
        }
    }

    echo $nav; // Insert this in your code
?>

Here is a jsfiddle link for reference

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

Obtaining localStream for muting microphone during SIP.js call reception

My approach to muting the microphone involves using a mediastream obtained through the sessionDescriptionHandler's userMedia event. session.sessionDescriptionHandler.on('userMedia', onUserMediaObtained.bind(this)) function onUserMediaObta ...

Angular's browser animation feature allows for smooth slide-up animations from the bottom

I have been experimenting with creating a simple animation, and it's working, but in the opposite direction of what I intended. I want the div to open from bottom to top and close from top to bottom. Here is my animation code in Angular: animations: ...

How can you set an input field to be initially read-only and then allow editing upon clicking a button using Vue.js?

//I have two divs that need to be set as readonly initially. When an edit button is clicked, I want to remove the readonly attribute and make them editable. <div> <input type="text" placeholder="<a href="/cdn-cgi/l/email-protection ...

Troubleshoot: Issue with Navbar Dropdown Expansion on Bootstrap Sass 3.3.6 with JavaScript

Beginner: Bootstrap Sass 3.3.6 - Incorporating Javascript - Issue with Navbar Dropdown Not Expanding application.html.erb Head: <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %> ...

How can PHP be utilized to dynamically add classes to <li> elements and alternate them after every third item

I'm trying to find a way to add a class to an unordered list and alternate that class after every third item. Here's the code I have so far: <?php $i=1; foreach($this->items as $item) : ?> <li class="<?php if ($i % 3 == 0) : ...

Implementing a sorting mechanism for ajax data retrieval

Currently, I am using the code below to save HTML created with jQuery in a database and retrieve it later: $('div[read]').each(function(){ var kelas = $(this).attr('kelas'); $.post('admin.php',{kelas:kelas,id:id},func ...

Technique for Retrieving Hyperlinks from HTML Resulting in Repetitive

I have been working on a web-crawler and encountered an issue while parsing the HTML content to extract links. The method I am using seems to be returning duplicate links, even though the HTML content is correct. Here is the code snippet: public static Ar ...

A guide on extracting keywords from the tynt API using JavaScript

Looking to extract the inbound keyword from an API: What would be the best way to use JavaScript to extract and display the value of the inbound keyword from this API? ...

Maintain scroll position during ajax request

I am working on a single-page website that contains numerous containers. Each container's content is loaded dynamically via ajax, so they may not all be populated at the same time. These containers have variable heights set to auto. The website uti ...

decorating elements in a line with colored backgrounds

I am facing an issue where I want to keep three divs aligned horizontally on the same line, but their background colors are causing them to not align properly. Adding margin or padding causes the divs to wrap up instead of staying in line. #service_cont ...

Expanding the padding of the selected item to create more breathing room

Upon examining the following: https://jsfiddle.net/h8kmove5/27/ Let's say you select 9 at the bottom. The display shows 8 9 10. My intention is to create some additional space on either side of 9, or any other active item for that matter. This way, ...

Make sure link opens in the same window/tab

Currently, I am utilizing the Open Link in Same Tab extension on Google Chrome. This extension can be found here. The purpose of this extension is to ensure that all links open in the same window/tab, which is necessary for touch screen kiosk left/right s ...

What would be more efficient: inputting all items in a form at once or adding them one by one consecutively

My mind is preoccupied with a dilemma: is it better to have all possible items already on the form, or should items only be added when the user requests them? Let me elaborate - Imagine I have a form with 4 input fields and one textarea. Alongside that, t ...

The Role of Filling in a Process

I am looking to create a rectangle that fills up gradually every day, increasing by 1% each time. This is the basic concept. My main struggle is figuring out how to fill it up. I need the rectangle to increase by 1% of its width each day. So essentially, ...

Adjust size of item within grid component in VueJS

I have a grid container with cells and a draggable item in a Vue project. I am trying to figure out how to resize the box inside the grid component (refer to images). https://i.stack.imgur.com/q4MKZ.png This is my current grid setup, and I would like the ...

Using HTML <style> in a bash script is a great way to enhance

I am attempting to eliminate the bullet points from HTML code generated by a bash script. I am currently struggling to apply the style across the entire program. Given my limited knowledge of html, I suspect that I may be misinterpreting or incorrectly p ...

What is the best way to insert an image in front of text within a table cell that can be identified by its class name?

JavaScript Question: function addFlags(){ while(i < $('.tabledata').length){ var current_val = $('.tabledata').eq(i).text(); arr.push(current_val); $('.tabledata').eq(i).html("<img s ...

What is the Best Way to Ask Users Not to Delete Local Storage Information?

As I work on developing an application using angularJS, the need to save data locally has arisen. To achieve this, I am utilizing HTML5 local storage. One challenge faced with HTML5 local storage is that when a user clears their browsing data, all stored ...

Managing the ajax response to showcase a button within datatables

Here is my current datatable structure: <table id="list" class="display" width="100%" > <thead> <tr> <th>Title</th> <th>Description</th> <th>delete</th> ...

Stop capturing mouse and keyboard events within a specific div element on all web browsers

I manage a website with forms that have jquery autosave features and are updated using ajax. These forms include various types of input elements such as textboxes, jQuery UI datepickers, and time pickers... <div id="content"> <form id="line1"&g ...