Changing the background color using jQuery switch case statement

I am attempting to utilize jquery to dynamically change the background image of a webpage based on different cases in a JavaScript switch statement. I have completed three steps:

1) Included this script tag in my HTML document:

<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>

2) Set up my switch case (which I confirmed is being triggered) in the HTML document like this:

function calcBackground() {
switch(counter) {
case 1:
    $('body').toggleClass('background1');
    break;
case 2:
    $('body').toggleClass('background2');
    break;
case 3:
    $('body').toggleClass('background3');
    break;
default:
    //no significant action
}
}

3) Added the following CSS code:

body {
    background-repeat: no-repeat;
    background-image:url('http://hdwallpicture.com/wp-content/uploads/2013/08/Blue-Widescreen-HD-Wallpapers.jpg');
    background-size: 100% auto;
}

body.background1 {
  background-image:url('http://hdwallpicture.com/wp-content/uploads/2013/08/Blue-Widescreen-HD-Wallpapers.jpg');
}

body.background2 {
  background-image:url('http://3.bp.blogspot.com/-vmh1i-b3XNY/T9iTjPGKYZI/AAAAAAAAFwo/jv3Yysxcl9Q/s1600/Blue-wallpaper-23.jpg');
}

body.background3 {
  background-image:url('http://wallpaper4god.com/wallpapers/blue_1269_1076x768.jpg');
}

Note: The URL for body.background1 is intentionally the same as the default background URL for the page. However, the backgrounds are not changing when the switch statement is executed.

What could be missing or incorrect in my implementation?

Answer №1

It seems like you are not removing any classes in your current implementation. This could lead to all three classes eventually being applied to the body element, especially if this code is part of a slideshow.

Consider incorporating the following function:

function changeBackground() {
    switch (counter) {
        $('body').removeClass('background1 background2 background3');
        case 1:
            $('body').addClass('background1');
            break;
        case 2:
            $('body').addClass('background2');
            break;
        case 3:
            $('body').addClass('background3');
            break;
        default:
            // no specific action
    }
}

Answer №2

Initially, it appears that there is no presence of a counter, so one can assume that it has not been set. A potentially tidier function could be devised like this:

function updateBackground() {
    if(typeof counter !== 'undefined'){
        $('body').removeClass('background1 background2 background3')
                 .addClass('background' + counter);
    }
}

Alternatively, if the body element does not hold any additional classes (ever):

function updateBackground() {
    if(typeof counter !== 'undefined'){
        $('body').attr('class', 'background' + counter);
    }
}

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

Navigate a user upon completion of an update

My webpage requires users to click an update link, which triggers a process of fetching data from an API that takes a few minutes. I don't want users to have to constantly refresh the page to know when the process is complete and they can continue. Is ...

What could be the issue with this C# GridView code snippet?

I am facing an issue with a GridView that contains checkboxes. When I try to select a checkbox, I need to retrieve the values from that specific row. The problem lies in the fact that the chk variable in my C# code never evaluates to "true," preventing the ...

CSS selector for GTM trigger that is not specific to any particular element

I am attempting to develop a CSS selector that can target the specific entries within the page-top-menu: Header menu - Menu 1 DE #page-top-menu > div > div.menu-wrapper > ul > li.i39.dropdown.layer.item-type-1.catid-0eca5a6c6e53f281b9e0469ca3d ...

Trigger a fixed bottom bar animation upon hover

I have a bar fixed to the bottom of the browser that I want to hide by default. When a user hovers over it, I want the bar to be displayed until they move their cursor away. <!doctype html> <html> <head> <meta charset="utf-8"> &l ...

Expanding the Number of Arguments Sent to a Callback Function

I have a scenario where I am using a method that sends a POST request and then triggers a specific callback function to manage the response: myService.verify(id, verificationCallback); function verificationCallback(err, response) { ... } My query is two ...

Assistance with organizing date schedules using Javascript

I'm currently assisting a friend with his small project, and we've run into an interesting situation. Imagine a scenario where a doctor informs their patient that starting today, they have X number of consultations scheduled for every Wednesday a ...

