Having trouble with jQuery loading for the first time

I am having trouble getting the jQuery to load properly. My goal is to toggle classes on specific items identified by their ID.

When an item is clicked, I want it to have the class "menu-selected" while the other item has the class "unselected."

I have included all the necessary HTML below. I'm not sure if there's a mistake in my HTML or CSS, as the functionality hasn't changed since I added the JS code.

Could I have imported jQuery incorrectly?

Is there an issue with my script?

Have I placed everything in the correct order?

Code:

    <!DOCTYPE html>
    <html>
    <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $('#left-cafe').click(function(){
                $('#left-cafe').removeClass('unselected');
                $('#left-cafe').addClass('menu-selected');
                $('#left-breakfast').removeClass('menu-selected');
                $('#left-breakfast').addClass('unselected');
            });
        });
    </script>
    <style>
        .left-menu{
            background-color:rgb(200,200,200);
            display:block;
            float:left;
            width:100%;
            height:50px;
        }
        .left-menu-list{
            width:100%;
            height:100%;
        }
        .left-menu-list li{
            display:block;
            float:left;
            width:20%;
            height:100%;
            font-size:35px;
            line-height:75px;
            }
        .menu-selected{
            background-color:rgb(150,150,150);
        }
        .unselected{
            display:none;
        }
    </style>
    </head>
    <body>
        <div class="left-menu"> <!-- Start left-menu -->
            <ul class="left-menu-list">
                <li class="menu-selected" id="left-cafe">Cafe</li>
                <li class="unselected" id="left-breakfast">Breakfast</li>
            </ul>
        </div> <!-- End left-menu -->
    </body>
    </html>

Answer №1

