Let us know when the information on a different tab is updated

I have multiple tabs and I want to indicate when a change occurs on another tab that the user hasn't clicked. For example, if the user hits the run button while on the Data pane, I would like the Errors tab to change to red to show that there was a change on that tab as well. How can I achieve this? Conversely, if they're on the error tab, the Data tab should turn red. Also, once the tab is clicked, I want to remove the red color. Any assistance would be appreciated!

Desired Output

runCode = () => {
   document.getElementById("dataOutput").innerHTML = "Paragraph changed!";
   document.getElementById("errorOutput").innerHTML = "Error Occurred";
 }
.fab {
  width: 60px;
  height: 60px;
  background-color: #A7C0CD;
  border-radius: 50%;
  box-shadow: 0px 3px 15px rgba(0,0,0,0.2);
  transition: all 0.1s ease-in-out;
  font-size: 15px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  color: white;
  text-align: center;
  line-height: 58px;
  float: right;
  margin: 8px;
  z-index: 5000;
  position: absolute;
  right:0;
  top:0;
}

.fab:hover {
  box-shadow: 0px 3px 15px rgba(0,0,0,0.2);
  transform: scale(1.05);
}
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
  </head>
    <!-- Visual appearance -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap/dist/js/bootstrap.min.js"></script>
  <body>

<div class="fab" id="runCode" onclick="runCode();">RUN</div>
        <ul class="nav nav-tabs">
          <li class="active"><a data-toggle="tab" href="#data">Data</a></li>
          <li><a data-toggle="tab" href="#error">Errors</a></li>
        </ul>

        <div class="tab-content">
          <div id="data" class="tab-pane fade in active">
            <div id="dataOutput"></div>
          </div>
          <div id="error" class="tab-pane fade">
            <div id="errorOutput"></div>
          </div>
        </div>

  </body>
</html>

Answer №1

Utilizing MutationObservers, I believe I have successfully achieved your desired outcome. Although it may require some restructuring, the essence should be clear:

// To reuse our tabs, we store a reference to them
const data = document.getElementById("dataOutput");
const error = document.getElementById("errorOutput");
const runCode = () => {
  data.textContent = "Paragraph changed!";
  error.textContent = "Error Occured";
};

// Remove the 'changed' class from clicked tabs
const tabs = document.querySelector('.nav-tabs');
tabs.onclick = ({ target }) => target.classList.remove('changed');

// Watch for mutations in our output elements
new MutationObserver(observe).observe(data, { childList: true });
new MutationObserver(observe).observe(error, { childList: true })

function observe(mutations) {
  const target = mutations[0].target;
  // Extract the name of the changed tab by removing 'Output' from the target's id
  const tabName = target.id.slice(0, target.id.indexOf('O'));
  const tab = document.querySelector(`a[href="#${tabName}"]`);
 
  // Add the 'changed' class to the corresponding tab if it's not currently active
  if (!target.parentNode.classList.contains('active')) {
    tab.classList.add('changed');
  }
}
 
.fab {
  width: 60px;
  height: 60px;
  background-color: #A7C0CD;
  border-radius: 50%;
  box-shadow: 0px 3px 15px rgba(0,0,0,0.2);
  transition: all 0.1s ease-in-out;
  font-size: 15px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  color: white;
  text-align: center;
  line-height: 58px;
  float: right;
  margin: 8px;
  z-index: 5000;
  position: absolute;
  right:0;
  top:0;
}

.fab:hover {
  box-shadow: 0px 3px 15px rgba(0,0,0,0.2);
  transform: scale(1.05);
}

a.changed {
  color: red
}
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <head>
    <!-- Visual appearance -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7f150e0a1a0d063f4c514b514e">[email protected]</a>/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f1939e9e858285839081df9c989fdf9b82b1c2dfc2dfc4">[email protected]</a>/bootstrap.min.js"></script>
  </head>
  <body>

