CSS hover effect ceases to function after the button has been clicked once

I am facing a dilemma with styling that I can't seem to resolve. There is a basic toggle feature on my page with two options -- the user can select either Toggle1 or Toggle2, resulting in different data being displayed dynamically based on the active toggle:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>replit</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <div id="toggle1">Toggle 1</div>
  <div id="toggle2">Toggle 2</div>
</body>

</html>

When a toggle is active, it should have a blue background. When a toggle is inactive, it should have a white background but turn orange when hovered over. Initially, upon page load, toggle1 is selected.

Everything works perfectly upon the initial page load -- toggle1 is selected and displayed in blue, while toggle2 is white with an orange hover effect. However, after toggling between the options, the orange hover effect seems to stop working. The reason for this issue eludes me. Could it be due to the elements being marked as "active" post-click? I cannot pinpoint the exact cause.

I have attempted implementing the hover effect using both CSS and jQuery:

CSS:

#toggle1:hover, #toggle2:hover {
  background: lightblue;
}

jQuery:

$(toggle1).hover(
    function () {
      $(this).addClass("blue");
    },
    function () {
      $(this).removeClass("blue");
    }
  );

  $(toggle2).hover(
    function () {
      $(this).addClass("blue");
    },
    function () {
      $(this).removeClass("blue");
    }
  );

While both methods successfully apply the hover effect on page load, they fail to do so consistently after a toggle has been clicked. Hover functionality ceases to work altogether.

In terms of the onClick function, it is handled in JavaScript:

JS:

const showToggle1 = () => {
    // ...code to show toggle 1 content 

    // switch background colors from blue to white
    $(toggle2).css({ background: "#FFFFFF", color: "#000000" });
    $(toggle1).css({ background: "#0074d9", color: "#FFFFFF" });
}

const showToggle2 = () => {
    // code to show toggle 2 content

    // switch background colors from blue to white
    $(toggle1).css({ background: "#FFFFFF", color: "#000000" });
    $(toggle2).css({ background: "#0074d9", color: "#FFFFFF" });
}

I can only assume that there might be some interference between the onClick functions and the hover effect, causing it to malfunction after toggles have been switched. Yet, identifying the root cause remains elusive.

Answer №1

While I couldn't pinpoint the exact reason for the output you're experiencing, I have a different approach to suggest. Try implementing the following HTML, CSS, and JS:

toggle_btn1 = document.querySelector("#toggle_btn1");
toggle_btn2 = document.querySelector("#toggle_btn2");
const displayToggle1 = () => {
    //Display Toggle1 Content
    toggle_btn1.classList.add('active');
    toggle_btn2.classList.remove('active');
}
const displayToggle2 = () => {
    //Display Toggle2 Content
    toggle_btn2.classList.add('active');
    toggle_btn1.classList.remove('active');
}
.btn-toggle{
    background: white;
    color: black;
}
.btn-toggle:hover{
    color: orange;
}
.btn-toggle.active{
    background: blue;
    color: white;
}
.btn-toggle.active:hover{
    color: white;
}
<div id="toggle_btn1" class="btn-toggle active" onclick="displayToggle1()">Toggle Button 1</div>
<div id="toggle_btn2" class="btn-toggle" onclick="displayToggle2()">Toggle Button 2</div>

Give it a try, this should solve your issue.

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

Loading 3D models in Three.js from the cache

Every time my page reloads, the loader loads objects from the URL instead of cache. Is there a way to check if the resource is in cache and load it directly? Appreciate your help! ...

Redirecting to the homepage with ScrollTop feature

With the development of my Single page HTML5 web application, I have encountered a scrolling issue. To scroll to the top of the page, I am implementing the following code: $('html, body').animate({ scrollTop: 0 }, 800); This functionality works ...

The functionality of Angular Datepicker is disrupted when scrolling through the page

Coding in HTML <div class="col-5 col-md-3 px-0 daterange-picker"> <div class="form-group"> <div class="input-group"> <input type="text" id="second ...

Override the default HTML style overflow to hidden with Material UI Swipable Drawer

Currently, I'm utilizing the Material UI SwipableDrawer component which has an unexpected drawback of causing the scrollbar to disappear when the drawer is displayed. This issue overrides my specified style of "overflow-y: scroll" on the Html tag and ...

Struggling to align your website content properly?