Your code is free of jQuery errors, but there is a logic error present.

       
$(document).ready(function(){
     $('#left-cafe').click(function(){
         
          $('#left-cafe').toggleClass(' menu-selected unselected');
               
          $('#left-breakfast').toggleClass(' menu-selected unselected');
     });
});
 .left-menu {
     background-color:rgba(200, 200, 200,1);
     display:block;
     float:left;
     width:100%;
     height:50px;
 }
 .left-menu-list {
     width:100%;
     height:100%;
 }
 .left-menu-list li {
     display:block;
     float:left;
     width:20%;
     height:100%;
     font-size:35px;
     line-height:75px;
 }
 .menu-selected {
     background-color:rgba(150, 150, 150, 1);
 }
 .unselected {
     display:none;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<body>
    <div class="left-menu">
        <!-- Start left-menu -->
        <ul class="left-menu-list">
            <li class="menu-selected" id="left-cafe">Cafe</li>
            <li class="unselected" id="left-breakfast">Breakfast</li>
        </ul>
    </div>

You are attempting to remove and add the same class again, resulting in no difference in your output. Instead, you should toggle the class for the desired effect.

Answer №2

Encountering an issue in your script? Try using the following JavaScript code instead:

$(document).ready(function () {
    $('#left-cafe,#left-breakfast').click(function () {
        $(".menu-selected").removeClass("menu-selected").addClass("unselected");
        $(this).addClass("menu-selected");
    });
});

Check out the Live Demo Here

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

Is it recommended to place the styles created by material-ui for child components after the styles generated for the parent component?

Utilizing material-ui, which utilizes JSS for styling a website. I have a component named Layout that applies margin to all its children (using the all children selector & > * in its style). This functionality works, but I would also like the child ...

How to center a responsive image in a container using Bootstrap

How can I properly center my banner and place the logo above it? Currently, both elements are not centered as desired. View the live version here: http://codepen.io/anon/pen/waYBxB HTML Code: </head> <body> <!-- LOG ...

Automatically updating client-side values in AngularJS using setInterval()

Implementing a value calculator on the client side using AngularJS. I need to update the main value of the calculator every 5 minutes with setInterval(). This is my AngularJS code: $http({method: 'GET', url: '../assets/sources.json'} ...

Tips on extracting the ID number prior to locating an element by its ID using Python Selenium

I am currently attempting to automate sending LinkedIn connection requests using Python with Selenium. However, I am facing an issue where the ember number value keeps changing every time I try to copy the id of the button. Sometimes it shows as #@id=" ...

Encountering an error while trying to launch Chrome with Puppeteer

Currently, I have set up an elastic-beanstalk instance on AWS and am in the process of creating a pdf export feature on a dashboard using Puppeteer. Although I have successfully tested the application locally, I encountered an error when attempting to run ...

What is the best way to set breakpoints on Material UI components?

Currently, I am exploring material-ui and I'm curious if there is a way to set all breakpoints at once. The code snippet below seems quite repetitive. Is there a more efficient method to achieve this? <Grid xs={12} sm={12} md={12} lg={12} xl={12} ...

Pattern matching system to replace only the single occurrence of a character preceding a particular sequence

I have a lot of HTML code that looks like this: <a href="http://example.com/project-a" title="Project A (test)">Project A (test</span></a> <a href="http://example.com/project-b" title="Project B (test)">Project B (test</span> ...

The table does not move up or down when using the mousewheel over the rows, but only when

I'm encountering an issue with a table inside a div that has overflow-y: scroll applied to it. While the scrollbar appears when there is content overflow, I am unable to scroll using the scrollwheel. It only works when the cursor is directly on top o ...

Using importXML with Internet Explorer 11

My project website includes a roster page that retrieves XML data. Previously, this functionality worked across all browsers but now it only works in Chrome. In IE11, it seems that the importXML function is not functioning correctly as the roster data is m ...

Drawer in Material-UI has whitespace remaining at the corners due to its rounded edges

While using the Material UI drawer, I attempted to round the corners using CSS: style={{ borderRadius: "25px", backgroundColor: "red", overflow: "hidden", padding: "300px" }} Although it somewhat works, the corners appear white instea ...

When adding values, they remain in their original positions

I am populating a select dropdown with options using AJAX. These options are added based on the selection made in another dropdown. The first function that appends the data: var appendto_c = function(appendto, value, curcode) { appendto.append("& ...

In search of a React.js/Redux OpenID library or example, particularly focused on Steam OpenID integration

Currently, I am developing a Node/Express REST + React/Redux application that requires Steam OpenID for authentication. Despite searching extensively for tutorials, libraries, or example code related to Steam OpenID (or any other OpenID), I have come up em ...

Choose a drop-down menu with a div element to be clicked on using Puppeteer

Issue Description: Currently encountering a problem with a dropdown created using material select. The dropdown is populated through an API, and when selected, ul > li's are also populated in the DOM. Approaches Tried: An attempt was made to res ...

Implementing individual NGRX Selectors for each child component to enable independent firing

My component serves as a widget on a dashboard, and I am using *ngFor to render multiple widgets based on the dashboard's data. Each WidgetComponent receives some of its data via @Input() from the parent. parent <app-widget *ngFor="let widget ...

Troubleshooting: Issues with Jquery's has, find, contains functions

As I check whether an element contains another element, I've previously utilized the jquery element.has(secondElement) function. In my angularjs project, I make use of jquery within a directive where I transclude elements through markup using ng-tran ...

Chaining inheritance through Object.create

Recently, I decided to experiment with Object.create() instead of using new. How can I achieve multiple inheritance in JavaScript, for example classA -> classA's parent -> classA's parent's parent, and so on? For instance: var test = Objec ...

Capturing errors from various pages with the Jquery Ajax .ajaxError event

Is there a way to display various Ajax request response errors in a universal dialog, similar to a standard error page? Can we capture error descriptions from multiple Ajax calls on different pages and display them using a common Ajax error event? $(doc ...

Ways to include a CSS file path in a link tag from an npm package

I have recently installed a package using npm. npm install lightgallery Now, I am trying to fill the href attribute of a link with the css file directory of this package. Here is what I have so far: <link rel="stylesheet" href="/node_mod ...

Encountering an error in accessing my own API: "Cannot read property 'then

I'm currently in the process of using my personal express.js API with nodejs. Although it is functioning, I am encountering an error that is preventing me from accessing the response of the request. Below is a snippet of my code: routes.js: app.post ...

Having trouble setting a value in a Vue.js variable

Upon assigning a value retrieved from the firebase collection, I encountered the following error message. Error getting document: TypeError: Cannot set property 'email' of undefined at eval (Profile.vue?5a88:68) Here is the code snippet in que ...