Tips for changing the size of a background image using JavaScript on the fly

I am a beginner in the world of programming and currently working on my very first mini-project - a word definition game.

One of the challenges I am facing is related to an event listener on an input field, where I aim to change the background image every time a certain score is achieved. The issue I am encountering is that whenever the background image is changed, it seems to lose its CSS style properties, specifically backgroundSize = cover;.

I attempted to resolve this by creating a function to set the backgroundSize value to cover. However, this solution only seems to work when executed in the console. I also tried using inline styles, but that did not have the desired effect either.

My efforts to implement this change through the javascript file, whether through the eventListener or an if statement, have all been unsuccessful. The loaded image always defaults to auto, but I require it to be set to "cover".

Any guidance or support on this matter would be greatly appreciated.

body {
    background: url("/IMG/moebius.jpg");
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}


let changeBackground = () => {
    document.body.style.backgroundSize = "cover";
    return document.body.style.backgroundSize;
}

defInputField.addEventListener("keyup", () => {

    setTimeout(userScore, scoreInterval);
    if (splitInputWords.length < 2) {
        correct.style.display = "none";
        incorrect.style.display = "none";
        displayScore.style.display = "none";
    };

    if (totalScore > 5) {
        document.body.style.background = "url('/IMG/moebius3.jpg')";

    };

    if (totalScore > 10) {
        document.body.style.background = "url('/IMG/moebius.jpg')";

    };

    if (userScore() >= 3 || userScore() >= splitDisplayedDef().length) {
        correct.style.display = "block";
        incorrect.style.display = "none"
        displayScore.textContent = userScore();
        displayScore.style.display = "block";


    } else {
        incorrect.style.display = "none";
        correct.style.display = "none";
        displayScore.display ="none";
    }; 

});

defInputField.addEventListener("keydown", (e) => {

    if (e.keyCode === 13 && userScore() >= 1) {
            totalScore += userScore();
            totalScore--;
            currentLevel++;
            newDefButton.textContent = "Definition"
            let newWordObject = newWordObjectGenerator();
            displayNewDef.style.display = "none";
            correct.style.display = "none";
            incorrect.style.display = "none";
            displayScore.style.display = "none";    
            defInputField.value = "";
            displayNewWord.textContent = newWordObject.word;
            displayNewDef.textContent = newWordObject.definition;
            scoreTracker.textContent = "Total Score = " + " " + totalScore;
            levelTracker.textContent = "Level = " + " " + currentLevel;
            console.log(currentLevel);
            console.log(totalScore);
}});

Answer №1

When referencing an image path, it is recommended to use backgroundImage instead of background.

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

If I type too quickly in the input field, it ends up displaying the incorrect div

I need to display two different dropdowns in my input field. To achieve this, I am using a method called shouldShowWarningBox that gets triggered every time the user updates the input and updates the value of showWarningBox accordingly. However, when I typ ...

Sending a massive video file to a node.js server and saving it in AWS S3 with ReactJS

I am currently in the process of creating an OTT platform, but I have encountered a problem while attempting to upload large files to the server. I initially attempted to store the file in a temporary folder using multer and then utilize aws-sdk s3.upload. ...

Comparing the use of input parameters to pass information in node.js versus the use

I'm grappling with the concept of when to inject a response into a function or call a function and retrieve something from it. Specifically in Node.js. Do functions in Node.js actually return data, or is it primarily about passing arguments and utili ...

Nodejs: A function is expected in the instanceof check, but an undefined value was provided

Encountering a peculiar error while using node-webkit, here's a detailed example to replicate it: index.js: var jQuery = require('jquery'); var Backbone = require('backbone'); (function($){ var ListView = Backbone.View.extend( ...

Ensuring nested JSON key existence before rendering in React

When retrieving data from MarvelAPI, there is no certainty that the key being accessed will be available. Therefore, I am implementing if statements to check each key before accessing them. The current code below appears quite messy. Is there a more effic ...