<div class="fab" id="runCode" onclick="runCode();">RUN</div>
        <ul class="nav nav-tabs">
          <li class="active"><a data-toggle="tab" href="#data">Data</a></li>
          <li><a data-toggle="tab" href="#error">Errors</a></li>
        </ul>

        <div class="tab-content">
          <div id="data" class="tab-pane fade in active">
            <div id="dataOutput"></div>
          </div>
          <div id="error" class="tab-pane fade">
            <div id="errorOutput"></div>
          </div>
        </div>

  </body>
</html>

Answer №2

To illustrate how this can be achieved:

executeCode = () => {
   document.getElementById("dataOutput").innerHTML = "Updated paragraph!"
   document.getElementById("errorOutput").innerHTML = "An Error Occurred"
   document.querySelector("li:not(.active) > a").style.color = "Blue"
 }
.fab {
      width: 60px;
      height: 60px;
      background-color: #A7C0CD;
      border-radius: 50%;
      box-shadow: 0px 3px 15px rgba(0,0,0,0.2);
      transition: all 0.1s ease-in-out;
      font-size: 15px;
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
      color: white;
      text-align: center;
      line-height: 58px;
      float: right;
      margin: 8px;
      z-index: 5000;
      position: absolute;
      right:0;
      top:0;
    }

    .fab:hover {
      box-shadow: 0px 3px 15px rgba(0,0,0,0.2);
      transform: scale(1.05);
    }
 <html>
      <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
      </head>
        
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
        <script src="https://cdn.jsdelivr.net/npm/jsdelivr@16.5.6/dist/jquery.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/jsdelivr@13.48.32/bootstrap.min.js"></script>
      </head>
      <body>

    <div class="fab" id="executeCode" onclick="executeCode();">EXECUTE</div>
            <ul class="nav nav-tabs">
              <li class="active"><a id="dataTab" data-toggle="tab" href="#data">Data</a></li>
              <li><a id="errorTab" data-toggle="tab" href="#error">Errors</a></li>
            </ul>

            <div class="tab-content">
              <div id="data" class="tab-pane fade in active">
                <div id="dataOutput"></div>
              </div>
              <div id="error" class="tab-pane fade">
                <div id="errorOutput"></div>
              </div>
            </div>
      </body>
    </html>

For a more interactive approach, Javascript can identify the displayed text in a tab and change the corresponding tab's color to red.

Simply assign IDs to the tabs and adjust the css property for "color".

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

Would it be considered poor design to send back a partial view with just a simple JavaScript alert in my ASP.NET MVC application?

