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

What is the process for converting an Angular UTC timestamp to a local timestamp?

Is it possible to convert a UTC timestamp to a local time timestamp using any function or method? I am sending the timestamp to angular moments, but the server's timestamp is in UTC. ...

Optimize the height of embedded Linkedin posts for a seamless viewing experience without the need for scrolling

I have noticed that in LinkedIn embedded posts on my page, each post has a different height and there are scrolls. Is there a way I can make the height dynamic according to the post height? <iframe src="https://www.linkedin.com/embed/feed/update/ur ...

Challenge with JavaScript personalized library

No matter how many times I review my code, I find myself perplexed. Despite my efforts to create a custom library of functions from scratch (shoutout to stackoverflow for guiding me on that), the results are leaving me puzzled. A javascript file is suppose ...

Setting a variable for a JavaScript function to insert a video - a step-by-step guide

Here is a grid structure that I am working with: <div class="main"> <ul id="og-grid" class="og-grid"> <li> <a href="http://..." data-video="my-url" data-largesrc="images/1.jpg" data-title="Title" data-descript ...

Does writing JavaScript code that is easier to understand make it run slower?

While browsing the web, I stumbled upon this neat JavaScript program (found on Khan Academy) created by another user: /*vars*/ frameRate(0); var Sz=100; var particles=1000; scale(400/Sz); var points=[[floor(Sz/2),floor(Sz/2),false]]; for(var i=0;i<part ...

Switch div and expand/shrink the rest

Apologies for what might seem like a trivial question, but after working for a few hours now, I'm finding it difficult to wrap my head around this. My initial instinct is to handle this by manipulating the entire div structure with JavaScript, but I c ...

Extracting data from websites: How to gather information from dynamic HTML elements

On the website I am exploring, there is a dynamic graph with descriptions below it that keep changing. My goal is to extract all these trajectory descriptions. The HTML code snippet related to the description area looks like this: <div class="trajDesc ...

My goal is to utilize CSS grid to craft a unique layout by establishing a grid area. However, the layout is not functioning as anticipated

Currently, I am in the process of mastering CSS grid layout design. If you are curious to see my progress so far, check out this Codepen link showcasing my code. Additionally, for a visual representation of the layout, feel free to view the layout image ...

Issue with converting form data to JSON format

Having an issue converting a filled form in HTML to a JSON request for sending to the server via HTTP POST. Despite having a filled form, the JSON request only shows an empty array. Here is the JavaScript snippet: $("#submitSurveyBtn").on("click", functi ...

JavaScript: Employ array destructuring for improved code readability (eslintprefer-destructuring)

How can I resolve the ESLint error that says "Use array destructuring. eslint(prefer-destructuring)"? The error occurs on this line of my code: let foo = 1; foo = obj.data[i][1]; //ESLint error on this line If anyone could provide assistance in fixing thi ...

What is the method to obtain the content height of individual pages in Android, with or without the use of JavaScript?

I am facing an issue while trying to retrieve the content height of each webpage consecutively. When I load pages separately, I can successfully get the height of each page. However, when I attempt to fetch the content height continuously for webpages in a ...

Dynamic Namespaces in Socket.io is a feature that allows for

I am currently working on implementing multiple namespaces in my app. As I receive route parameters, I dynamically create new namespaces. For example: var nsp = io.of('/'); var className; app.post('/class/:classID',function(req,res){ ...

How to set up a Carousel as the background within a div using Bootstrap 5

I'm attempting to create a visually appealing layout by showcasing a Carousel component behind some text. The idea is to have scrolling and fading images with a prominent header overlaid on top of them. I want the carousel images to be contained withi ...

What is the best way to effectively carry out a partial update using ReactJS?

During a recent job interview, the recruiter discussed the importance of handling partial updates and managing application size. As an example, he presented a Single Page Application (SPA) with a size of 8MB, which he deemed less than ideal. He emphasize ...

The backend function of an aspx page is failing to execute when triggered by a $.ajax request

Currently, I am facing an issue with a web form IndexPage.aspx. The script in this front-end code makes an ajax call to a code-behind function. Take a look at the code snippet below: $.ajax({ type: "POST", url: &apos ...

Modify the hash URL in the browser address bar while implementing smooth scrolling and include the active class

I have implemented a smooth scroll technique found here: https://css-tricks.com/snippets/jquery/smooth-scrolling/#comment-197181 $(function() { $('a[href*=#]:not([href=#])').click(function() { if (location.pathname.replac ...

Combining JSON parameter and multipart/form-data file in a single request using Vue.js

Is there a way to send both JSON parameters and multipart/form-data files in a single request using Vue, similar to how Postman does it? I've been looking into how to submit "multipart/form-data" from VueJs. What I need is to include an image file in ...

I. Discovering the Step-by-Step Guide on Retrieving User Information from Facebook Upon Generating App

I have set up a Facebook login for user registration on my website. However, I am only able to retrieve the profile name and user ID from Facebook. How can I access the email and other user information? Here is the data I am currently receiving from Faceb ...

The combination of Ajax, JavaScript, PHP/HTML, and dynamic variables

Hey there, I'm currently working on a game development project and have encountered what seems to be a scope issue. The issue arises in my js file when a player clicks on the card they want to play: It starts in my js file:</p> <pre>&l ...

Is it preferred to utilize v-show in combination with v-for?

I understand that using "v-if" with "v-for" is discouraged, but I'm unsure about the case of "v-show" since it simply toggles the display attribute. Here is the code for reference. Essentially, I am trying to switch between 3 different types of fi ...