Changing Background Color on Div Click

After spending a considerable amount of time on this, I find myself getting confused and stuck. It seems like I might be overlooking something crucial. Essentially, my code is designed to have the default div background (gamebg), and upon clicking one of the buttons, the background of that specific div should change.

<style>        
    #gamebg {
        background-color: #00b5d3;
        background-image: url('background_button_1.png');
        background-position: center;
        background-size: cover;
        background-repeat: no-repeat;
        width: 100%;
        max-width: 950px;
        height: 800px;
        box-sizing: border-box;
        padding: 20px;
    }

    .gamebg1 {
        background-color: #00b5d3;
        background-image: url('background_button_1.png');
        background-position: center;
        background-size: cover;
        background-repeat: no-repeat;
        width: 100%;
        max-width: 950px;
        height: 800px;
        box-sizing: border-box;
        padding: 20px;
    }

    .gamebg2 {
        background-color: #00b5d3;
        background-image: url('background_button_2.png');
        background-position: center;
        background-size: cover;
        background-repeat: no-repeat;
        width: 100%;
        max-width: 950px;
        height: 800px;
        box-sizing: border-box;
        padding: 20px;
    }

</style>

<div id="gamebg">

    <a href="#none" onclick="document.getElementById('gamebg').className ='gamebg1'"><img src="background_button_1.png" class="panel-button"></a>
    <a href="#none" onclick="document.getElementById('gamebg').className ='gamebg2'"><img src="background_button_2.png" class="panel-button"></a>

</div>

If you have any suggestions or insights, they would be greatly appreciated.

Answer №1

When it comes to IDs versus classes, IDs have a higher specificity. In this situation, the styling of #gamebg will take precedence over .gamebg1.

It's advisable to avoid putting extensive code in inline JavaScript. Instead, consider creating a function where you can utilize the attribute function to add a class and the removeAttribute function to remove an ID.

By calling the function within the onclick event with the desired class as a parameter, you simplify the process.

Below is a suggested solution:

JavaScript

function addNewClass(className) {
    var background = document.getElementById('gamebg');
    background.attribute('class', className);
    background.removeAttribute('gamebg');
}

<a href="#none" onclick="addNewClass('gamebg1');"><img src="background_button_1.png" class="panel-button"></a>
<a href="#none" onclick="addNewClass('gamebg2')"><img src="background_button_2.png" class="panel-button"></a>

For further details on specificity, refer to:

https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

Answer №2

The reason behind this behavior is known as "specificity". In the world of CSS, ids carry more weight in terms of specificity compared to classes. This means that an id's background-color property will take precedence over a class' background-property, resulting in no change to the actual background color while the classes assigned to the element with that id remain active.

For more insights on specificity, check out this informative video:

https://www.youtube.com/watch?v=ab98yhTJfWR

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

Calling Node Express request inside a GET route

I am currently utilizing nodejs as an intermediary layer between my public website and an internal server within our network. Through the use of express.js, I have created a basic REST api where the endpoint should trigger a request call to a webservice a ...

What is the best way to handle waiting for an API call in JavaScript export?

In my Vue app, I've set up my firestore app initialization code as shown below: if (firebase.apps.length) { firebase.app() } else { firebase.initializeApp(config) } export const Firestore = firebase.firestore() export const Auth = firebase.auth() ...

The functionality of useMemo is compromised when changes are made to sessionStorage

I'm facing an issue with my app where the header contains an icon that should only be shown when the user is logged in. I store the login status in sessionStorage, but the component doesn't re-render when it changes. I attempted to use useEffect ...

Create a fresh instance of an object in node.js by utilizing the require/new method

I am encountering a beginner problem with node.js where I cannot seem to create objects using the 'new' operator in the index.js file. My goal is to define a simple Person object within a Person.js file, located in the same directory as my index ...

"Enhance your website with the powerful autocompletion feature of

