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

Clicking outside of a Bootstrap 3 dropdown causes it to close

Let's analyze the code below: $(document).ready(function () { $('#dropdownMenu1').attr('aria-expanded', true); $('.dropdown').addClass('open'); $('#dropdownMenu1').on('hide.bs.dropdow ...

Error: The function cannot be performed on _nextProps.children

I'm having trouble implementing react context with nextJS and I keep encountering this error: Server Error TypeError: _nextProps.children is not a function This is my code for _App.js: import Head from "next/head"; import Router from &q ...

Creating TypeScript domain objects from JSON data received from a server within an Angular app

I am facing a common challenge in Angular / Typescript / JavaScript. I have created a simple class with fields and methods: class Rectangle { width: number; height: number; area(): number { return this.width * this.height; } } Next, I have a ...

What is the best way for Cucumber to move on to the next annotation only after ensuring all async requests from the previous one have finished processing?

I am looking to set up a basic test using Selenium and Cucumber for logging into my web application and confirming that the main page is displayed correctly. Currently, all three tests are returning true even before the page is fully loaded. The issue ar ...

Compiling Vue.js without the need for a build tool

Vue.js is the framework I've chosen for my PHP + JS application, and I'm using the full build of Vue by directly including it via a script tag without any build tool. I'm now wondering how I can pre-compile my templates without relying on b ...

Invalid PDF File - Unable to Complete Download via $http

I'm facing an issue while attempting to download a PDF file using the $http service in AngularJS. Upon trying to open the downloaded file, I encounter an error message stating "Invalid Color Space" and the page appears blank. To troubleshoot this pr ...

What is the best way to pass the text of a selected option in a dropdown menu to a function when a button is clicked in AngularJS?

Alright, so I've got this HTML page with a select element. The select has three options defined in the $scope below: <div id="mainID" ng-controller="theController"> <form name="assetTypeForm" class="form-horizontal" role="form" novalidat ...

The process of automating e-signature input with Selenium

Is there a way to automate e-signature input in Selenium? I attempted using the action class to draw a line on the canvas object. Below is the code I used: Actions actionBuilder=new Actions(driver); Action drawOnCanvas=actionBuilder ...

Eliminate all elements marked with a particular class when the user clicks outside of a

I am currently building upon a project that I previously started here. Essentially, what I'm doing is dynamically generating tooltip popups that appear next to a link when it is clicked. However, I now need these tooltips to close when any click even ...

Tips for accessing image data generated by the Bootstrap File Input plugin

I have a div that utilizes the Bootstrap File Input plugin to select, show, change, and cancel images. The image data is generated dynamically by the plugin. <div class="fileinput fileinput-new" data-provides="fileinput"> <div class="fileinpu ...

Deactivate the submission button when there are no search results in typeahead.js

How can I disable the submit button if there are no search results found? The form should not be submitted in this scenario. I am currently using typeahead.js for my code. $('.typeahead').typeahead(null, { name: 'suburb', disp ...

Sending a div class as a parameter to a JavaScript function

Wondering if it's possible to pass a div's class into a JavaScript function. I'm using SquareSpace so adding an id to the div is not an option, but it works fine with divs that have ids. JQuery is already loaded. This is my current train of ...

Trigger Function on Input Change in Angular 2

Key aspects of component nesting: export class Child { @Input() public value: string; public childFunction(){...} } Main component responsibilities: export class Parent { public value2: string; function1(){ value2 = "a" } function2( ...

Struggling to set the value for a variable within an Angular factory?

When dealing with a variable as an array, I have no trouble pushing objects inside and retrieving the values within the controller. However, when trying to directly assign an object to that variable, I run into issues. If anyone can assist me in achieving ...

Encountering invalid parameters while attempting to utilize the track.scrobble service from the Last.Fm API in a Node.js application

After successfully completing the Last.Fm authentication process following the instructions provided here, I received the session key without any issues. However, my attempts to make an authenticated POST request to the track.scrobble method of the Last.Fm ...

Tips for including an additional label on a data point within a scatter plot using the Highcharts JavaScript framework

Incorporating the Highcharts JavaScript library, I am visualizing float values by passing them from PHP to the JS code. In the image below, you can observe that upon hovering over each point, the corresponding axes values are displayed along with the text ...

Every time I try to access my website, all I see is the WordPress installation process page

After initially hosting a WordPress website, I made the decision to switch over to SPIP. However, when attempting to access the site on my laptop, it continues to bring up the WordPress installation process. Interestingly enough, the website appears to lo ...

Creating an Http interceptor in Ionic 3 and Angular 4 to display a loading indicator for every API request

One of my current challenges involves creating a custom HTTP interceptor to manage loading and other additional functions efficiently. Manually handling loading for each request has led to a considerable increase in code. The issue at hand: The loader is ...

Experiencing problems with web page layout when using bootstrap on IE8?

Here is a code snippet that functions correctly in IE9 and later versions, but encounters issues in IE8: <div class="col-lg-5 col-md-5 col-sm-6 col-xs-6" id="div1"> <div class="panel panel-default" style="" id="panel1"> ...

Firefox does not allow contenteditable elements to be edited if they are nested inside a parent element that is draggable

Here is a basic HTML example: <div draggable=true> <div contenteditable=true>can't edit me</div> </div> When testing in Chrome, I noticed that I was able to edit the contents of the contenteditable div, however, this functi ...