The button's background color will vanish if you click anywhere outside the button or on the body of

Struggling with a tabpane created using HTML, CSS, and JavaScript. The problem arises when the background color of the active tab's button disappears upon clicking outside the button or on the body. While switching between tabs, I can change the colors of the buttons using the onfocus() and onblur() functions, but the issue persists. Is there a solution to this problem?

// console.log('hii');

function fun1(a){
    // console.log(a);
 var x = document.getElementById(a)  
 var data = document.getElementsByClassName('inner_section')
 console.log(data);
 for(var i=0;i < data.length;i++){
    data[i].style.display="none"
}
    x.className +=" slide-in-bottom"
    x.style.display = "block";

}

function fun2(b){
  b.style.backgroundColor="#ff6136"
  var d = document.getElementById('button_1')
  d.classList.remove('active_button')
}

function fun3(c){
    c.style.backgroundColor="white"
}

Answer №1

"Focus" within the browser serves as a tool primarily utilized for input boxes, allowing websites to track where text is being typed or aiding those with visual impairments in using tab navigation. This feature should not be misused to trigger events that alter the site's state, as doing so can result in unexpected behavior. It is advised against employing this method for a menu selector setup.

Instead of relying on focus to determine the selected menu item, consider utilizing existing functions to apply a "selected" class to the chosen button while removing it from all other buttons. To access all buttons, assign them a shared class in the HTML markup and retrieve the list using JavaScript:

document.getElementsByClassName("menu-buttons");

This will return an array of elements. Remove the "selected" class from an element like this:

el.classList.remove("selected");

Then, add the selected class to the clicked element:

el.classList.add("selected");

It is recommended to avoid using the onclick HTML attribute and instead utilize JavaScript to set event listeners, granting access to the Event object which simplifies identifying the clicked button. Here's an example implementation:

function selectMenuHandler(event) {
  for (var el of document.selectElementsByClassName("menu-selected")) {
    el.classList.remove("menu-selected")
  }
  event.target.classList.add("menu-selected")
}

for (var el of document.selectElementsByClassName("menu-button")) {
  el.addEventListener("click", selectMenuHandler);
}

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

Displaying JSON data in an HTML table cell format

Hey everyone, I need some help with the following task: I am working on displaying a list of log lines in an HTML table. Some of these lines will contain JSON strings, and I want to format the JSON data within the table when the HTML file is loaded from ...

Let's compare the usage of JavaScript's toUTCString() method with the concept of UTC date

When I fetch the expiry date time in UTC from the Authentication API along with a token, I use the npm jwt-decode package to extract the information. private setToken(value: string) { this._token = value; var decoded = jwt_decode(value); this._ ...

Navigate to the middle of the visible area

Is there a way to automatically center a div when it is clicked, so that it scrolls to the middle of the browser viewport? I have seen examples using anchor points but I want to find a different solution. Any ideas on how to accomplish this without using ...

Expand the grid with extra rows once it has been generated, especially when dealing with a large volume of database records, utilizing JQGrid or JSGrid

Having a large dataset (json) that takes too long to display in the grid for users, I'm looking for a solution. My idea is to initially run a filtered query (e.g. records from the current year) to quickly build the grid. Once the grid is presented to ...

What is the formula to determine if x is greater than y and also less than z?

I need help determining if a number falls within the range of greater than 0 but less than 8 using JavaScript. Can anyone assist me with this? Here is my attempt at it: if (score > 0 && score < 8) { alert(score); } ...

Responsive design with Flexbox, interactive graphics using canvas, and dynamic content resizing

I'm having difficulties with my canvas-based application. I have multiple canvases, each wrapped in a div container alongside other content. These containers are then wrapped in an "hbox" container. The objective is to create a dynamic grid of canvas ...

Using SVG files as properties in React from a data.js file

I have a website where I store my content in a data.js file and pass it to my components using props. Everything is working correctly, except for my .svg files. When I try to display them, they do not appear. However, if I change the extension of the image ...

Utilizing AngularJS: Executing directives manually

As a newcomer to AngularJS, I am facing a challenge that requires creating a 3-step workflow: The initial step involves calling a web service that provides a list of strings like ["apple", "banana", "orange"]. Upon receiving this response, I must encap ...

Forwarding to another page following an AJAX post request to a Django view

I've been struggling to get this basic piece of code to work properly, despite trying numerous resources. I can't seem to pinpoint where I'm going wrong. Essentially, I have a javascript function submitData() that is supposed to make an ajax ...

Learning the ins and outs of HTML5 and CSS3

Does anyone have recommendations for high-quality HTML5 and CSS3 tutorials? ...

I am puzzled as to why my jQuery height and width functions are returning NaN as the result

I am attempting to calculate the ratio of height and width for each image on a webpage. Unfortunately, I am consistently receiving a NaN result and I cannot figure out why. I have been using get() and find() <div class='image-wrapper'> ...

Creating a Cancel Button in JSP/HTML/JS/CSS Form: A Step-by-Step Guide

It is necessary to incorporate the functionality of "save" and "cancel" in the JSP code for this particular form. By selecting "save", the data entered into the form will be submitted to its intended destination. Alternatively, choosing "cancel" will dismi ...

Vue.js: Select a different div within the Vue object instead of the one that is bound

I am currently utilizing Vue and Leaflet to showcase polygons (zones) on a map and exhibit relevant information (messages) upon clicking on specific polygons. The div responsible for rendering these messages has the unique id "#messagearea" and is connec ...

Experiencing an unexpected wait before the requestAnimationFrame?

Surprisingly, Internet Explorer is actually performing the way I want it to in this case :-) I developed a function for SVG animations using requestAnimationFrame (for simplicity, I left out the value calculations here ... but my initial test involved an ...

Is there a way to remove deleted SASS styles from the generated CSS?

Is it possible to remove markups from a generated css file using sass? For instance, in my scss file I have: body{ background:$dark; } The resulting CSS file looks like this: body{ background: #000; } If I delete that line of code in sass, what will h ...

When using getStaticPaths, an error is thrown stating "TypeError: segment.replace is not a function."

I am a beginner when it comes to using Next.js's getStaticPaths and I recently encountered an error that has left me feeling lost. Below is the code I have written (using query from serverless-mysql): export async function getStaticPaths() { cons ...

The isAuthenticated status of the consumer remains unchanged even after being modified by a function within the AuthContext

I am working on updating the signout button in my navigation bar based on the user's authentication status. I am utilizing React Context to manage the isAuthenticated value. The AuthProvider component is wrapped in both layout.tsx and page.tsx (root f ...

Using jQuery to retrieve the content of a textarea and display it

I need help finding the right way to read and write to a Linux text file using JavaScript, jQuery, and PHP. Specifically, I want to retrieve the value from a textarea (#taFile) with jQuery ($("#taFile").val();) and send it via $.post to a PHP script that w ...

Jquery function for determining height across multiple browsers

I am currently facing an issue with setting the height of table cells in my project. While everything works smoothly on most browsers, Firefox seems to add borders to the overall height which is causing inconsistency across different browsers. If anyone k ...

Problem with z-index in VueJS: Child div z-index not functioning within v-dialog

I am facing an issue where I have brought a span to display a loading image inside the v-Dialog of a vuejs screen. The problem is that the v-dialog has a z-index of 220 set as inline style, causing my new span (loading image) to appear below the v-dialog. ...