I am using Zend Framework to create a form element that utilizes Zend_Dojo_Form_Element_ComboBox. By setting dojox.data.QueryReadStore as the store type, I am able to generate a list of selectable values in my HTML input field. This allows me to either cho ...

Ways to shut down a pop-up

Can someone assist me with how to close the bio-info popup and implement it in the code provided below? The HTML file: <ul class="ch-grid"> <li> <div class="bioinfo"> <h2>tooltips</h2> /div> The CSS file: .bioinfo { ...

Issue with Abide Validation Events not triggering in Reveal Modal for Foundation Form

Currently, I am developing a login/registration feature for a basic web application using Foundation. On the index page, users are presented with a login screen and a register button. When the user clicks on the register button, a Reveal Modal pops up cont ...

Place a div element immediately following a table row in the HTML document

Welcome to my hotel and cabin availability page! I've created a PHP query that displays the available hotels and cabins in a table format. However, I want to enhance the user experience by displaying a Google Maps location and some pictures of each ho ...

What is the process for a server to transmit a JWT token to the browser?

Here is an example response sent to the browser: HTTP / 1.1 200 OK Content - Type: application / json Cache - Control : no - store Pragma : no - cache { "access_token":"MTQ0NjJkZmQ5OTM2NDE1Z ...

Having trouble with the JSFiddle dropdown button that is unresponsive to

I am currently in the process of developing a test drop-down menu. The open menu button functions correctly, however, the close button is unresponsive to clicking or hovering actions. Upon clicking the open menu button, it should make the other button visi ...

Extract all objects from an array where a specific field contains an array

data:[ { id:1, tags:['TagA','TagB','TagC'] }, { id:2, tags:['TagB','TagD'] }, { id:3, tags:[&a ...

Retrieving the ID from the element that was clicked

Here is a code snippet that allows for the changing of color and text when an href link is clicked. /* Function to change the color of the button upon click */ function changeColor(element) { alert(element.target.id); if (element.innerHTML == "Selec ...

Is there a way to transform an Array or Object into a new Object mapping?

When using the map method in JavaScript, it typically returns an Array. However, there are instances where I would like to create an Object instead. Is there a built-in way or a simple and efficient implementation to achieve this? Solutions using jQuery ar ...

centering the text within the div for perfect alignment

I've been attempting to customize a Register form. My goal is to position the heading in the center of the div while having another login form located right beside it. Using flexbox, I styled them and then applied justify-content as center. Additiona ...

The element type is not valid: it should be a string for built-in components or a class/function for composite components, but it is currently an object in a React project

In the process of developing a React app to explore MUI capabilities, I encountered an error in my browser: The issue reported is: Element type is invalid - expected a string (for built-in components) or a class/function (for composite components), but rec ...

Using Typescript to Import One Namespace into Another Namespace

Is it possible to export a namespace from one typescript .d.ts file and then import that namespace into another .d.ts file where it is utilized inside of a namespace? For instance: namespace_export.d.ts export namespace Foo { interface foo { ...

The bootstrap modal form does not allow for user input of information

For the past few days, I've been encountering a strange bug with Bootstrap Modals that I can't seem to find a solution for online. Any help on this matter would be greatly appreciated. The section of my site that is currently giving me trouble i ...

The Vue.createApp function seems to be malfunctioning, whereas using the new Vue() method is functioning correctly

When running my code, I encountered the following error message: tesyya.js:16 Uncaught TypeError: Vue.createApp is not a function. My code snippet looks like this: const app = Vue.createApp({ data() { return { count: 4 } } }) const vm ...

tips for sending a chosen item to the Vujes API

How can I send the selected item from a dropdown to an API in Vue.js? <select :v-model="selectedRole" class="custSelect"> <option v-for="option in options" v-bind:value="option.value"> {{option.role}} </option> ...

The ajax POST method fails to trigger in a Node.js environment

Having an issue with the POST request. It's necessary for updating info without page reload. Below is my pug code: .tinder--buttons form(id="form1") button#love(type="submit") i.fa.fa ...