Fixing the Else part of the If Else statement for my JavaScript Toggle button issue in ASP.net-JavaScript application

I am fairly new to JavaScript and looking for some help. I have a button that I want to toggle its background color using if/else logic in JavaScript. My development environment includes ASP.net, C#, JavaScript, and VS2013 Express.

The first part of my code successfully changes the button's color to #198B07. However, when clicking again, it does not seem to trigger the "else" condition to change the color to "#2A303C". The initial state of the button is the standard gray color. Is this color getting reset on the second click, causing the initial "if" statement to be true again? It seems like once the color changes to #198B07, it remains that way for all subsequent clicks.

Can anyone identify what might be going wrong with my code?

Here is the code snippet:

JavaScript

<script>
    function myFunction2() {
        if (document.getElementById("test").style.background != '#198B07') {                
            document.getElementById("test").style.background = '#198B07';
        } else {
            document.getElementById("test").style.background = '#2A303C';
        }
        return false;
    }
</script>

HTML

 <button type="button" id="test" onclick="myFunction2()">Try it</button>

Answer №1

style.background does not represent a hex color; instead, it returns RGB values. To properly compare these values, you should adjust the if statement to compare the RGB values like this:

if (document.getElementById("test").style.background != 'rgb(25, 139, 7)')

By making this change, the background will be updated as needed. Check out this jsfiddle example for reference.

Answer №2

Consider utilizing jQuery for this solution:

    function changeBackgroundColor() {
        if ($('#example').css('background-color') != '#198B07') {                
            $('#example').css('background-color', '#198B07');
        }
        else {
            $('#example').css('background-color', '#2A303C');
        }
        return false;
    }

Answer №3

One issue arises with HTMLElement.style.background as it returns the color in RGB format when accessing it. For instance, if you were to set the hexadecimal color '#198B07' for the element style property using 'document.getElementById("test").style.background', the returned value would be 'rgb(25, 139, 7)'.

Instead of directly styling the element with JavaScript, consider adding or removing a class and then applying the styles via CSS. This approach is not only better but also more maintainable in the long run.

Answer №4

Give this a shot:


   function changeBackground() {
        if (document.getElementById("box").style.background !== '#198B07') {                
            document.getElementById("box").style.background = '#198B07';
        }
        else {
            document.getElementById("box").style.background = '#2A303C';
        }
        return false;
    }

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

The useEffect hook is failing to trigger within the Higher Order Component (Hoc

My component was working fine without using a HOC, but now that I've wrapped it inside withSpinner HOC, the fetching process does not start. const CollectionPage = (props) => { const { isCollectionLoaded, isCollectionFetching } = props; useEf ...

Show various options in a dropdown menu depending on the numerical input in a text box

I am currently facing a challenge. I hope you can understand my issue. I have a drop-down list field named "Address type" with options such as Home, Office, Other, and Hostel. Additionally, I have a text field named ID which is of integer type. My goal is ...

How can I show the initial three digits and last three digits when using ngFor loop in Angular?

Greetings! I have a list of numbers as shown below: array = [1,2,3,4,5,6,7,8,9,10] By using *ngFor, I am displaying the numbers like this: <div *ngFor =" let data of array"> <p>{{data}}</p> </div> Now, instead of d ...

Ensuring that one then() statement waits for the other to finish before executing

My React application is connected to Firestore DB, and I'm fetching data in the componentDidMount() lifecycle method. I handle two then() calls - one for retrieving data from the DB and saving it, and the other for updating the component's state. ...

"Locate the position of the input value in the JSON object index

How can I retrieve the index of a JSON object using an input value? When the user inputs '2', my JavaScript should display: 3rd question from JSON with id:2 and index 2, then when they click next, they will get the 4th question with id:9 and ind ...

Can a background image flow into another div?

My goal is to use this specific image as the background image for this particular page. I want the background image to begin within the navbar navbar-default class. However, I'm facing an issue. I need the image to extend into the next div, which is d ...

Troubleshooting Firefox's inability to properly utilize jQuery's scrollTop() function on the 'body' element

I'm puzzled as to why the scrollTop() jquery function isn't functioning properly on the 'body' element in Firefox. $('body').scrollTop(0); To resolve this issue, I ended up using: $(window).scrollTop(0); The jquery documen ...

Can the widthSegments parameter in SphereGeometry be dynamically adjusted?

Within my Three.JS project, I am utilizing a Sphere Geometry that is defined as follows: var radius = 1 ; var widthSegments = 12; var heightSegments = 12; var geometry = new THREE.SphereGeometry(radius, widthSegments, heig ...

Why is it not possible to declare an interface or type within a TypeScript class?

I am struggling to define interface | type within a TypeScript class. Here is the code snippet: class MyClass { interface IClass { name: string, id: string } } However, I keep encountering this error: Unexpected token. A constructo ...

Using a single quote in JsonConvert.SerializeObject causes the method to fail

Consider this object: public class Comment { public string Id { get; set; } public string Author { get; set; } public string Body { get; set; } } Whenever there is a single quote in the body (the other variables will not contain single quotes ...

How can I handle and interpret SQLExceptions within an ASP.NET (MVC) framework?

Although validation can catch many SQL errors, there are certain situations where errors cannot be avoided. Two examples include ensuring column uniqueness and dealing with incorrect foreign keys: In these cases, validation may not be effective due to the ...

Serializing Form Data with Checkbox Array

I am currently utilizing JQuery to submit a form using the form.serialize method. However, within the same form, there is an array of checkboxes that are dynamically created by a PHP function. Here is the structure of the form: <form class="form" id="f ...

Tips for implementing self-managed state in Vue.js data object

My approach in organizing my Vue application involves using classes to encapsulate data, manage their own state (edited, deleted, etc), and synchronize with the back-end system. However, this method seems to conflict with Vue in some respects. To illustra ...

What are the steps to manipulate third party API data with the Node.js 'Request' module, prior to transmitting it to the frontend?

Being a newcomer to NodeJs, I took to Google for assistance but came up empty. My challenge lies in editing the json data retrieved from an API link and sending it to frontend AngularJS as is. app.get('/getCustomers', bodyParser.urlencoded({exte ...

An unusual html element

During a recent exploration of a website's code using the inspect tool, I stumbled upon a tag that was completely unfamiliar to me. <gblockquote></gblockquote> I've come across a blockquote before, but never a gblockquote. Interest ...

Using `reduce` in TypeScript, you can organize an array of objects based on a shared property

Here is an example of an array: [ { id: '1', task: 'Grocery shopping', isImportant: true }, { id: '2', task: 'Meeting', isImportant: false }, { id: '3', task: &apos ...

Out-of-sync movement in animated characters

Looking for some assistance with my page coding. I have a scenario where two stars are moving around a button, simulating an animation by incrementing the CSS properties top and left. Initially, everything appears fine and they move synchronously. However, ...

Have the quotes within my markup been replaced with HTML entities?

Currently, I am working on a content page that uses a master page which includes a text box and a button. My goal is to have the button execute some JavaScript code before performing any other actions. At the moment, I am in the testing phase of this JavaS ...

Getting a jquery lightbox up and running

After experimenting with three different jquery plugins in an attempt to create a lightbox that appears when clicking on a link containing an image, I am currently testing out this one: . Despite adding the plugin source in the head and ensuring that the l ...

Verify whether a dependency is being passed into an Angular component

As mentioned in a discussion about IE caching issues, Internet Explorer tends to cache things when using ajax with AngularJS, causing potential problems. You can find a helpful solution to this problem here. Given that we have multiple angular apps on our ...