Removing unnecessary code from a jQuery script

I have created a page that loads data through AJAX using the jQuery .load function.

When loading a new file by clicking on a tab on the bar, I change the selected tab's color to yellow using jQuery. Initially, I tried using the .toggleClass function to set the class of an li element to active and turn it yellow, but it didn't work, so I ended up resetting the CSS every time.

How can I reduce the redundant code or completely revamp the script?

Here is the jQuery script. Any help would be greatly appreciated!

$(document).ready(function () {
    $('a#catalog').click(function() {
        $("#nav ul li a").css("color","white");
        $(this).css("color","yellow");
        $("#content").load("files/catalog.html");   
    });
    $('a#request').click(function() {
        $("#nav ul li a").css("color","white");
        $(this).css("color","yellow");      
        $("#content").load("files/request.html");
    });
    $('a#publisher').click(function() {
        $("#nav ul li a").css("color","white");
        $(this).css("color","yellow");
        $("#content").load("files/publisher.html");
      });
    $('a#incoming').click(function() {
        $("#nav ul li a").css("color","white");
        $(this).css("color","yellow");
        $("#content").load("files/incoming.html");
    });
    $('a#finished').click(function() {
        $("#nav ul li a").css("color","white");
        $(this).css("color","yellow");
        $("#content").load("files/finished.html");
    });
    $('a#shipments').click(function() {
        $("#nav ul li a").css("color","white");
        $(this).css("color","yellow");
        $("#content").load("files/shipments.html");
    });
});

Below is the navigation bar:

<div class="bar" id="nav">
            <ul class="left">
                <li><a href="#" id="request">Request Search</a></li>
                <li><a href="#" id="catalog">Catalog Search</a></li>        
                <li><a href="#" id="publisher">Request from Publisher</a></li>
                <li><a href="#" id="incoming">Catalog Incoming Files</a></li>
                <li><a href="#" id="finished">Send Finished Files</a></li>      
                <li><a href="#" id="shipments">Shipments</a></li>
            </ul>
        </div>

And finally, the CSS styles are as follows:

.bar { margin: 5px 0; position: relative; height: 20px; background-color: #515e6c; }
.bar a { color: #fff; }
.bar ul li a:hover { color: yellow; }
/* .bar ul li.active { color: yellow; } */
ul { margin: .3em 0; }
ul li { display: inline; padding: 0 5px; border-right: 1px solid #fff; }
ul li:last-child { border-right: none; }

Thank you in advance for any input!

Answer №1

Here is the solution you need:

$(document).ready(function () {
    var $links = $('#nav ul li a');
    $links.click(function() {
        $links.css("color","white");
        $(this).css("color","yellow");
        $("#content").load("files/" + $(this).attr('id') + ".html");       
    });
});

To address your specified rule, update it to this:

.bar ul li a.active { color: yellow; }

You can then modify the initial two lines of the click function with the following:

$links.removeClass('active');
$(this).addClass('active');

The original problem stemmed from applying the style to the <li> instead of the <a>.

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

Unable to display elements from an array in the dropdown menu generated by v-for

Having just started learning Vue.js, I am facing a challenge in rendering the following array: countries: ["US", "UK", "EU" ] I want to display this array in a select menu: <select> <option disabled value="">Your Country</option& ...

Is there a simpler method to access the source element for an event?

I'm just starting to learn JavaScript and jQuery, and right now I have the following code in my HTML: <a id="tog_table0" href="javascript:toggle_table('#tog_table0', '#hideable_table0');">show</a> After that, I hav ...

Display a message following the final ajax request made in AngularJS

I've been attempting to make multiple AJAX calls within a loop. My goal is to display a message only when the final AJAX call is successful. Can anyone provide feedback on what I might be doing incorrectly here? $scope.defer = $q.defer(); ...

Tips for securely transmitting data via a hidden form using the POST method

I have a query that displays records of people, and I want to send the id_Persona using a hidden form through a post function to the idsPersonas.php page. However, when I try to do this, it redirects me to an undefined page. Here is the code snippet: < ...

How can I dynamically adjust the size of an image in a directory based on its filename with php?

Is it possible to resize a specific image in a folder by its name using PHP? ..................................................................................................................................................................... I have trie ...

Searching in Django utilizing jQuery keyup

When implementing a search functionality using the jQuery keyup function, I have set up my views to display the searched contacts in a template. Here is how my views are structured: def contacts_profile(request, search_id=None): contact = Invitation.o ...

Issue with ngModel value not being accurately represented by checkbox state in Angular 2

My issue lies with a checkbox that does not reflect its ngModel value. To provide some context, I have a Service managing a list of products and a component responsible for displaying this list and allowing users to select or deselect products. If a user d ...

The query for Node.js using mysql is not defined

Recently, I've been working with Node.js and attempting to incorporate mysql in conjunction with nodejs. Specifically, I have written a query trying to retrieve numbers from a table: select numbers from TABLE, but the end result shows up as: "undef ...

Leverage the power of Vuex within your Nuxt application

I successfully obtained and displayed data using Nuxt's Fetch API, but now I'm looking to transition to using Vuex instead. store/index.js: import Axios from 'axios' export const getters = { isAuthenticated: (state) => { retu ...

DxDataGrid: Implementing a comprehensive validation system for multiple edit fields

I'm currently working with a DxDataGrid within an Angular Application. Within this particular application, I have the need to input four dates. I've implemented validation rules that work well for each individual field. However, my challenge aris ...

"Verifying the dimensions of the input sizes with the i

It's possible that this question has been asked before on this platform. However, I haven't come across a satisfactory answer yet. How can I adjust the size of inputs in the iCheck library? The current size is too large for my website. Css: .ic ...

Move to the first item on the list without any unnecessary scrolling of the view - ReactJS

Whenever I try to scroll to a specific item in the list, clicking on it causes the entire view to scroll instead. Is there a way to ensure that only the div containing the list scrolls? <AlertsList> {productInventoryAlert?.map((prod ...

What happens if I attempt to pass a blank field in multer?

I am trying to verify if the image field passed to Multer will include the file. There are no errors being thrown by Multer and the server is currently processing the request. ...

When utilizing the data property within the useQuery() hook, an error may arise stating "Unable to

This problem has me scratching my head. The code snippet below is triggering this error: TypeError: Cannot read properties of undefined (reading 'map') When I use console.log() to check res.data, everything seems normal and there is data present ...

The size of table td is less than 100%

I'm having trouble getting my td to fill 100% of my table. I have tried using the following code: .table-scroll tbody { display: block; overflow-y: scroll; height: calc(100% - 130px); } Even with the display block property, the td element is s ...

Creating a directive in AngularJS to automatically populate select options with custom values

As someone who is relatively new to creating directives, I am looking to develop a directive that will assist me in my application. What I aim to achieve is a select element directive that comes pre-populated with options and is self-contained. All I need ...

Converting User Input Special Characters to HTML5 data-attributes with URL Encoding/Decoding

Seeking assistance from the experts on my first question here at stackoverflow. Our web application allows users to input escape/special characters, and we are conducting testing for extreme scenarios. I have successfully passed escape characters through a ...

Utilizing a NodeJs Express app.get to manage both query strings and parameters

In my quest to develop a REST Service, I have crafted a route that triggers the execution of a stored procedure and retrieves JSON results. app.get('/spparam', function (req, res) { var sql = require("mssql"); // Database configuration var id=0 ...

How to identify NaN in JavaScript code?

I am attempting to use JavaScript to determine the number of days in a selected month of a selected year. However, I keep receiving a NaN value as a result. How can I resolve this issue? Thank you. <script> function myFunction() { var month ...

One-time execution of timed event

I'm struggling to get this function working properly. In my system, users can approve or disapprove a post by clicking on a link. All the content is loaded using ajax calls. When a user clicks, an alert pops up indicating success or error and then r ...