Move the grid items to their new positions with animation

I have a group of floating elements, all the same size and arranged within a grid layout. I am now adding a new element using jQuery's .after() method, which is larger in size and spans the entire width of the container, necessitating its own row. T ...

proper integration of socket.io

I have been experimenting with socket io for my project to display online friends, and I have noticed an issue that seems strange to me. Every time the page is rerendered (whether due to a user changing their profile information or sending a friend request ...

Node.js making an API request

I am encountering an issue with the following code snippet: const req = require("request"); const apiReq = req("http://example.com/car/items.json", (err, res, body) => { if (!err && res.statusCode === 200) { return JSON.parse(body); } } ...

Encountering issues with implementing useStyles in Material-UI components

Currently, I am working on a project utilizing Material-UI's library and encountering styling issues. This project marks my initial venture into ReactJS and JavaScript in general. Therefore, any assistance would be greatly appreciated! I am struggli ...

Issue with VueJS on Internet Explorer version 11 - SCRIPT1004 error: Missing semicolon

Internet Explorer 11 Error: SCRIPT1004: Expected ';' Hello there! My website is functioning properly on all browsers except for Internet Explorer. Below is the content of my babel.config.js file: module.exports = { presets: [ ['@vue ...

Hiding the original shape with ClipPath in d3 ReactJS

Currently diving into the world of D3 and ReactJS, I attempted to clip a circle with a straight line, but struggled to grasp how it functions. Below is the HTML code snippet used to draw an image: <div> <svg xmlns="http://www.w3.org/2000/svg" ...

Testing asynchronous functions with Mocha

Currently, I am in the process of developing a node wrapper to interface with an external api. One particular challenge I am facing is testing the asynchronous functionality of the createJob method. Provided below is the test case code: api_key = "test_0d ...

Developing with node and express: optimizing your workflow

After researching various blogs and tutorials on node + express development workflow, there is one crucial aspect that seems to be missing: When developing, which version of the app should you have open in your browser? The source app, featuring clean, ...

Understanding the implementation of public and private methods in mixins in Vue2

While I've come across documentation on the following implementation, I find myself struggling to visualize how it can be executed. // A more advanced alternative! var myGreatMixin = { // ... methods: { publicMethod() { // ... myPr ...

The alignment of list bullets is inconsistent across different web browsers

Check out this code snippet on JSFiddle: http://jsfiddle.net/PZgn8/8/. It's interesting to see how the rendering differs between Chrome 27 and Firefox 21. Despite the difference, I believe Firefox is actually displaying the desired outcome. <ul st ...

Can we expect to receive multiple returns?

I have a piece of code and I am looking to add 2 returns to it. What is the correct way to achieve this in PHP? function two_tables($atts, $content = null) { return '<div id="table1"><table class="table table-bordered">'.$co ...

Creating, customizing, and assigning values to data attributes in Draft-js blocks: A complete guide

My current setup involves a DraftJS editor displayed like this: <Editor editorState={this.state.editorState} handleKeyCommand={this.handleKeyCommand} onChange={this.onChange} placeholder="Write a tweet..." ref="editor" spellCheck={true} /&g ...

The progress indicator fails to activate during the first step

As a beginner in coding, I wanted to incorporate a progress bar on my website. However, I encountered an issue where when I try to make step 1 "active", it's actually step 2 that becomes active, and the same pattern continues for subsequent steps. ...

The jquery error NS_ERROR_XPC_BAD_CONVERT_JS is causing issues on Google Chrome while working fine on Firefox

Currently, I am utilizing jQuery to dynamically add fields to a form. These are considered "repeatable" fields since users can click an "add more" button. Here is the code snippet: $(".add-attacker-scores").click(function() { count = count + 1; ...

How to adjust the background picture opacity in HTML

Is it possible to adjust the transparency of a background image in HTML? I came across one solution that involved adding a box on top of the background picture and changing the opacity of the box, which in turn changed the opacity of the background pictur ...