Keep the button in a single color unless it is being hovered over

Is there a way to create a button that changes color on hover, then reverts back to its original color after it's clicked?

I'm facing an issue where my button initially has a red gradient, then changes color when hovered over, but turns white once it's been clicked. What I actually want is for it to return to red instead of white after being clicked.

I attempted to solve this problem by introducing 'focus'. This seemed to work initially - after the button was clicked, it would revert back to its original color while in focus. However, hovering didn't trigger the color change until the focus was removed from the button.

So far, I haven't been able to find a solution using various pseudo classes or javascript code to maintain the button's red color unless it's being hovered over.

Edit

In response to a suggestion from @webeno, I decided to remove the CSS and try a new approach using the following javascript. Unfortunately, the button still retains its default style. (In this scenario, the colors are blue initially and turn red upon hover.)

<button class = "btn">Go</button>
<script>
.red {background-color: #f00;
}
     
.blue {background-color: #00f;
}

$(document).ready(function(){
   $('.btn').mouseover(function(){
      $(this).addClass('red');
   }).mouseout(function(){
      $(this).addClass('blue');
   });
});
</script>

Answer №1

To achieve the desired color change effect on mouse hover, simply implement a CSS solution.

.button, .button:focus, .button:active {background-color: #00f;}

.button:hover {background-color: #f00;}

Answer №2

Your CSS definitions were mistakenly placed inside the script tag, when they should be in the head section under the style tag or in a separate .css file referenced in the head.

Here's how it should be done:

<head>
    <link rel="stylesheet" type="text/css" href="mystyle.css">
</head>

...or...

<head>
    <style>
        /* Place your CSS rules here */
    </style>
</head>

Once you make this change, the code at the bottom of your question should function correctly (as long as you also link to jQuery properly, similar to how you link your stylesheet).

Below is the full corrected code snippet:

<head>       
  <style>     
    .red {background-color: #f00;}     
    .blue {background-color: #00f;} 
  </style>
  <script>
    $(document).ready(function(){
      $('.btn').mouseover(function(){
        $(this).addClass('red');
      }).mouseout(function(){
        $(this).addClass('blue');
      });
    });
  </script> 
</head>
<body>
  <button class = "btn">Go</button>
</body>

You can view a demo of the corrected code on JSFiddle here: https://jsfiddle.net/6wbnvy7g/

One important note is that you need to remove the class each time an event occurs, otherwise both classes will accumulate and cause issues with hovering over the button. I recommend updating your jQuery code to one of the following options:

$(document).ready(function(){
   $('.btn').mouseover(function(){
      $(this).removeClass('blue');
      $(this).addClass('red');
   }).mouseout(function(){
      $(this).removeClass('red');
      $(this).addClass('blue');
   });
});

Or you could simplify it using the .hover function in jQuery:

$(document).ready(function(){
   $('.btn').hover(function(){
      $(this).removeClass('blue');
      $(this).addClass('red');
   }, function(){
      $(this).removeClass('red');
      $(this).addClass('blue');
   });
});

An updated version of the JSFiddle showcasing this alternate code can be found here: https://jsfiddle.net/6wbnvy7g/2/

Answer №3

After trying various solutions, I found that incorporating zatee29's suggestion into my CSS code was the key to success:

.btn, .btn:focus, .btn:active {background-color: #00f;}
.btn:hover {background-color: #f00;}

Of course, don't forget to include the button element in the HTML:

<button class = "btn">Go</button>

This approach achieved the desired effect effortlessly. The button initially appears blue, changes to red when hovered over, and then reverts back to blue.

It is worth noting that webeno's alternative solution yielded the same outcome in JSFiddle, although it didn't seem to work seamlessly with my current program for some reason.

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

What is the best way to increase the space between table columns in CSS?

I'm struggling to increase the space between the columns in a simple table with two columns. The column-gap property doesn't seem to be working for me. Any suggestions on how I can achieve this? JSFiddle #t td { -webkit-column-g ...

Is there a way to transform an HTML table into an Excel file with several sheets?

Is there a way to transform multiple HTML tables into an Excel file with multiple worksheets? I need assistance with this task. You can find an example here function exportTablesToExcel() { var tableContent = "<table border='2px'>< ...

Issue with Material-UI and React: Changes not visible after using <ThemeProvider>

I've encountered an issue where the "ThemeProvider" tag does not seem to be causing any changes in my project, even when following a simple example like the one shown below. Despite having no errors or warnings in the browser console (except for some ...

Unable to display image using jQuery load() function on an HTML page

I have implemented the following code snippet to load an HTML page within a div: $("#htmlViewer").load("conversion_test/to_convert_3264/"+getPageName(pageCount)+".htm", function(response, status, xhr) { if (status == "error") { ...

In the Android Chrome browser, the settings of the meta viewport attribute do not take effect when the device is in full screen mode

While using the fullscreen api in Android, I noticed that the values of meta viewport attributes like initial-scale and user-scalable are not reflected in the browser when in full screen mode. However, when not in full screen mode, these values work as exp ...

A step-by-step guide on utilizing img src to navigate and upload images

I would like to hide the input type='file' element with id "imgInp" that accepts image files from users. Instead, I want them to use an img tag to select images when they click on a specific img tag. How can this be achieved using jQuery? Here i ...

PHP post data repeater form

I am working on creating a form that utilizes form repeater, but for some reason, I am unable to successfully register the form data in the database. Here is the HTML code I am using: <div class="m-portlet__body" id="myRadioGroup"> <div id=" ...

What is the process for taking a website project running on localhost and converting it into an Android web application using HTML, CSS, and JavaScript

Looking for recommendations on how to create an Android web application using HTML, CSS, and JavaScript. Any suggestions? ...

What is the best way to implement a jQuery post for a file upload form?

My form has the following structure: <form id="uploadForm" name="uploadForm" method="post" enctype="multipart/form-data"> <input type="file" id="uploadFile" name="uploadFile" /><br /> <input type="submit" id="process" name="pr ...

When utilizing a script to deliver a true or false response for jQuery's .load() function

Currently, I have found myself delving deep into jquery to manage the ajax requests in my web applications. Specifically, I am working on a bidding system in PHP that heavily relies on mod_rewrite. Using jQuery with a confirm dialog, I send an Ajax request ...

Unable to trigger JavaScript function from ASP.NET MVC HTML view

I am encountering an issue with my ASP.NET MVC project where I am attempting to call a JavaScript function to record a user's selection from a listbox. Despite duplicating the JavaScript function in multiple places, it is still not being found. What c ...

Steps for inserting an image:

Looking for help adding a static header image to a simple HTML page that contains two div tags: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1 /DTD/xhtml1-strict.dtd"> <html> <head> ...

Enhancing User Interactivity with JQuery Ajax Voting

Currently, I am referencing a JQuery Ajax Voting system guide to help me set up a similar system. However, I have concerns about the security aspects of this guide. As it stands, the guide simply stores the ID of an item and its corresponding voting statis ...

Declare a jQuery variable containing HTML elements

Greetings! I am facing an issue while attempting to create a jQuery variable that stores a table meant for displaying in different sections of a website. Unfortunately, I am encountering an error and struggling to comprehend the reason behind it. Below is ...

HTML elements generated dynamically do not possess any jQuery properties

I have implemented a draggable list of Div elements using jQuery. Here is the code: <div id="external-events"> <h4>List Of Staffs</h4> <div class="external-event" data-id="1">Name</div> //Draggab ...

Using AJAX POST for real-time validation of usernames and email addresses

Creating a basic form with AJAX and jQuery to validate the username and email address before submitting: <body> <div> <h5> Registration </h5> <hr /> <div> Username: <input type="text" size="32" name="membername" ...

A combination of fixed width column and dynamic content area in Bootstrap design

Is there a way to achieve the combination of fixed and fluid width columns using Twitter Bootstrap alone, similar to this example? The HTML and CSS in the example make it seem simple. But can this be done solely with Bootstrap? ...

Identifying the moment when attention shifts away from an element

Is it possible to detect when focus occurs outside an element without relying on global selectors like $(document), $(body), or $(window) for performance reasons? If achieving this without global selectors is not feasible, provide a provable reason expla ...

What is the best way to incorporate styled components and interpolations using emotion theming?

I've been building a React web application with a dynamic theme feature using the emotion-theming library. This allows users to switch between different environments, each with its own unique theme. To achieve this, I created my own CustomThemeProvide ...

Troubleshooting Hierarchical Ordering in Django-MPTT's recursetree Function

I am currently utilizing the django-mptt package within my Django application, and I have encountered an issue when trying to use the .order_by() method in conjunction with a filter. Despite attempting different criteria for ordering, the results remain un ...