having trouble with changing the button's background color via toggle

I've been experimenting with toggling the background color of a button, similar to how changing the margin works. For some reason, the margin toggles correctly but the button's color doesn't.

<script>
   let myBtn = document.querySelector("#menuBtn");

   function toggleMargin() {
    var Menubase = document.getElementById("list-menu-base");
    if (Menubase.style.marginTop === "0px") {
      Menubase.style.marginTop = "-250px";
    } else {
      Menubase.style.marginTop = "0px";
    }
  }

myBtn.onclick = toggleMargin;

   // The function above works, but the one below does not// 

   function changeColor() {
    var Menubase = document.getElementById("menuBtn");
    if (Menubase.style.backgroundColor === "red") {
      Menubase.style.backgroundColor = "#FF7E00";
    } else {
      Menubase.style.backgroundColor = "#FF7E00";
    }
  }

myBtn.onclick = changeColor;
</script>

Answer №1

Irrespective of the code within each function block.

Avoid having two onClick Events assigned to the same element.

Encapsulate both functions within a single container function like this:

function fullFunction() { 
   myFunction1();
   myFunction3();
}
myBtn.onclick = fullFunction;

Another point is: It's recommended to use color codes in rgb format in your JavaScript code instead of hex.

Demo:

let myBtn = document.querySelector("#menuBtn");

function myFunction1() {
  var Menubase = document.getElementById("list-menu-base");
  if (Menubase.style.marginTop === "0px") {
    Menubase.style.marginTop = "25px";
  } else {
    Menubase.style.marginTop = "0px";
  }
}

function myFunction3() {
  var myBtn = document.getElementById("menuBtn");
  if (myBtn.style.backgroundColor === "rgb(142, 253, 27)") {
    myBtn.style.backgroundColor = "rgb(255, 103, 0)";
  } else {
    myBtn.style.backgroundColor = "rgb(142, 253, 27)";
  }
}

function fullFunction() {
  myFunction1();
  myFunction3();
}
myBtn.onclick = fullFunction;
#menuBtn {
  background-color: rgb(255, 103, 0);
  padding: 10px 15px;
  text-decoration: none;
  color: white;
  margin-top: 100px;
}

#list-menu-base {
  background-color: antiquewhite;
  width: 100%;
  height: 50px;
}
<div id="list-menu-base"></div>
<a id="menuBtn" href="#">MENU BUTTON</a>

Answer №2

Your JavaScript code needs to be corrected.

function updateMenu() {
    var menuBtn = document.getElementById("menuBtn");
    // Red color does not exist, you can try using RGB values instead
    if (menuBtn.style.color == 'rgb(255, 0, 0)') {
        menuBtn.style.backgroundColor = "rgb(255,126,0)";
    } else {
        menuBtn.style.backgroundColor = "rgb(255,126,100)";
    }
}

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

Angular 2 - synchronizing timer for all users

I have developed a timer that needs to function consistently for all users at the same time. To achieve this, I stored the start_time (timestamp when the timer begins) in my database and implemented the following code snippet to calculate the remaining ti ...

How can I dynamically populate my select field with JSON data using React.js?

My goal is to fetch data from an API and use the 'symbol' JSON field as options for a select dropdown. However, I'm encountering an issue: 'TypeError: Cannot read property 'length' of undefined.' Beneath my code, I' ...

What is the best way to adjust the spacing between elements using CSS?

