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

Reference now inactive in an array object no longer exhibiting reactivity

After implementing the following code successfully, we noticed that changing the language updates the text correctly thanks to the ref: const mainNavigationLinks = computed(() => [ { label: context.root.$t('navigationMenu.home') }, { labe ...

Verifying Several Inputs with Jquery

I need guidance on setting up 2 independent inputs with a single submit button. There are 2 input elements that will each post a different element id back. Each input will validate its input separately, showing its own error message. This is an overview ...

Error: npx is unable to locate the module named 'webpack'

I'm currently experimenting with a customized Webpack setup. I recently came across the suggestion to use npx webpack instead of node ./node_modules/webpack/bin/webpack.js. However, I am encountering some difficulties getting it to function as expecte ...

What is the best method for parsing information from the HTML source code of a specific tab on a webpage?

I have tried various methods mentioned in different responses, such as testing with different user agents (Chrome, Safari etc), and fetching HTML directly using HTTPClient and BufferedReader, but unfortunately none of them seem to be effective. How can I ...

Implement a dynamic order form using JQuery to automatically update prices and securely store customer information

Currently, I am utilizing Wordpress as the content management system for this particular website. The site consists of various products that are categorized differently. These products are stored under a custom post type labeled 'product.' I am ...

The vertical alignment feature seems to be malfunctioning in Bootstrap 4

My goal is to center multiple images within their respective divs, but I am facing issues with vertical alignment not working as intended. Even the CSS classes d-flex justify-content-end and text-center are failing to align the icons side by side. I need t ...

The Autoprefixer script crashes with the error message: TypeError - Patterns can only be a string or an array of strings

After successfully installing autoprefixer and postcss-cli, I embarked on setting up a simple build process with NPM scripts using my command prompt and VS code. As someone with only 2 months of coding experience, I was following a tutorial on CSS/SASS top ...

What is the best way to convert an object array into an array with identifiers for duplicate values?

Working with the following array of objects: const data = [ {count: 400, value: "Car Wash Drops"}, {count: 48, value: "Personal/Seeding"}, {count: 48, value: "Personal/Seeding"}, ]; I want to use the map function to create an array with an addition ...

Encountered an issue while building npm: "Error: Unable to locate module @restart/context

Lately, I've encountered an issue with npm build after upgrading to the latest version of react-bootstrap (1.0.0-beta.6). While creating an optimized production build... Failed to compile. Module not found: '@restart/context/forwardRef'. P ...

Setting up a connection to MongoDB on a local network using express and mongoose

As I set up a server with express and mongoose, my goal is to make it accessible on other devices within my local network. To achieve this, I configured the bind_ip variable to 0.0.0.0 in the Mongodb configuration file. const connection = mongoose .co ...

Displaying text underneath an image

Hey everyone, I'm currently working on getting some text to show up below an image using Bootstrap 3. Here's what I have so far: <div class="row"> <div class="col-xs-12 col-sm-6 col-md-3"><img alt="my image" class="img-about" ...

Error message: Uncaught SyntaxError: Unexpected import token encountered in (ReactJS, Babel, Webpack, NodeJS)

I've been struggling for days to get this simple Hello World app working using ReactJS and Babel. I have installed node.js and webpack, but unfortunately, I keep encountering the following error: Uncaught SyntaxError: Unexpected token import Below ...

Using Backbone to Handle Different Data Formats

I have a unique text file containing date-time data in the format below: 2014-03-14T16:32 2014-03-15T13:04 2014-03-16T06:44 ... I want to use this static file as a read-only data source for my backbone collection. However, the current format is not suita ...

verification tool for a less file's syntax

Searching for a tool to validate a specific less file at the syntax level. The issue lies in the validator not recognizing dependencies or detecting declared mixins. Many existing less processors do not work due to missing dependencies that cannot be prov ...

Setting the value of a custom component property dynamically after the component has been rendered

I'm currently developing an Angular application and have a specific requirement to work on. I am using a custom component with 3 inputs, and I want to bind this custom component tag in the HTML of my page. <my-column [setInfo]="info" [dis ...

To ensure responsiveness in JavaScript, adjust the width to 100%

Recently, I came across this piece of code: <div style="text-align:center; max-width:500px; width:100%; margin:auto"> <script type="text/javascript" src="transition_example.js"></script></div> Here is the content of transition ...

What is the best way to bring up the keyboard on an iPhone when focusing an HTML text field?

Currently working on developing a web app for iPhone, and looking to implement a feature where a text field is automatically focused upon page load, prompting the keyboard to appear. Despite attempting the standard Javascript method: input.focus(); I see ...

Passing a div's ID value using AngularJS AJAX to store it in a PHP variable

I have a collection of div elements, each with a unique id. My goal is to trigger a JavaScript function when a specific div is clicked. This function should send the id value of the clicked div to PHP, assign it to a PHP variable, and then receive a respon ...

Checking parameters from two forms that are both associated with the same model in Rails

Recently, a new feature was added to the system - a phone and sim checker. Users are required to input their phone number into the first form. If the phone number is found in the database, a message indicating this is displayed. Otherwise, the form switche ...

CSS/HTML: Resolving Internet Explorer's Div Positioning Challenges

I've been struggling to find a resolution for this issue but I haven't been able to come up with anything effective. Here's the basic concept of what I'm trying to achieve. My goal is to have my layout divided into 3 divs. The first se ...