Leverage JavaScript to customize the appearance of existing links within an external HTML document

Forgive me for my lack of expertise in Javascript. I will do my best to explain clearly.

On my website, I have an external html file for the navigation menu that is loaded with javascript to simplify editing (so I don't need to update nav elements on every page). To insert the nav menu, I used this script:

<script>
$(function(){
$("#nav").load("nav.html");
});
</script>

This script, along with the div below, successfully loads nav.html without any issues.

<div id="nav"></div>

Now, I want to add a unique style to the current link (the link corresponding to the current page). After extensive research, I found the following script as the best solution:

<script>
$(document).ready(function(){
var str=location.href.toLowerCase();
$("a").each(function() {
if (str.indexOf(this.href.toLowerCase()) > -1) {
$("a").removeClass("current");
$(this).addClass("current");
}
});
})
</script>

However, this script only works if the link is directly written into the main html file and not when it is loaded from an external html file. Here is a snippet from the external nav.html file:

<a class="nav-link" href="projects/senseofspace" target="_top">Sense of Space</a>
<a class="nav-link" href="projects/gsac" target="_top">GSAC Accessibility</a>
<a class="nav-link" href="projects/jonahecologycenter" target="_top">Jonah Ecology Center</a>

As you can see, these links are already styled based on settings from the css file provided below:

a.nav-link:link {display:block; padding-left:5px; text-decoration:none; color:rgb(210,210,210);}
a.nav-link:visited {display:block; padding-left:5px; text-decoration:none; color:rgb(210,210,210);}
a.nav-link:active {display:block; padding-left:5px; text-decoration:none; color:black; background-color:white;}
a.nav-link:hover {display:block; padding-left:5px; text-decoration:none; color:black; background-color:white;}
a.nav-link {position:relative; display:block; left:10px; line-height:150%;}

I want the "current" link to be styled differently with the following specifications:

a.current:link {display:block; padding-left:5px; text-decoration:none; color:black; background-color:white;}
a.current:visited {display:block; padding-left:5px; text-decoration:none; color:black; background-color:white;}
a.current:active {display:block; padding-left:5px; text-decoration:none; color:black; background-color:white;}
a.current:hover {display:block; padding-left:5px; text-decoration:none; color:black; background-color:white;}
a.current {position:relative; display:block; left:10px; line-height:150%;}

The main html files contain script in the header, including a link to jQuery.js 1.11.0, but the external html navigation file does not.

If you require further clarification, please feel free to reach out. Thank you!

Answer №1

Ensure to execute the functions like .each(), .addClass(), etc. only after incorporating the new HTML elements into the DOM.

Consider this approach:

$( "#nav" ).load( "nav.html", function() {
    var pageUrl = location.href.toLowerCase();
    $("a").each(function() {
        if (pageUrl.indexOf(this.href.toLowerCase()) > -1) {
            $("a").removeClass("current");
            $(this).addClass("current");
        }
    });
});

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

Why does the flex-start and flex-end values correspond to the top and bottom positions when using the flex-direction property set

I am attempting to organize text and buttons into a row, with the buttons aligned on the right side and the text on the left side. My approach involves creating a flexbox layout and assigning items the appropriate classes for alignment. html, body { widt ...

Is there a way to get pQuery to function properly with HTML that is slightly malformed?

pQuery is an innovative adaptation of the jQuery JavaScript framework to Perl that serves the purpose of screen scraping. pQuery has shown a high sensitivity to malformed HTML content. Take, for instance, the following scenario: use pQuery; my $html_mal ...

How can you retrieve newly added DOM elements from a PartialView using Ajax.BeginForm?

Below is a snippet of code that loads a Partial View within a div element: <div id="_customerForm"> @Html.Partial("~/Views/Customer/_customerForm.cshtml", Model.customerForm) </div> The Partial View contains an Ajax Form as shown ...

JQuery AJAX call not showing the outcome of PHP execution

I have a form that utilizes AJAX to send data to a PHP file for processing on the server-side and then returns the results. Check out the HTML form below: <div id="new_loc"> <form id="loc_form" method="post" action=""> <p><b> ...

Updating data in a SQL database using PHP when a button is clicked

This Question was created to address a previous issue where I had multiple questions instead of focusing on one specific question Objective When the user selects three variables to access data, they should be able to click a button to modify one aspect o ...

Tips for verifying the password of a protected post using ajax?

I have set a password for a protected post. Now, I want to verify the entered password using ajax. Here is the HTML code: <form class="protected-post-form" action=".../wp-pass.php" method="post> <input name="post_password" id="pwbox-4470" t ...

When you scroll through the page, white blocks suddenly appear

After completing a website, I noticed some white blocks appearing when scrolling. You can view the site here. This issue occurs on both mobile and desktop devices during the initial load only. Could this indicate that the page has not fully loaded yet? If ...

Swapping out ChildNode data for HTML elements

When attempting to replace a node value with HTML content, I encountered an issue where the HTML tags were being displayed on the HTML page instead of applying the intended style. <style> .YellowSelection { background: yellow; } < ...

Creating a clickable table row in bootstrap with optimal effectiveness

Is it better to implement a clickable row using jquery or pure JS? Consider server and client efficiency Ensure compatibility with various browsers The jquery option: // my tr (row) class <tr class='clickable-row' data-href='url:www.g ...

What is causing the Bootstrap accordion to not display content when clicked on?

As a beginner in web development, I am currently working on my very first website. One issue I'm facing is with incorporating an accordion-style card in my webpage. Although it allows me to click on different titles, the collapsed ones fail to expand ...

The tabs functionality is broken due to an upgrade in jQuery and jQuery UI

I recently upgraded my website to use the latest versions of jQuery and jQuery UI, but I'm facing some unexpected issues with the Tabs widget. Previously, everything was working fine with jQuery 1.5.1 and jQuery UI 1.8.4. After upgrading to jQuery 1. ...

Unleash the power of jQuery to leverage two different input methods

Here is the code I'm working with: $('input[type="text"]').each(function(indx){ Right now, this code targets input elements with type "text". But how can I modify it to target both inputs with type "text" and "password"? Any suggestions o ...

The jQuery selectors are not able to identify any dynamically generated HTML input elements

After successfully injecting HTML code into the DOM using Ajax, I encountered an issue where my jQuery selector was not working for a specific HTML input element. For example, when attempting to use the following jQuery code: $("input[id*='cb_Compare ...

What is the method to retrieve the image's value after dropping it onto the droppable area?

I have implemented a drag and drop feature using jQuery, and I am trying to extract the value of an image and insert it into a database. Additionally, I want to update and remove the image value when it is removed from the droppable area. How can I achie ...

Storing information in a table before having an assigned ID

Currently, I am developing a CMS using Codeigniter which consists of standard fields like title and post content, similar to Wordpress. On my page, there is an image uploader that utilizes ajax to save images to a MySQL table with basic fields including i ...

The webpage becomes unresponsive and gets stuck when sending a stream of requests to the web server via ajax

I am currently working on creating a signal on the webpage that displays either a green or red color based on values retrieved from a database. However, when I send a request after 10 seconds, the page appears to freeze and becomes unresponsive. I am strug ...

Why is the 3D CSS transform (translateZ) feature malfunctioning on Android 4.0.3?

I have this HTML code that is functioning well on Chrome, Safari, and Mobile Safari. However, when testing it on Android 4.0.3, the translateZ property does not seem to have any desired effect on the div element. While everything else works as expected, ...

jQuery's p:parent selector fetched an extra element

Currently, I am delving into the depths of the jQuery API with a specific focus on the :parent selector. Behold my html and jQuery code. <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title ...

A div housing a jQuery progress bar within an unordered list (ul)

Having an issue incorporating a jQuery progress bar into a ul li tag. <ul> <li> <a href="test">test</a> <div id="progressbar"></div> </li> </ul> I have set display: block for the anchor tag and ...

Tips for showcasing a full body height background

I'm currently working on a project where I need to display random background images when the body loads. To achieve this, I've created a function. However, I'm facing an issue where the images are filling up the entire page, making it very l ...