Ways to implement two distinct background color changing features

Is there a way to reset mouseover after mouseout for changing the background color of an element on mouseover, mouseout, and onclick events in Javascript?

        function init() {
          document.getElementById('default').onmouseover = function() {
            tabHoverOn('default', 'grey')
          };
          document.getElementById('default').onmouseout = function() {
            tabHoverOff('default', 'yellow')
          };
          document.getElementById('section2').onmouseover = function() {
            tabHoverOn('section2', 'grey')
          };
          document.getElementById('section2').onmouseout = function() {
            tabHoverOff('section2', 'yellow')
          };
          document.getElementById('section3').onmouseover = function() {
            tabHoverOn('section3', 'grey')
          };
          document.getElementById('section3').onmouseout = function() {
            tabHoverOff('section3', 'yellow')
          };
        }


        function tabHoverOn(id, bgcolor) {
          document.getElementById(id).style.backgroundColor = bgcolor;
        }

        function tabHoverOff(id, bgcolor) {
          document.getElementById(id).style.backgroundColor = bgcolor;
        }
        var current = document.getElementById('default');

        function tab1Highlight(id) {

          if (current != null) {
            current.className = "";
          }
          id.className = "tab1highlight";
          current = id;
        }

        function tab2highlight(id) {

          if (current != null) {
            current.className = "";
          }
          id.className = "tab2highlight";
          current = id;
        }

        function tab3highlight(id) {
          if (current != null) {
            current.className = "";
          }
          id.className = "tab3highlight";
          current = id;
        }
        window.onload = init();
body {
  width: 900px;
  margin: 10px auto;
}
nav {
  display: block;
  width: 80%;
  margin: 0 auto;
}
nav > ul {
  list-style: none;
}
nav > ul > li {
  display: inline-block;
  margin: 0 3px;
  width: 150px;
}
nav > ul > li > a {
  width: 100%;
  background-color: #ffff66;
  border: 1px solid #9b9b9b;
  border-radius: 12px 8px 0 0;
  padding: 8px 15px;
  text-decoration: none;
  font-weight: bold;
  font-family: arial, sans-serif;
}
main {
  display: block;
  width: 80%;
  margin: 0 auto;
  border: 1px solid #9b9b9b;
  padding: 10px;
}
main > h1 {
  font-size: 1.5em;
}
.tab1highlight {
  background-color: #339966;
  color: white;
}
.tab2highlight {
  background-color: #ff6666;
  color: white;
}
.tab3highlight {
  background-color: #6600ff;
  color: white;
}
main img {
  border: 5px solid #eeefff;
  width: 80%;
  margin-top: 20px;
}
<body>
<nav>
    <ul>
        <li><a href="#sec1" id="default" onclick="tab1Highlight(this)">Section 1</a></li>
        <li><a href="#sec2" id="section2" onclick="tab2highlight(this)">Section 2</a></li>
        <li><a href="#sec3" id="section3" onclick="tab3highlight(this)">Section 3</a></li>
    </ul>
</nav>
<main>
    <h1>Exercise: Navigation Tab #5</h1>
    <ul>
        <li>
            Combine the navigation tab exercises #1, #3, and #4 in one file, including <br>
            <ul>
                <li>temporarily change the background color of a tab when the cursor is hovering on it.</li>
                <li>set the foreground and background color of the tab being clicked.</li>
                <li>change the background color of the main element based on the selected tab.</li>
            </ul>
            <p>
                To test, click on a tab and then move your mouse around.  For example, the third tab is clicked, the tab background color is switched to blue.  Then hover the mouse over the third tab, the background color of the tab should be switch to light green and then back to blue after the mouse moves out.
            </p>

            <img src="menu_tab5.jpg">


        </li>
    </ul>
</main>

Answer №1

To avoid cluttering JavaScript with CSS, it's best practice to keep them separate whenever possible. An effective solution for handling hover effects is using the CSS pseudo selector :hover instead of implementing color changes in JavaScript. Simply assign the same class to all tabs and define the required styles once:

.tab {
  background-color: yellow;
}

.tab:hover {
  background-color: grey;
}

After setting this up, you can manage click styling through CSS by adding or removing a specific class when a tab is clicked.

In your CSS file:

.tab.clicked {
  background-color: blue;
}

Then, in JavaScript, you can handle tab clicks like this:

var tabs = document.getElementsByClassName('tab');
for (i = 0; i < tabs.length; i ++) {
  tabs[i].onclick = function (ev) {
    for (i = 0; i < tabs.length; i ++) {
      tabs[i].classList.remove('clicked');
    }
    ev.currentTarget.classList.add('clicked');
  };
}

For a visual representation, check out this JSFiddle.

Answer №2

Consider manipulating a Boolean variable

var Element = document.getElementById('default');
var pressed = false;

Element.onclick = function(){
    pressed = true;
    // insert more actions here
}
Element.onmouseover = function(){
    pressed = false;
    // insert more actions here
}
Element.onmouseout = function(){
    if(!pressed){
    // insert more actions here
    }
}

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

"Encountering errors when attempting to load partials on the server-side