I have a unique Action method that handles exceptions by returning an _error partial view: [AcceptVerbs(HttpVerbs.Post)] public PartialViewResult Register(string id, int classid) { try { Thread.Sleep(3000); User user = r.FindUser(i ...

What steps can be taken to issue an alert when the table does not contain any records?

Upon clicking the submit button, the value from the database is retrieved based on the hidden field ID and displayed in a table. If the value is present, it should load in the table; otherwise, an alert saying 'there is no record' should be displ ...

Utilize JavaScript to redirect based on URL parameters with the presence of the "@ symbol"

I need help redirecting to a new page upon button click using a JS function. The URL needs to include an email address parameter. <form> <input type="email" id="mail" placeholder="ENTER YOUR EMAIL ADDRESS" requir ...

What is the best way to ensure the search box remains fixed in the top navigation bar while maintaining a fluid and responsive design?

I've been struggling as a novice programmer, and even with the help of more experienced programmers, we haven't been able to figure it out. I'm trying to integrate a search box into the top navigation that adjusts responsively to different ...

Stop the promise chain when the first error callback is encountered

Here is a sequence of promises I am dealing with: Transaction.findPublic({}).then(function(transactions) { combined = combined.concat(transactions); return JoinEvent.find().exec(); }, function(err) { return res.status(503).send(er ...

Enhancing WordPress Icons for Parent and Child Elements

I am seeking to customize icons on a WordPress website. The site contains a variety of product categories, including subcategories. My goal is to display one icon for parent categories and a different icon for child categories. I have tried the following ...

Verifying dynamic number inputs generated using JavaScript values and calculating the total with a MutationObserver

Preamble: I've referenced Diego's answer on dynamic field JS creation and Anthony Awuley's answer on MutationObserver for the created fields. After extensive searching, I found a solution that meets my needs, but it feels somewhat bulky des ...

Utilizing JavaScript to enable HTML checkbox to be checked automatically

I am currently working on a constructor that generates checkboxes within a loop. My issue lies in attempting to set these checkboxes as checked, however, it doesn't seem to be functioning correctly. Below is the code snippet: funct ...

Having trouble with AngularJs and moment.js integration?

Looking to create a simple webpage using Angular Js for date calculations. Utilizing moment.js from http://momentjs.com/ Below is the current code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> ...

Hide Material UI Drawer when clicking elsewhere

Attempting to implement the Drawer component in Material UI React. Want to ensure that the state within the Drawer component persists even when the Drawer is closed, so passing variant="persistent" in Drawer component. The issue arises with the ...

Update the color of the angular material input text box to stand out

Hey there, I'm currently using Angular Material and I want to change the color of the input focus when clicked. At the moment, it's displaying in purple by default, but I'd like it to be white instead. https://i.stack.imgur.com/vXTEv.png ...

Enable seamless SCSS inclusion in Vue components through automatic importing

My goal is to import a variables.scss file globally in my Vue project. I have set up my vue.config.js file as follows: module.exports = { css: { loaderOptions: { scss: { additionalData: `@import "@/st ...

Toggle display of list items using jQuery on click event

I want to be able to toggle the visibility of my submenus when a link is clicked. Here's an example code snippet: <ul> <li><a href="www.example.com">Test</a></li> <li><a href="www.example.com ...

Creating a Navigation Bar using the Flexbox property

As a beginner, I attempted to create a navbar using flex but did not achieve the desired outcome. My goal is to have: Logo Home About Services Contact * { margin: 0; padding: 0; font-family: ...

The code is triggering IE 8 to switch to compatibility mode resembling IE7

I have created a custom javascript function that generates a pop-up, and I am invoking this function in my code. However, every time I click the button, the browser switches to IE 7 compatibility mode and the pop-up appears behind the button. Below is my ...

Passport JS fails to pass req.user data to Angular Controller

Currently, I am in the process of developing an application that utilizes an Express/Node backend along with Angular JS for the front end. This stack is fairly new to me, and I have been struggling with retrieving data in an Angular Service + Controller. ...

Does JSON have a special reserved key for identifying the time?

I've noticed an interesting issue when logging the json string of a key labeled tid - it always shows up as 0. Take a look at this example: var transaction = {tid:1, type:0, time:126312736}; var transStr = JSON.stringify(transaction); console.log(tra ...

What is the best way to iterate through an array containing multiple objects in order to create a graph?

My API response contains multiple objects organized in an array: [{"symbol":"AAPL","date":"2020-02-27","adj_close":68.24}, {"symbol":"TSLA","date":"2020-02-27","adj_close":133.8}, {"symbol":"TSLA","date":"2020-02-28","adj_close":122.3}, {"symbol":"AAPL" ...

Angular 2 encountered a fatal error: Issues with parsing the template:

Here is the code snippet I am currently working with: <div class="container"> <div [hidden]="loggedIn"> <md-grid-list cols="6" [style.margin-top]="'20px'"> <md-grid-tile [colspan]="1"></md-grid-tile> I have already ...

I am currently struggling with the mapquest GeoJson integration within my Node/Express application. I keep encountering an error message that reads "body used already."

I attempted to utilize the mapquest API by following the provided documentation, however I encountered an error message: HttpError: body used already for: Below is my geoCoder.js configuration: const NodeGeocoder = require('node-geocoder'); con ...