Is there a way for me to modify the color of the currently selected button?

I've been attempting to change the color of the active button when clicked, but my CSS class "activePage" isn't doing the trick. Ideally, clicking the "projects" button should turn it red, and clicking the "about" button should change it to red while reverting the "projects" button to its original color.

This is the JavaScript function that governs the button transitions:

function homeTransition()
    {   
        $(this).toggleClass('activePage');
        
        if(document.getElementById("aboutContent").className.indexOf("slideInLeft") !== -1){
        document.getElementById("aboutContent").className = " animated slideOutLeft";
        }
        ... // Remaining transition functions omitted for brevity
    }

//Menu
function expand(){
  $(this).toggleClass("on");
  $(".menu").toggleClass("active");
};
$(".button").on('click', expand);

Answer №1

Your click functions need to be within jQuery's scope.

I've removed irrelevant code, so please avoid copying and pasting blindly.

I've updated the HTML to remove onClick and instead bind the events inside jQuery's ready function. Additionally, I've adjusted the CSS targeting the anchor tag for the text style.

Take a look at the refactored snippet below:

//Menu

$(function() {
  function expand() {
    $(this).toggleClass("on");
    $(".menu").toggleClass("active");
  };

  $('.noselect').click(function() {
    $('.noselect').removeClass('activePage');
    $(this).toggleClass('activePage');
  });

  $(".button").on('click', expand);
});
// Revised CSS styles for the menu and content

body {
  font-family: "Source Sans Pro", sans-serif;
  color: #ccc;
  z-index: -100;
  background-color: black;
  overflow: hidden;
}

#aboutContent, #projectsContent, #contactContent {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  width: 100%;
  height: 100%;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  background-color: black;
  z-index: -1;
}

.menu {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  padding: 0;
  overflow: hidden;
  background: rgba(38, 139, 190, 0.84);
  width: 18%;
  box-sizing: border-box;
  transition: all 250ms;
  -webkit-transform: translateZ(0) translateX(-100%);
  transform: translateZ(0) translateX(-100%);
  text-align: center;
  box-shadow: 0 0 20px #000000;
}

.active {
  transform: translateZ(0) translateX(0);
  -webkit-transition: 0.4s;
  transition: 0.4s;
  color: #e5e5e5;
}

.activePage {
  color: red;
}

// Rest of the CSS styles remain unchanged
<!DOCTYPE html>

// HTML and external resources remain unchanged for context display

Answer №2

One useful feature in CSS is the 'active' property which enables you to customize the color and appearance of your elements.

For example:

button:active{
    background:olive;
}

button:focus{
    background:olive;
}

I trust this information will be beneficial to you

Answer №3

The 'this' variable in the homeTransition function and all other functions makes reference to the window object.

To resolve this issue, you can follow these steps:

Modify the onclick function call in the HTML to:

<div id="home" onclick="homeTransition(event)"

Also, ensure to include the event argument in the JavaScript file:

