Include a return or delete from the default IO statement

I am utilizing an intersection observer that alters the header's font-color and background-color based on the content intersecting with it. This change is determined by the presence of data-color and data-background attributes declared on the div/section elements.

In its default state, when no attributes are specified on a div/section, the header should remain unchanged. However, currently, it retains its last modification and does not revert to the default settings. Therefore, my inquiry is regarding how to implement a mechanism to return/remove the header back to its default state within the existing script? In the provided fiddle example, you will notice that the second div without any attributes specified fails to reset the header to its default appearance of black text on a green background.

Fiddle

* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: sans-serif;
}

.g-100vh {
height: 100vh
}

header {
  min-height: 50px;
  position: fixed;
  background-color: green;
  color: black;
  width: 100%;
}

Intersection Observer

  const header = document.querySelector('header');
  const sections = document.querySelectorAll('div');
  const config = {
    rootMargin: '0px',
    threshold: [0.05, 0.95]
  };

  const observer = new IntersectionObserver(function (entries, self) {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        if (entry.intersectionRatio > 0.95) {
          header.style.color = entry.target.dataset.color;
          header.style.background = entry.target.dataset.background;   
        } else {
      if (entry.target.getBoundingClientRect().top < 0 ) {
          header.style.color = entry.target.dataset.color;
          header.style.background = entry.target.dataset.background;
          }
        } 
      }
    });
  }, config);

  sections.forEach(section => {
    observer.observe(section);
  });

Answer №1

If the element doesn't have a specified color or background, you can set it back to the default one in your code;

Updated Code:

header.style.color = entry.target.dataset.color !== undefined ? entry.target.dataset.color : "black";
header.style.background = entry.target.dataset.background !== undefined ? entry.target.dataset.background : "green"; 

See the working example below:

const header = document.querySelector('header');
const sections = document.querySelectorAll('div');
const config = {
  rootMargin: '0px',
  threshold: [.05, .95]
};

const observer = new IntersectionObserver(function (entries, self) {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      if (entry.intersectionRatio > 0.95) {
        header.style.color = entry.target.dataset.color !== undefined ? entry.target.dataset.color : "black";
        header.style.background = entry.target.dataset.background !== undefined ? entry.target.dataset.background : "green"; 
      } else {
        if (entry.target.getBoundingClientRect().top < 0 ) {
        header.style.color = entry.target.dataset.color !== undefined ? entry.target.dataset.color : "black";
        header.style.background = entry.target.dataset.background !== undefined ? entry.target.dataset.background : "green"; 
        }
      } 
    }
  });
}, config);

sections.forEach(section => {
  observer.observe(section);
});
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: sans-serif;
}

.g-100vh {
height: 100vh
}

header {
  min-height: 50px;
  position: fixed;
  background-color: green;
  color: black;
  width: 100%;
}
<header>
 <p>Header Content </p>
</header>
<div class="grid-30-span g-100vh" style="background-color:darkblue;" data-color="white" data-background="blue">
    <img 
    src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1.414 1'%3E%3C/svg%3E"
    data-src="/images/example_darkblue.jpg" 
    class="lazyload"
    alt="<?php echo $title; ?>">
</div>

<div class="grid-30-span g-100vh" style="background-color:lightgrey;">
    <img 
    src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1.414 1'%3E%3C/svg%3E"
    data-src="/images/example_lightgrey.jpg" 
    class="lazyload"
    alt="<?php echo $title; ?>">
</div>

<div class="grid-30-span g-100vh" style="background-color:darkblue;" data-color="white" data-background="blue">
    <img 
    src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1.414 1'%3E%3C/svg%3E"
    data-src="/images/example_darkblue.jpg" 
    class="lazyload"
    alt="<?php echo $title; ?>">
</div>

<div class="grid-30-span g-100vh" style="background-color:lightgrey;" data-color="black" data-background="grey">
    <img 
    src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1.414 1'%3E%3C/svg%3E"
    data-src="/images/example_lightgrey.jpg" 
    class="lazyload"
    alt="<?php echo $title; ?>">
</div>

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

When utilizing the dojox.grid.enhanceGrid function to delete a row, the deletion will be reflected on the server side but

I have a grid called unitsGrid that is functioning correctly. I am able to add and delete rows, but the issue arises when I try to delete rows - they do not disappear from my unitsGrid. I have spent hours trying to debug the code but I cannot seem to fin ...

Changing background colors of dropdown items in VueJs

Currently grappling with understanding the intricacies of styling in web development (specifically VueJS). I am facing some challenges: I am dynamically rendering colored dropdowns filled with dropdown items. I am struggling to figure out how to change t ...

Updating text color in JavaFX for a textarea

