"Can you provide instructions on how to set the background to the selected button

How can I change the background color of a selected button in this menu? Here is the code for the menu:

<ul id="menu">
      <li class="current_page_item"><a class="button" id="showdiv1"><span>Homepage</span></a></li>
      <li class="current_page_item1"><a class="button" id="showdiv2"><span>Experience</span></a></li>
      <li class="current_page_item2"><a class="button" id="showdiv3" ><span>Vision</span></a></li>
      <li class="current_page_item3"><a class="button" id="showdiv4" ><span>Portfolio</span></a></li>
      <li class="current_page_item4"><a class="button" id="showdiv5"><span>Social</span></li>
      <li class="current_page_item5"><a class="button" id="showdiv6"><span>About me</span></a></li>
</ul>

Answer №1

To begin, assign a specific class to all target elements (in this case, we will use class1)

    <style>
    .selected{
        background-color:green;
    }
</style>
    <ul id="menu">
          <li class="class1 current_page_item"><a class="button" id="showdiv1"><span>Homepage</span></a></li>
          <li class="class1 current_page_item1"><a class="button" id="showdiv2"><span>Experience</span></a></li>
          <li class="class1 current_page_item2"><a class="button" id="showdiv3" ><span>Vision</span></a></li>
          <li class="class1 current_page_item3"><a class="button" id="showdiv4" ><span>Portfolio</span></a></li>
          <li class="class1 current_page_item4"><a class="button" id="showdiv5"><span>Social</span></li>
          <li class="class1 current_page_item5"><a class="button" id="showdiv6"><span>About me</span></a></li>
    </ul>

Next, you can remotely access specific items by their class name

Important Note: Remember to include JavaScript code after the HTML content.

var element = document.getElementByTagName('class1'),i,j;
for(i in element){
    element[i].onclick = function() {

        this.className = this.className + ' selected';

        for(j in element){
            element[j].className = str.replace(" selected", "");
        }
    }
}

Here's a suggestion: There are many JavaScript frameworks available that can assist you with this task

If you want a faster and easier way to implement JavaScript, consider using jQuery

Here's the same functionality with jQuery:

$(document).ready(function() {
    $('#menu li').click(function() {

        $('#menu li').removeClass('.selected');

        $(this).addClass('.selected');

    });
});

Answer №2

To change the background color, you can simply use the following code:

document.body.style.backgroundColor = "red";
.
Make sure to include an onclick event as follows:

<button onclick="changeColor()">Click me</button>

In your JavaScript file:

function changeColor() { 
  document.body.style.backgroundColor = "red";
}

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

Rendering ng-include before setting the source

Is there a way to prevent the ng-include directive from trying to render before a value on scope is set? Consider the following example: <ng-include src="'./lib/templates/' + $parent.currentEditable.editTemplate"></ng-include> It s ...

What is the best way to divide multiple event handlers in jQuery?