Currently, I am working on creating a basic single page application using the MEAN stack. Everything was running smoothly when I was developing on localhost. However, upon uploading the code to the server, I encountered a status code 500 (Internal Server ...

Find the highest value in a MySQL column

Currently, I am working with a mysql table in NodeJs where there is a column called packageId. My goal is to fetch the highest value from that particular column. For instance, if the values in the column are 2,3,4,5, I only want to retrieve 5. I attempted ...

Convert HTML templates into JavaScript on the client side using Angular framework along with Browserify, Babel, ES2015, and Gulp

Having trouble with my Browserify Angular configuration file, specifically when using require() to load HTML templates. I attempted to use stringify or browserify-ng-html2js in the transform() function, but it resulted in multiple transform calls in my gul ...

Jest Testing encounters an error: TypeError - the variable state.userInfo cannot be iterated

Every time I run my jest tests on a specific reducer, I encounter a TypeError. It appears to be related to the inability to locate the state of the store? Upon running yarn test --coverage on the reducer test file, this is the exact error displayed in the ...

Phantom writing reminiscent of the ghostly prose found on a Tumblr registration

Is there a way to create a URL field similar to the one on ? It's the field where the text is faded and when you click on it to type, it automatically appends ".tumblr.com" that cannot be erased or highlighted. The JavaScript used for this feature is ...

proper integration of socket.io

I have been experimenting with socket io for my project to display online friends, and I have noticed an issue that seems strange to me. Every time the page is rerendered (whether due to a user changing their profile information or sending a friend request ...

Tips for obtaining an Amazon email within an Alexa SDK V2 skill

I am currently working on creating an Alexa skill and I need assistance with extracting the user's email in order to compare it with a database. Most of the resources I found online are using SDK v1, which is outdated now. Does anyone have expertise i ...

Validation does not occur when the submit button has an ng-click event attached to it

This is the form I created: <form action="" ng-controller="forgotCtrl as forgot" name="forgotForm"> <div class="form-group row"> <label for="email" class="col-sm-2 form-control-label">Email address</label> ...

Getting just the page path in Express.js can be achieved by utilizing the `req.path

Is there a way to extract only the page path in express.js? I need to dynamically render pages based on the URL. For example, when accessing http://example.com/a_lion, my code should search for an object in an array with a title that matches the path (a_li ...

Tips for storing arrays in AngularJS with JavaScript

I am new to using JavaScript. I have a function that stores objects in an array to an Angular model. Here is an example: function getSpec(){ debugger var i; for(i=0;i<main.specifications.length;i++){ main.newProduct.Specification= ( ...

Mapping objects in an array with Javascript

This code snippet is intended for a React Native Chat app. The structure of my data should look something like this: const chatData = [ { id: 1, name: 'John Doe', messages: [ {text: 'Hello', sentAt: 'time here' ...

Navigating through the drupal module directory using JavaScript

Is there a way to retrieve the module path in Drupal 7 from which a .js file was loaded? Although JS is primarily a front-end language, is it possible that Drupal includes this information within the Drupal object? Essentially, I am trying to achieve so ...

AngularJS script to dynamically update a table upon selecting an option from the dropdown menu

Just starting out with Angularjs and facing a challenge. I have a table with a "Update" button on the UI and a drop-down option in the 3rd column. The requirement is, upon selecting an option from the drop-down and clicking the "Update" button, the values ...

Tips on destructuring an object property from a Pinia getter that may return an object based on a condition

I obtained this particular Store: export const useMyStore = defineStore('myStore', { state: () => { return { openTransOnly: false, keyword: '', openTransStatus: { nextPage: 0, complete: false }, pastDueT ...

Unable to display MathJax content on the HTML webpage

After implementing MathJax in the header of the page: <script type="text/javascript" id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script> I inserted Latex into the ...

Is there a way for me to limit my usage of the async keyword in my code

Consider the scenario outlined below, using Javascript: Deep within the call stack, Something transforms into a Promise This transformation can occur due to various reasons. // a calls b, calls c, and so on. function z(){ // Let's assume this ...

The upcoming picture does not have a valid "width" or "height" attribute. Please ensure that these properties are set to numerical values

Recently, I attempted to apply my custom style definition to the Next image element, but encountered an unexpected error. Unhandled Runtime Error Error: Image with src "/images/search_icon_green.svg" has invalid "width" or "height& ...

Utilizing the Command Line/Window feature within Visual Studio Code

As a newcomer to Visual Studio Code, I'm currently using the latest Version: 1.29.1. When I used Matlab, I had access to a script window for writing code, a Command Window for testing code snippets and viewing variable values, as well as a workspace ...

How can I make the footer on my webpage have a white background?

My goal is to create a white div that spans from point (A) to point (B) on the page, just like in the image. I aim for it to stretch all the way down to cover the entire browser without showing any gray background underneath, even when the page is scrolled ...

Blinking magic of dynamic rendering with NextJs

I am facing some challenges with dynamically importing a component in my NextJs application. I am attempting to import the Froala text editor, which is supported for React. However, when I try to import it, I encounter errors stating that window is not def ...