I'm having trouble getting this to work. After checking the CSS analyzer in the scene builder, it seems that changing the text color in a textarea requires something like this: .text-area .text { -fx-fill: #1e88e5; -fx-font-size: 32px; } How ...

How can we eliminate duplicate arrays of objects within a multi-dimensional array using ReactJS and JavaScript?

let galleryItems = [ {id: 1029, name: 'College-Annual-Day.jpg', ext: 'jpg', mime: 'image/jpeg', size: 91153, …}, {id: 1029, name: 'College-Annual-Day.jpg', ext: 'jpg', mime: 'image/jpeg', si ...

Wondering how to execute logic before generating a template in a custom directive?

I am interested in creating a unique custom directive that can take an array of strings and display it as a table. Here is an example of how I envision it: 'string1' | 'string2' | 'string3' | 'string4' 'stri ...

Error: The login is invalid due to authentication failure with code 535 5.0.0

I'm currently working on setting up Outlook calendar events by integrating a mailing service with my project. I'm using the Express framework and Mongoose queries for this purpose. Below is the code snippet I have implemented: var _ = require(& ...

Tips for switching a group of buttons within a userscript by clicking a single button?

Apologies if my wording is not clear, allow me to clarify. I am in the process of developing a userscript that will display a set of buttons below a main button when clicked. These additional buttons will serve different functions and should disappear whe ...

"Hiding elements with display: none still occupies space on the

For some reason, my Pagination nav is set to display:none but causing an empty space where it shouldn't be. Even after trying overflow:hidden, visibility:none, height:0, the issue persists. I suspect it might have something to do with relative and ab ...

Verifying conditions in an AJAX-based upload system using JavaScript

Recently, I was working on implementing a JavaScript/AJAX upload system with a progress indicator based on a tutorial. The process went smoothly, and I even managed to include a CSS progress bar for visual representation. However, I encountered a hurdle th ...

Error: The URI you are trying to access is restricted and access has been denied

I'm facing an issue with my HTML file that contains multiple d3-graphs embedded directly within script tags. When I try to move one of the graphs to an external JavaScript file, I receive the following error message: "NS_ERROR_DOM_BAD_URI: Access to r ...

There is a hidden delete button obscured by another element. What steps can be taken to bring that element to the forefront and make it visible?

I'm having trouble positioning a delete button in the top right corner of a collapsible box. Despite setting it to `visibility: visible`, I can't seem to get it to display at the top of the collapsible element. Any suggestions or ideas would be g ...

The tooltip menu options in material ui are displaying in a different location in the window rather than below the button icon. How can this issue be resolved?

I'm having trouble implementing a tooltip on an option menu icon and it's not working as expected. Here is my code: export default function FadeMenu() { const [ anchorEl, setAnchorEl ] = React.useState(null) const bus = Bus() const o ...

Can I apply a universal babel configuration across all of my personal projects?

It becomes tedious to duplicate the same configuration file for each new project I start. ...

Is it beneficial to incorporate keys into an express instance for improved functionality?

If I want to pass information from my index.js file to multiple endpoints across different routes, is it sufficient to attach a custom key to the express instance (app)? For instance, if I am using socket.io and want multiple endpoints to emit from the i ...

Having issues with Sequelize and SQLite auto increment functionality. No errors when using AutoIncrement, but the auto increment feature is not working. On the other hand, errors arise when using

I am currently in the process of developing a discord bot, which includes 2 slash commands. One command is called /setup, used for adding the guildId and an adminChannel to a database. The other command is named /onduty, which is used for adding the user, ...

Parsley JS: A Solution for Distinct IDs

I have a form that contains multiple select boxes, and I need to ensure that no two select boxes have the same value selected. In simpler terms, if select box 1 is set to value 2 and select box 4 is also set to value 2, an error should be triggered. While ...

Why am I encountering this export issue while attempting to integrate a NextAuth.js Provider with Next.js?

Embarking on my first project in React/Next.js, I opted to employ NextAuth.js for authentication. Following the initial steps outlined in the Getting Started guide provided by NextAuth, I have successfully set up a [...nextauth].js page featuring the code ...

What methods can a controller use to verify the legitimacy of the scope?

I'm a bit perplexed when it comes to validation in angular. It seems like all of the validation is connected to the form. But what happens when the controller needs to ascertain if the model is valid or not? Here's an example I quickly whipped u ...

Prevent specific fields from being saved in Node MongoDB native

When working with MongoDB and using the node mongodb native driver to insert documents, I have encountered an issue. The objects I am inserting have fields that I do not want to be saved in the database: var x = { field: 'value', _nonPersist ...

What is the best way to send the value from a textbox to this script?

My challenge is with this particular textbox: <input type="text" autocomplete="off" required="required" id="bar" name="bar" class="form-control" placeholder="Barcode"> Also, there's a button in the mix: <button type="button" style="float:r ...