Is there a way to organize the code below more effectively by splitting the multiple events into separate lines? $document.find('body').on( 'click dblclick mousedown mousemove mouseout mouseover mouseup mousewheel keydown keypress keyup ...

The variable that contains a function is invoked, but the result is undefined

I'm having trouble with a function that should return John temp (2021) when called, but instead it's returning John undefined (undefined) const user = { username : 'John', type: 'temp', yearJoin: 2021, user ...

Using jQuery to submit data via POST method without having the page reload

I have a link in the footer that, when clicked, jumps to the header with a # in the address bar. Is there a way to prevent this and stay in the footer? Here is the code snippet: <a href="#" class="clickIn" id="1" attrIn="Like"><span style="color ...

Is it possible for me to listen to an AngularJS event using regular JavaScript, outside of the Angular framework?

Is it possible to listen to an event triggered in AngularJS using regular JS (outside of Angular)? I have a scenario where an event is being emitted using RxJS in Angular 2. Can I observe that event from pure JS? Here's some example pseudo code: imp ...

Tips for extracting text from a selenium webelement icon that displays hovertext

Let's use Amazon as an example. Suppose we want to extract the star rating for a product. When hovering over the stars, we see a text element that says "4.0 out of 5 stars" and upon inspecting the code, we find: <span class="a-icon-alt">4.0 ou ...

If a radio button is either selected or deselected, a jQuery alert will display the value of the radio button

When a user logs into the system, there is a radio button that is almost checked. I want to create an alert when the user clicks the button to show whether it is checked or unchecked. This is the HTML code for the radio button: <input id="radio1" name= ...

Is it possible to modify parameter values while transitioning?

While transitioning, I need the ability to modify parameter values. After researching the documentation, I discovered a method called `params('to')` that allows accessing target state's parameters. This is how it looks in my code: $transiti ...

Struggling to remove a row from the MUI DataGrid within a MERN CRUD application with Redux/RTK?

Struggling to understand why the delete button isn't working on my Material UI (MUI V5) Data Grid table. As a beginner in coding, especially with MERN and Redux, my mind is overwhelmed after trying various solutions all weekend - Google, Stack Overflo ...

`Vanilla JavaScript AJAX request without using any external libraries or

Seeking advice on creating an ajax request function that is compatible across various browsers without relying on a javascript framework such as jQuery. Any ideas or suggestions are appreciated! ...

Bootstrap grid button with maximum flexibility

I am currently exploring the intricacies of the bootstrap grid system. My goal is to create a set of buttons that look like this: https://i.sstatic.net/V5meG.png Each button should expand to fill the width and height of its container. However, when a b ...

Confusion surrounding the Javascript object prototype (utilizing require.js and three.js)

I'm feeling a bit confused about my understanding of Objects, prototypes, require.js and three.js. Let me illustrate with an example: In Summary: The instance "wee" is derived from "Wee," which acts as a wrapper or monkey patch for THREE... Shouldn& ...

The error message "props.text is undefined in React Native" indicates that there is an issue with accessing the property text within

//**// import { StatusBar } from 'expo-status-bar'; import {StyleSheet, Text, View, Button, TextInput, ScrollView, FlatList} from 'react-native'; import {useState} from "react"; import GoalItem from "./components/GoalItem"; export defau ...

Implementing a Radial Cursor with a Custom Background Image in JavaScript

I am attempting to implement a radial cursor on a website that features a background image. Currently, I am facing two main issues: The radial cursor works in Chrome but not in Firefox. When using Firefox, I encounter a parsing error related to the "bac ...

HTML - No alterations to Writing Mode

Hello everyone, I'm attempting to display a header vertically in my table but the writing-mode property is not having any effect. CSS .VerticalText { writing-mode: tb-rl; } HTML <td rowspan="6" id="tableHeader" class="Border"> <h1 cl ...

Tips for adjusting HighCharts layout with highcharts-vue integrations

I have a fairly simple component: <template> <div> <chart v-if="!loading" ref="priceGraph" constructor-type="stockChart" :options="chartData" ...

Trouble with the Rotate <text> feature in Internet Explorer 11 on Windows 10

I am using d3.js to draw SVG with the transform:rotate(180deg) property. It displays perfectly on Chrome, but doesn't work on IE11. I tried changing it to rotateY(180deg), and it works with div elements but not with text elements. Here is my screen an ...

Experiencing challenges accessing information from the useEffect hook in React

I'm facing some issues with my useEffect hook and I can't seem to figure out why it's not working. I've been trying to make a call to an endpoint, but it seems like I'm not getting any response back. Any help would be greatly appr ...

Switching over to styled components from plain CSS using a ternary operator

Currently, I am in the process of converting my project from using regular CSS to styled components (https://styled-components.com/). So far, I have successfully converted all my other components except for one that I'm having trouble with. I've ...

I am having trouble locating my TypeScript package that was downloaded from the NPM registry. It seems to be showing as "module not found"

Having some challenges with packaging my TypeScript project that is available on the npm registry. As a newcomer to module packaging for others, it's possible I've made an error somewhere. The following sections in the package.json appear to be ...