Troubles with modifying website background using JavaScript

I'm looking to update my website background using JavaScript, starting with buttons before moving to a drop-down menu. I have the following code that successfully changes the background when the button is clicked:

function selectText(test){
    var arr = document.getElementById(test).value;

    if (arr == 1){
        document.body.style.backgroundImage = "url('https://images6.alphacoders.com/431/thumb-1920-431411.jpg')";
    }
    else if (arr == 2){
        document.body.style.background = 'none';
    }
}

<button id="btnim" value="1" onclick="selectText(this.id)">text</button>
<button id="btnim2" value="2" onclick="selectText(this.id)">more text</button>

However, when I change the condition in the else if statement to arr == 2 and both buttons have the same id (btnim), it doesn't work as expected. I must be overlooking something simple. Can someone please point out what I am doing wrong?

Answer №1

When using `arr==2` and keeping the id as `btnim2` for button 2, it will still function correctly. It's important to avoid having identical ids for multiple elements on a webpage as this can cause confusion for the JavaScript compiler when targeting elements.

function selectText(test){
            var arr = document.getElementById(test).value;

            if (arr == 1){
            document.body.style.backgroundImage = "url('https://images6.alphacoders.com/431/thumb-1920-431411.jpg')";
            }
            else if (arr==2){
            document.body.style.background = 'none';
          }
      }

 <button id="btnim" value="1" onclick="selectText(this.id)">text</button>
 <button id="btnim2" value="2" onclick="selectText(this.id)">more text</button>

Answer №2

One alternative approach to getting this code functioning is by passing the button's value rather than its id.

function selText(test){
  var arr = test;

  if (arr == 1){
    document.body.style.backgroundImage = "url('https://images6.alphacoders.com/431/thumb-1920-431411.jpg')";
  } else if (arr==2){
    document.body.style.background = 'none';
  }
}
<button id="btnim" value="1" onclick="selText(this.value)">text</button>
<button id="btnim2" value="2" onclick="selText(this.value)">more text</button>

Answer №3

Pass the button itself as an argument instead:

<script type="text/javascript">
    function changeBackground(button){
        var value = button.value;

        if (value == 1){
            document.body.style.backgroundImage = "url('https://images6.alphacoders.com/431/thumb-1920-431411.jpg')";
        } else if (value == 2) {
            document.body.style.background = 'none';
        }
    }
</script>

<button id="btn1" value="1" onclick="changeBackground(this)">Click to change background</button>
<button id="btn2" value="2" onclick="changeBackground(this)">Reset Background</button>

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

Exploring AngularJS tab navigation and injecting modules into the system

Two separate modules are defined in first.js and second.js respectively: first.js var app = angular.module('first',['ngGrid']); app.controller('firstTest',function($scope)) { ... }); second.js var app = angular.mo ...

Find the name of the region in the user's query

I've implemented the weather-js npm module (weather-js) to retrieve weather information for a specific region. While everything is functioning correctly, I'm looking to customize it based on user input. The module currently only accepts region ...

When iterating through it, a sorted array in Javascript mutates the window object, but not in any

I am working with Python Django to create a view that returns JSON data to a template. In this template, I initialize a global JavaScript variable like so: <script type="text/javascript"> coordinates = {{ coordinates | safe}} </script> Th ...

What is the best way to alter the color of faces in three.js?

I'm currently working with a sample script that involves flying bird objects. However, I am struggling to figure out how to change the color of the birds. I attempted to modify the color on the line where the birds are instantiated: bird = birds[i] ...

Encountered an issue during my initial AJAX call

Hello everyone, I am currently attempting to use AJAX to send a request with a button trigger and display the response HTML file in a span area. However, I am encountering some issues and need help troubleshooting. Here is my code snippet: //ajax.php < ...

Having trouble implementing object type switching in Typescript

While in the process of developing an angular application, I stumbled upon a peculiar issue. Some time ago, I crafted this piece of code which performed flawlessly: selectedGeoArea: any receiveStoreEvent(event) { switch (event.constructor) { ca ...

What is the best way to view or save the content of a PDF file using a web service?

As a newcomer to web services and JavaScript, I am facing a challenge with calling a web service that returns a PDF file in a specific format. Here is the link to view the PDF: https://i.stack.imgur.com/RlZM8.png To fetch the PDF, I am using the following ...

When trying to implement a dark/light theme, CSS variables may not function properly on the body tag

Currently, I am in the process of developing two themes (light and dark) for my React website. I have defined color variables for each theme in the main CSS file as shown below: #light{ --color-bg: #4e4f50; --color-bg-variant: #746c70; --color-primary: #e2 ...

How can I specify the specific function for AJAX to send a POST request to if there are two functions in one PHP file?

Looking for guidance on how to set up ajax to post to the function named upvoteImage() in a php file that contains both upvote and downvote functions. As a beginner in ajax, I'm facing some challenges in making it work. Javascript file $('.arro ...

Avoid triggering react-query to fetch data on page load, but instead set up a manual refetching mechanism

Currently, I'm utilizing react-query v3.13 for retrieving information from an API. Instead of fetching data immediately when calling useQuery, my goal is to fetch the API periodically starting from a specific point (such as clicking a start button). ...

Highcharts displaying black color after AJAX refresh

Struggling to implement real-time data visualization using Highcharts, I found myself tired of sifting through documentation and feeling confused. My solution involves using AJAX refresh. When the page initially reloads, my chart renders properly. However, ...

Setting up isotope using dynamic JSON data

I've done some searching, but without any luck. My current dilemma involves utilizing the isotope jQuery library to display data in a dynamic manner using a JSON dataset. I've stored the data in a .json file and am reading it in, parsing the info ...

Locate and eliminate the item containing specific content

There are many <p> &nbsp </p> tags scattered throughout the description. I need to locate and delete any tags that contain only &nbsp. The description is enclosed in a container with the class name of desc_container. Below is an exampl ...

Here's a unique version: "A guide on using jQuery to dynamically adjust the background color of table

I need some assistance with changing the background color of td elements based on the th class. Specifically, I want to target all td elements under the bots class in the HTML code provided below. <table border="1" class="CSSTableGenerator" id="myTab ...

The onSubmit function is resistant to updating the state

Currently, I am facing a challenge while working on a form using Material-UI. The TextField component is supposed to gather user input, and upon submission, my handleSubmit() function should update the state with the user-entered information. Unfortunate ...

Using jQuery, you can easily insert a <span> tag around selected text and then save this modification permanently in a local HTML file

I have compiled notes in an HTML file stored on my local computer, with the intention of keeping it solely for personal use. For instance, I have a snippet like this: <p> this is an example text</p> My goal is to highlight the word "example" ...

modify the color of text in a row within a jquery ajax table

Is it possible to change the font color of values in a row based on a condition inside a function? Specifically, if the TotalStudent count exceeds the room capacity, can we add student information to the table with red font color? Below is my attempt using ...

Tips for transmitting information from the main window to a child in JavaScript

Being relatively new to JavaScript, I am attempting to transfer a value entered into an input text field on a parent window to its child window when a button on the parent window is clicked. The parent window features an input field for entering a number a ...

"Step-by-Step Guide: Activating Tab Functionality in J

I'm facing an issue here - I've been attempting to log the event's key code and I keep getting key number (9). I believe my script isn't disabling event.keyCode properly, hence the key function remains active. What changes should I make ...

Browsing a nearby document in JavaScript

I have a text file named plaintext.txt that is stored locally, and I'm attempting to read it in JavaScript from the same folder where my script is located. In my HTML, I include the following: <script id="plaintext" src="plaintext.txt" type="text ...