function homeTransition(event) {   
    $(event.target).toggleClass('activePage');

Answer №4

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>

.button {
  border: none;
  outline: none;
  padding: 10px 16px;
  background-color: #f1f1f1;
  cursor: pointer;
  font-size: 18px;
}

.active-button, .button:hover {
  background-color: #666;
  color: white;
}
</style>
</head>
<body>
<div id="myDIV">
  <button class="button">1</button>
  <button class="button active-button">2</button>
  <button class="button">3</button>
  <button class="button">4</button>
  <button class="button">5</button>
</div>

<script>
// Apply active class to the current button (highlighted)
var header = document.getElementById("myDIV");
var buttons = header.getElementsByClassName("button");
for (var i = 0; i < buttons.length; i++) {
  buttons[i].addEventListener("click", function() {
  var current = document.getElementsByClassName("active-button");
  current[0].className = current[0].className.replace(" active-button", "");
  this.className += " active-button";
  });
}
</script>

</body>
</html>

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

employing express.json() post raw-body

Within my Express application, I am aiming to validate the length of the request body and restrict it irrespective of the content type. Additionally, I wish to parse the body only if the content type is JSON. How can I go about accomplishing this? Curren ...

What type of loader is required to manage the output from these loaders?" - What specific loader should be used in this case?

I recently initialized a new react application using the create-react-app command. Upon attempting to utilize a react package by importing its default component, I encountered a compilation error: Compiled with problems: ERROR in ./node_modules/@USER-NAME ...

"Troubleshooting: Issues with jQuery Counter Functionality

Hey there, I'm new to JavaScript and jQuery! I've got this form set up with Bootstrap's disabled class: Note: the 'disabled' class in bootstrap properly disables and enables the button based on conditions. <form action="" met ...

What is an alternative method to interact with elements in Selenium besides using Driver.get?

I am currently working on a code to automate joining a google meet. The process involves signing into my google account, which is successful until I reach the "Verify that it's you" stage (image 1). When I attempt to use driver.get, it redirects me ba ...

Creating Styles in Material-UI using makeStyles: Tips for Styling by Element Name

I am currently facing a challenge of adding a rule for all <p> tags within the current component. Despite searching through various sources such as material-ui documentation and Stack Overflow, I have been unable to find any information on how to add ...

Kids in the realm of useCallback are stuck in dependency pur

My understanding of useCallback was to prevent rerendering, so I've implemented it in all my functions. However, I have a feeling that this might not be the best approach. What's even worse is that by using it everywhere, I am passing dependenci ...

How can I create a Bootstrap button with a custom href link in my code

I have created a button, is it possible to add an "href" link to this code? My link isn't working! <button class="buttoncostum"> <a href="http://example.com/"><span class="glyphicon glyphicon-th-list" style="color:white" aria-hidden=" ...

Revamp the angular design of the mat-tree UI bottom border line issue

Can you help me with changing the direction of the mat tree from right to left? I need to remove the bottom border, please refer to the image https://i.sstatic.net/ecRIO.png here ...

"React Bootstrap column showing gaps on the sides instead of filling the entire

In my current project with React and React Bootstrap 4.0, I am aiming to create a collapsible side-bar of 300px width on the left side of the screen, with the content displayed in the remaining space. The main parent component for the side-bar and content ...

Is there a way to trigger an Axios response without repeated calls or the use of a button?

As I navigate my way through using react and Axios, I encountered an issue with a get request in my code. Currently, I have a button that triggers the request when clicked, but I want to eliminate the need for this button and instead have the information d ...

What is the best method for extracting one specific data point from a database table?

Currently, I am faced with a challenge in fetching data from one database table to another. Despite successfully utilizing SQL's JOIN feature for this task, I still struggle with isolating a single result from the database and showcasing it on the res ...

What is the best way to compare my filter search input with my regular expression?

My image gallery has a search field where I can type #cat to filter through the tags of my images extracted from a JSON file using a separate variable. However, the Regex I'm using searches for tags that partially contain the word, rather than the sp ...

Combining PHP and MySQL with a join statement

I am trying to calculate the average rating for each store in a directory list using MySQL's AVG function. Whenever someone reviews a store, they assign a rating ranging from 1 to 5. This rating is then inserted into the rating column of the reviews ...

Acknowledge that a checkbox was found to be unchecked while editing a php/html form

Currently, I am in the process of developing a form using PHP/HTML that enables users to input data, review, and potentially edit their inputs before final submission. One of the key elements within this form is the use of checkboxes. Thanks to resources l ...

Incorporate a genre twist in animated films

Is there a way to implement an animated feature where the letters appear one by one in between a sentence, similar to what is seen on this page? On the linked page, there is a sentence displayed inside a banner that reads: Create meaningful documents Cr ...

Pricing determined by location on a website created with HTML

We are looking to customize our HTML5/CSS3 website by displaying different pricing tables based on the location of each visitor. Our goal is to have a fixed price for users from Singapore while showing a different price for visitors from other parts of th ...

Error Encountered: Unable to Locate 'bootstrap' label in Bootstrap 5 Popover

I have been working on implementing a popover in my Angular 12 project using Bootstrap version v5.0.1. However, I am encountering a name error that I can't seem to resolve: var exampleEl = document.getElementById(item.name + index); var tooltip = ne ...

Create an HTTP-only cookie from the resolver function in Apollo GraphQL

My objective is to pass the 'res' from my context into a resolver in order to utilize 'context.res.cookie' within my signin function and send an http only cookie. Although my sign-in function works fine, I am unable to see the cookie ad ...

retrieving the site's favicon icon

Currently, I am attempting to extract favicons from website URLs using the HtmlAgilityPack library. While I have been successful in retrieving some favicons, there are still some that remain elusive. I suspect that the inconsistency lies in the implementat ...

bourbon neat quadrilateral layout

Attempting to revamp someone else's messy, yet effective, CSS3 template into a more organized format. The transition to bourbon/neat has been smooth, but I'm facing a roadblock when it comes to creating a responsive image grid. <section class ...