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

Mastering AngularJS - Field Population with Blinking Placeholders

I understand that AngularJS fills in fields through their model. HTML is loaded first: <input type="text" data-ng-model="data.myValue" placeholder="example"> The JavaScript code comes next: $scope.data = {}; $scope.data.myValue = 'hello my v ...

Velocity.js causing a slowdown in animated performance

Currently, I am attempting to animate spans, and while the animation is functional, it appears to be somewhat choppy and lacks smoothness. https://codepen.io/pokepim/pen/JBRoay My assumption is that this is due to my use of left/right for animation purpos ...

Cease the execution of a task in Express.js once the request timeout has been

Suppose we have the following code snippet with a timeout of 5 seconds: router.get('/timeout', async (req, res, next) => { req.setTimeout(5000, () => { res.status(503) res.send() }) while (true) { ...

Managing Server Crashes in Node.js

Is there a way to automatically update the database whenever my node.js server crashes or stops? Similar to how try{}catch(){}finally(){} works in JAVA. I am new to this. Does Node emit any events before shutting down so that I can run my function then? ...

Color picker can be utilized as an HTML input element by following these steps

After trying out various color pickers, I was not satisfied with their performance until I stumbled upon Spectrum - The No Hassle jQuery Colorpicker. It perfectly met my requirements. <html> <head> <meta http-equiv="content-type" content="t ...

Issue with Vue.js where the v-if directive placed inside a v-for loop does not properly update when

I want to dynamically show elements from an array based on boolean values. However, I am facing an issue where the element does not disappear even after the boolean value changes. <li v-for="(value, index) in list"> <span> {{ value[0] }} & ...

Animating transitions when hovering (using jQuery)

As a newbie to jQuery, I am currently exploring how to create an animated transition for a headline. I stumbled upon this CodePen (http://codepen.io/ansac/pen/BHtkE) but it doesn't quite match what I have in mind. My main query is: How can I maintain ...

ParcelJs is having trouble resolving the service_worker path when building the web extension manifest v3

Currently, I am in the process of developing a cross-browser extension. One obstacle I have encountered is that Firefox does not yet support service workers, which are essential for Chrome. As a result, I conducted some tests in Chrome only to discover tha ...

tips for sending an array from an HTML page to a PHP server via AJAX

I am having issues passing an array using jQuery with AJAX and back, but my code isn't functioning correctly. I've tried making changes multiple times, but it's still not working. Can someone please advise me on what to do? I suspect that my ...

Creating a virtual roulette wheel with JavaScript

I'm currently working on creating a roulette wheel using JavaScript. While researching, I came across this example: , but I wasn't satisfied with the aesthetics. Considering that my roulette will only have a few options, I was thinking of using ...

The process of a ReactJS component's lifecycle is affected when an onClick event triggers a fetch function, causing the state

For the past week, I've been grappling with a coding challenge. My goal is to create a basic Pokedex featuring the original 151 Pokemon. The list of Pokemon should be displayed on the right side of the screen, pulled directly from a .json file copied ...

Filtering multiple rows in a table using Javascript

I'm currently working on creating a filter that can filter based on multiple inputs, with each input filtering in a separate column. Here is the JavaScript & code I am using: function myFunction(column, input) { var filter, table, tr, td, i, t ...

Angular does not seem to support drop and drag events in fullCalendar

I am looking to enhance my fullCalendar by adding a drag and drop feature for the events. This feature will allow users to easily move events within the calendar to different days and times. Below is the HTML code I currently have: <p-fullCalendar deep ...

Having trouble getting the form input max-width to work properly within a flex-box

My webpage features a header containing various icons, a title, and a search box that triggers an animation when the search button is clicked. While this setup works seamlessly on larger screens, I encounter issues on smaller screens. My goal is for the se ...

Firefox inexplicably splits words in haphazard locations

Although I know about this question, the solution provided doesn't seem to work for me Firefox word-break breaks short words at random points Despite applying the recommended CSS property as shown in the screenshot, it appears that the latest versio ...

no visible text displayed within an input-label field

Currently, I have started working on a multi-step form that is designed to be very simple and clean. However, I am facing an issue where nothing is being displayed when I click on the next arrow. I am puzzled as to why it's not even displaying the te ...

Is there a way to reset the canvas with just a click of a button?

How do I reset the canvas upon button click? I attempted: cx.fillRect() However, the above method did not work as expected. I simply want to refresh the canvas without reloading the entire page. Below is my current code snippet: var canvas = docum ...

Struggling with the navbar-toggler in Bootstrap 4 Beta 2?

As part of my Bootstrap practice, I have implemented a navbar on my webpage. However, I am facing issues with the nav-bar toggler not working for small screens and the icon navbar-toggler-icon not appearing. Below is my current navbar code: <nav class ...

In-line divs are known for their rebellious nature, refusing to conform to traditional

I'm in need of some assistance with taming my unruly HTML. It seems to be misbehaving lately. The content area on the page I'm currently designing has a two-column layout. Instead of using separate containing divs for each column, I opted for a ...

Dynamic content being added and modified using Ajax on a webpage

Trying to integrate Ajax requests into my Rails 3 app has been a challenging experience. Despite spending days following various online tutorials, the only successful outcome I've achieved so far is with Ajax delete. On my site, users have a profile ...