Tips for making a dynamic active button using javascript

I'm trying to create a toggle button with eight buttons. When seven out of the toggle buttons are clicked, it should toggle between two classes and change its CSS styles. If the daily button is clicked, it should toggle the styles of the other seven buttons.

This is the code I have so far:

The toggleclass(this) function I have defined toggles from class1 to class2 in CSS.

I attempted the following:

<div id="menu1">

$(document).ready(function() {

$('#hey').click(function()
{
         if($('#btnDiv,#btnDiv1,#btnDiv2,#btnDiv3,#btnDiv4,#btnDiv5,#btnDiv6').hasClass('class1')){
     $('#btnDiv,#btnDiv1,#btnDiv2,#btnDiv3,#btnDiv4,#btnDiv5,#btnDiv6').toggleClass('class2')
  }else{
    $('#btnDiv,#btnDiv1,#btnDiv2,#btnDiv3,#btnDiv4,#btnDiv5,#btnDiv6').toggleClass('class2')
  }

});

});



                        <div class="cols"><button id="btnDiv" onclick="toggleclass(this);monday();" class="class1"><h5>MONDAY</h5></button></div>
                        <div class="cols"><button id="btnDiv1" onclick="toggleclass(this);tuesday();" class="class1"><h5>TUESDAY</h5></button></div>
                        <div class="cols"><button id="btnDiv2" onclick="toggleclass(this);wednesday();" class="class1"><h5>WEDNESDAY</h5></button></div>
                        <div class="cols"><button id="btnDiv3" onclick="toggleclass(this);thursday();" class="class1"><h5>THURSDAY</h5></button></div>
                        <div class="cols"><button id="btnDiv4" onclick="toggleclass(this);friday();" class="class1"><h5>FRIDAY</h5></button></div>
                        <div class="cols"><button id="btnDiv5" onclick="toggleclass(this);saturday();" class="class1"><h5>SATURDAY</h5></button></div>
                        <div class="cols"><button id="btnDiv6" onclick="toggleclass(this);sunday();" class="class1"><h5>SUNDAY</h5></button></div>
                        <div class="cols"><button id="hey" onclick="toggleclass(this);daily();showdaily();" class="class1"><h5>DAILY</h5></button></div>   

I'm having trouble getting this code to work. Can someone please help me figure out how to make the daily button change the styles of the other buttons to class 1 when clicked and back to class 2 again?

A simple solution using raw JavaScript would be greatly appreciated as I am new to JavaScript. :)

Answer №1

For those who view this as a "learning exercise," consider minimizing the excessive HTML to streamline the process. Removing unnecessary divs containing each button can enhance the efficiency of your code. Rather than cluttering the structure, focus on achieving the desired functionality.

Here is a starting point to guide you through the process. When a button is clicked, the objective is to switch all other buttons to "class1" and set the currently clicked button to "class2". Utilize the javascript classList attribute for seamless toggling between classes.

Refine the code further to include toggling options for a select all button. Whether you prefer to turn all buttons on, off, or toggle them individually, customize the functionality to suit your needs. Experiment with different possibilities to achieve the desired outcome.

By incorporating minor modifications to the existing code, you can enhance the user experience. Simplify the process by adding a class to all day buttons for easier access and manipulation. Implement listeners for efficient toggling between classes and optimize the functionality for seamless interaction.

Answer №2

Here is a simple example of how you could achieve this:

<style>
  .style1 {
    background-color: blue;
  }
  .style2 {
    background-color: yellow;
  }
</style>

<div>
<button class="style1" onclick="toggleStyles(event)">Click me</button>
<button class="style1" onclick="toggleStyles(event)">Click me</button>
</div>

<script>
function toggleStyles(e) {
    if (e.target.className.trim() === 'style1') {
     e.target.className = 'style2';
  } else {
     e.target.className = 'style1';
  }
}

</script>

Check out the live demo here: https://jsfiddle.net/abcdefg/

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

Is it advisable for a component to handle the states of its sub-components within the ngrx/store framework?

I am currently grappling with the best strategy for managing state in my application. Specifically, whether it makes sense for the parent component to handle the state for two subcomponents. For instance: <div> <subcomponent-one> *ngIf=&qu ...

Implement the same reference functionality in a React Function component that is seen in a React Class component

Is it possible to replicate the same functionality of class component ref in a function component? Here's an example: const AnotherComponent = () => { const DoSomething = () => console.log(something); return <div> There is some co ...

What is the best way to customize multiple checkboxes in React Native?

I need help with implementing checkboxes in my app using react-native-check-box. I have tried creating 4 checkboxes, but the text inside them is not aligning properly. The boxes are rendering one above the other instead of staying on the same line. I want ...