Currently, I am attempting to center all of the products on my Wordpress page so that everything is aligned centrally. I attempted wrapping it all in a div with specific CSS properties, but unfortunately, the content moved to the middle while the products ...

Error in Typescript: Function expects two different types as parameters, but one of the types does not have the specified property

There's a function in my code that accepts two types as parameters. handleDragging(e: CustomEvent<SelectionHandleDragEventType | GridHandleDragEventType>) { e.stopPropagation(); const newValue = this.computeValuesFromPosition(e.detail.x ...

What is the best way to assign three different dates in my protractor test?

I am facing an issue with setting random dates in 3 date fields in a row using Protractor. The problem is that Protractor sets the dates too quickly and sometimes assigns invalid dates like: first data: 01/08/1990 (correct) second data: 01/09/0009 (inva ...

Fetching image for jmapping AJAX request

Struggling to incorporate a loading image when making an ajax call using the jquery jmapping plugin to update categories on a map. While I typically work with PHP, I've put together this script below and it's all I could come up with. Any assista ...

Dispatching current to the default case of the switch statement

Hello everyone, I wanted to share a snippet from my JS file: function passDataToPHP() { endpoint = 'myfile.php'; parameters = ''; parameters += 'action=passData'; parameters += '&myfield='+someV ...

Integrate your React Native application with a Node.js backend on your local machine

My attempt to establish a connection between my react native app and my node.js app on a Windows system has hit a roadblock. While I am able to receive responses from the node API using Postman, the response from the react native app is coming back as unde ...

I'm seeking guidance on handling complex relationships with Mongoose. Please provide a specific challenge example for a quick solution. Thank you

While I am skilled in using sequelize with node, angular, express etc., I am just beginning to delve into the M part of the MEAN stack by learning mongoose. However, I'm unsure of MongoDB's capabilities when it comes to organizing data in the dat ...

CSS button with folded corner illusion and dynamic transitions

I have been using the code provided below to create a folded corner effect on a button, but I am having trouble with the white background that appears in the upper left corner of the button. Is there a class I can use to make this transparent so that the y ...

What is the best way to change a JSON string into an array of mysterious objects?

I am currently working on a flashcard generator project and I am dealing with a JSON String that is quite complex. The JSON String contains multiple arrays and objects structured like this: data = [{"front":"What is your name?","back":"Billy"},{"front":"H ...

We are experiencing an issue with WebSQL: The number of placeholders in the statement does not match the number of arguments provided

I'm looking to develop a customized function for dynamically inserting data into the webSQL Database. Unfortunately, indexed DB is not an option due to Zetakey's lack of support for it. tx.executeSql("INSERT INTO " + table + "(" + formatfields ...

Guidance on incorporating a function as a prop in React using TypeScript

I'm currently learning TypeScript with React and ran into an issue. I attempted to pass a function as a property from my App component to a child component named DataForm. However, I encountered the following error: Type '(f: any) => any&ap ...

Is it possible to customize the borders of boxes in Google Charts Treemap?

Although this may seem like a minor issue, I can't find any information in the documentation. I'm currently using Google Charts treemap for monitoring a specific project. The problem I'm facing is that when all the parent level rectangles ar ...

What is the method for using jQuery to retrieve hidden fields with the visible attribute set to "false"?

How can I access a control with "visible = false" attribute using jQuery? Some code examples would be appreciated. <tr>   <td class="TDCaption" style="text-align: left">     <asp:Label ID="lblMsg" runat="server" EnableViewState="False" F ...

Collapse the Bootstrap Menu upon selecting a Link

I am working on a side menu with an offcanvas display feature. The current functionality is such that when the button is clicked, the canvas pushes left and opens the menu. However, I want the menu to collapse and close automatically when a link is selecte ...

Identifying click events using jQuery specifically

After a jQuery event is triggered on a form by a click event only, I want to add some code. The event may also be called in other situations. To detect when the event is triggered, this code can be used: $( ".grouped_form" ).on("wc_variation_form", funct ...

Issue with modal rendering in Bootstrap4 when the body is zoomed in

I am encountering an issue with a Bootstrap html page where the body is zoomed in at 90%. The Bootstrap modal is displaying extra spaces on the right and bottom. To showcase this problem, I have created a simple html page with the modal and body set to 90% ...