Inconsistencies in Height Among JQuery Elements

I am encountering an issue with my datatable.js, where I am attempting to limit its height based on a specific row number, such as 4.5 rows. However, I am facing a problem with the row height (tr height). For example, when using the following method with m ...

Issue with SVG on tainted canvas causes IE security error when using toDataURL

In my Angular JS directive, I have implemented a feature to export SVGs to PNG. While this functionality works seamlessly in most browsers, it encounters a security error in IE. Despite my numerous attempts to troubleshoot the issue, I have been unable to ...

Arranging a flex item below another flex item within a flexbox container

Is there a way to use flexbox to ensure that the 2.5 element is placed below the 2 element instead of beside it on the same row within the flex container? Given the HTML provided, how can I achieve this layout using flexbox? I attempted to accomplish thi ...

Unable to retrieve jwt token from cookies

Currently, I am developing a website using the MERN stack and implementing JWT for authentication. My goal is to store JWT tokens in cookies. Despite invoking the res.cookie function with specified parameters (refer to the code below), I am facing difficul ...

Is there a way to adjust the width of a table cell in Material UI using React?

I encountered a problem where I am attempting to adjust the width of a table cell, specifically in Typescript. However, I am only able to choose between medium and small sizes for TableCellProps. Is there a workaround for this issue? I am looking to expand ...

Having trouble finding the right path. Is there an issue with Angular routing?

After successfully creating a simple application, I decided to write test cases for it. My first attempt was to work on the routing part of the application. Check out the code on StackBlitz The routing code snippet is as follows: Main module: export cons ...

PHP is failing to redirect the user to the correct index.php file

I encountered an issue in Jquery Mobile that has left me puzzled. Upon entering the site, users are prompted to either register or login. When selecting register, they are redirected to a page where they input their information. Once completed, the data is ...

What is causing the extended wait times for ttfb when utilizing Local IIS?

Despite consistently receiving performance test results of around 50ms on my server, the response times for calls to controller methods in my C# code using AngularJS (1.4) or jQuery (1.9.1) are varying greatly. Sometimes the data is returned in less than 1 ...

Is it possible to exclusively target a child div using JavaScript in CSS, without affecting the parent div?

I'm in the process of developing a calendar feature where users can select a specific "day" element to access a dropdown menu for time selection. The functionality is working fine, but I've encountered an issue. When a user selects a time from th ...

Tips for transforming a JSON array of file paths for images hosted on a server into a JavaScript array for showcasing them. Leveraging the power of AJAX

I am looking for a way to use HTML file/ajax code to extract the JSON message and store the PATHS as a JavaScript array. This will allow my buildImage function to display the first image in the array. I am new to AJAX and suspect that my issue lies in conv ...

Tips for personalizing the tooltip on a line chart in Vue.js using Chart.js

Attempting to create a line graph using chart js and vue, but new to both technologies. In the chart below, I am trying to change the tooltip to display "10 Answers July 19, 2023". I have attempted to use the beforeLabel and afterLabel options without succ ...

Utilizing ng-model to bind object values from radio inputs

Dealing with a JSON file: $scope.favoriteThings = [ {nr: 1, text: "Raindrops on roses"}, {nr: 2, text: "Whiskers on kittens"}, {nr: 3, text: "Bright copper kettles"}, {nr: 4, text: "Warm woolen mittens"}, {nr: 5, text: "Brown paper pac ...

Can the value in a JavaScript object be updated dynamically when a button is clicked?

In my JavaScript code, there is an object named annualPlan. Whenever a user submits the HTML form for a specific month, I aim to update the value in the object for that particular month accordingly. For instance, if someone submits August 21 and 200, I w ...

Attaching events to the window in Vue.js

Having recently started working with Vue.js, I have come across a problem related to attaching and detaching keyboard events to the window within one of my components. Below are the methods I am using: created() { this.initHotkeys(); }, beforeDestroy() ...