I am attempting to achieve this layout using CSS: The margin between each element is set to 10px. The height of the textarea is 100px and the width is 150px This snippet shows some HTML code for your reference: main form label { ...

Display Default Image in Vue.js/Nuxt.js when Image Not Found

I'm currently working on implementing a default image (placeholder image) for situations where the desired image resource is not found (404 error). I have a dictionary called article which contains a value under the key author_image. Although the stri ...

Error receiving by React while updating an array with setState() in TypeScript

I am in search of a way to adjust a property of an item within an array by using the updater returned from setState. The function is passed down as props to the child, who then invokes it with their own index to update their status. const attemptToUpdate ...

What is the best way to incorporate visual indicators into specific columns containing certain keywords?

Is there a way to customize the script code responsible for displaying table data so that icons automatically appear next to specific keywords in the Gender column? For instance, can we have an icon like glyphicon glyphicon-heart-empty for Male and glyphic ...

Navigating through elements in an array in node.js

Within my array, I store the languages that users prefer. Here is an example: let language = [] var Lang = "it" language.push(Lang) This process is repeated with various languages. The array would eventually contain these values: language ...

I am encountering the error 'user.matchPassword is not a function' while making a call to my API using bcryptjs in my Node.js and Express application. Can someone help me understand why

const checkUserAuth = asyncHandler( async (req,res)=>{ const { email , password } = req.body; const foundUser = User.findOne({email}); if(foundUser && (await foundUser.verifyPassword(password))){ generate ...

Encountering an unforeseen issue with the config.kit.methodOverride while executing Svelte

While working on a Svelte project, I recently updated it to the latest version using the migration tools provided. However, now the project doesn't seem to interact with npm as expected. When I run npm i, it installs the node modules but throws an er ...

Retrieve JSON information using AJAX

As I am new to JSON and Ajax, the question I have may seem basic. When I try to display data from my JSON object containing 'name', 'task', 'date', and 'status' using Ajax, it does not show up on my page. Below is m ...

What is the best way to filter out duplicate objects in JavaScript?

I have the following code snippet: let self = this; self.rows = []; self.data.payload.forEach(function (item, index) { if (!(self.rows.includes(item))) { self.rows.push(item); } }); The issue is that includes always returns false. Each ite ...

I am encountering an issue where I am using Getserversideprops within a page to retrieve data from Strapi, but I am consistently

Having an issue with fetching data from a Strapi backend using getServerSideProps in Next.js. The data appears to be undefined, even though the link works correctly in the browser. I am fetching inside a page, not a component, following the method descri ...

Get access to environment variables dynamically using parameters

I'm currently developing a Vue plugin to retrieve the content of environment variables, similar to PHP's env() method. Background: I require a URL in multiple components and have stored it in the .env file anticipating potential future changes. H ...

What is the process for reporting a security vulnerability in an npm package if you are the maintainer and publisher?

If I discover a security flaw in my published packages, how can I indicate which versions are vulnerable so that users running `npm audit` will be alerted? ...

unable to perform a specific binary operation

Is there an efficient method to achieve the following using binary operations? First byte : 1001 1110 Second byte : 0001 0011 Desired outcome : 1000 1100 I am looking to reset all bits in the first byte that correspond to bit values of 1 in the secon ...

Is there a way to provide "only responsive" content to the mobile m. subdomain without the need for redirection?

I currently have a website with www. that redirects to different content on the mobile m. site. I am in the process of updating my site to be responsive, but I want to ensure that I do not lose the links to the m. site in Google SERP. How can I redirect m ...

Ways to retrieve an input field value without triggering form submission

I'm currently working on a payment form where users input the amount in a text field. I also have another text field on the same form that should automatically display the amount in words based on the user input. However, I'm struggling to figure ...

iOS device encounters failure with Ajax CORS request and redirect

I am experiencing an issue where a URL is being redirected to another domain by the server. My test code is very simple: $.ajax({ type:"GET", url:"{MYURL}", success:function(d){alert('response');} }) You can che ...

Images overlapping within a dynamic container

I am currently working with a responsive container that contains one image. The container and image resize well when the window size changes. However, I now need multiple images to overlap each other (all of the same size). How can I achieve this using HTM ...

Show the total sum of a specific column in a datatable and enable the option to export the data to an Excel

When exporting a datatable as an Excel file with 4 columns, the third column contains product prices. After the export, I would like to see an additional row at the end of the table labeled "Total" that displays the sum of all values in column 3. I initia ...