Is there a way to include an optional backslash in URLs using the .htaccess file without leading browsers to believe I am navigating to a subfolder?

As I update my php pages with the .htaccess file, I am facing an issue where the pages do not load properly when an optional backslash ("/") is included in the URLs. One possible solution is to use absolute URLs instead of relative ones so that CSS and J ...

Error Message: "BlurbError on /taskapp/taskapp-board/ Failed to parse the remaining: '(status='fresh')' from 'tasks.filter(status='fresh')'"

I encountered an error known as "TemplateSyntaxError." I have created a project that manages tasks, and within this app, I developed a task-board.html page to handle user tasks. This page consists of three sections: 1) Add New Task, 2) In-progress Tasks, a ...

The art of layering images: How to stack one image on top of another

I am in the process of trying to place a logo on top of an image, but I have been unsuccessful so far. Rather than overlapping, the second image is appearing next to the first one. Can you help me figure out how to solve this issue? This is for a website ...

What's the best way to align three images in a row?

I am having trouble centering three social media icons next to each other. I can't seem to figure out the proper way to do it. https://i.stack.imgur.com/Zf5p9.png <div class="maintext flipInX animated"> <div class="socials wow bounce an ...

Is there a way to bypass the default layout on app router in Next.js and implement our own custom page layout

Utilizing a default layout in layout.jsx, I passed all my other pages as children through props. In the page router, we typically configure the router path to specify which layout to use. However, in this new system, I am facing challenges with coding it. ...

JS Emphasis on Scrolling Div

I'm facing an issue with a button that opens a scrollable div. When I try to use the arrow keys on the keyboard, they do not scroll the div as expected. Interestingly, if I click anywhere on the div, then I am able to scroll using the arrow keys. I ...

Tips for achieving a full div image on hover

I'm having trouble with my CSS code for an image hover effect in a div. The image is appearing larger than the div and leaking out of it. How can I make sure the image stays contained within the div? Here's the updated CSS code: img { display ...

Service in AngularJS designed specifically for storing and managing SEO metadata

I stumbled upon a tutorial that introduced me to using a service for dynamic SEO metadata here: However, I encountered an issue - It seems like the service is not accessible outside of the controller's view. <div ui-view></div> Here is t ...

Retrieving outcome of Solidity contract function using web3-1.0.0-beta.27

I am using web3 1.0.0-beta.27 and the pragma solidity is set to ^0.4.2. contract Charity{ function ping() public constant returns (uint) { return 200; } } Currently, I am compiling and calling it in typescript with: import * as fs ...

MVC Controller and JavaScript Ajax Call necessitate authentication for communication

In my ASP.NET MVC application, I am utilizing AJAX calls from the Client Page using AngularJS service to perform CRUD operations through Controller Action methods. While I have implemented ASP.NET form authentication for my MVC Pages, I am now looking to ...

Having difficulty saving data in database using Ajax request from a Chrome extension

I am currently working on an extension that captures the page URL and saves it in a database once the user clicks the submit button. However, I have encountered a roadblock and believe there might be a missing piece in the extension setup that I cannot pi ...

Guidelines for retrieving a file from Amazon S3 through a web browser utilizing Python (and boto) on Google App Engine

I have a Python program running on Google App Engine using boto 1.9b that retrieves all keys from an S3 Bucket and formats the output into an HTML table. bucket_instance = conn_s3.get_bucket(bucketname) liste_keys = bucket_instance.get_all_keys() table = ...

transition from jQuery to Zepto

I have been utilizing multiple jQuery plugins in my codebase... Recently, I decided to switch over to Zepto, but encountered an issue Uncaught TypeError: Object function (a,b){return A.init(a,b)} has no method 'data' when checking the console ...

Tracking user session duration on a React Native app can be achieved by implementing a feature that monitors and

I'm currently focusing on tracking the amount of time a user spends on the app in minutes and hours, and displaying this information. I have successfully implemented the functionality to count minutes, but I am struggling to figure out how to track wh ...

Retrieving the input value from embedded cells in a specific row of a table

I need the function to calculate the result of the following expression using values from the table below: a+b*c-(e/f) This calculation should exclude rows with e and f. Although I encountered a similar issue before, there was no solution for this spe ...

Alignment Woes in Bootstrap Designs

I'm seeking assistance regarding the alignment of content on my webpage. The content is not aligning properly with the sidebar and footer, and I'm unsure how to proceed. The page should have a left margin to avoid touching the sidebar, and the fo ...

When using Mongoose paginate, there is always one missing document

I currently have a database with 6 documents and the following route: router.get('', async (req, res) => { const search = req.query.search !=null ? req.query.search : ""; const page = req.query.page !=null ? req.query.page : 1; const limit = ...