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

Transferring data between JavaScript and PHP

Is there a way to transfer data from JavaScript to PHP when a button is clicked? For instance, can the getdate() function's result be sent to PHP? This transferred value will then be utilized for database manipulation. ...

Solving the issue of localizing the Datetime picker

My date input seems to be saving incorrectly in the database. When I enter a date like 18/02/2020, it gets saved as 17/02/2020 22:00:00. Is this a time zone issue? How can I fix this problem and thank you. Also, if I want to save the date with UTC, how do ...

How to dynamically display a div in Vue.js depending on the attributes of another element

I have a dilemma with my text container. My goal is to collapse the div if the text length exceeds a certain limit, and then display a button that says "...show more". When this button is clicked, the div should expand. Clicking it again should collapse th ...

Chrome and Internet Explorer are not prompting to save passwords after the input type has been altered by a script

I've encountered an issue with a form that includes: <input type="password" id="password" /> I want to display some readable text temporarily, so I used the following code: $('#password').prop('type', 'text'); ...

What is the best way to transfer a file from Postman to a Node.js server using Multer?

Windows Express version 4.12.4 Multer version 1.0.1 Node version v0.10.22 I'm currently working on sending a file to my node.js server using Postman. I'm following the instructions provided in the readme here This is what I am sending wi ...

Using jQuery to loop through a table and retrieve the button value from every row

I have a challenge with dynamically created buttons in a table. My goal is to loop through the table, identify the rows that have a checked checkbox, and retrieve the value of a button within that row. I then need to store these values in an array. Unfortu ...

Creating default values for MongoDB databases using bdhash in Express.js and mongoose asynchronously

What is the best way to set a default value (like bdhash which is async) for a field in my mongoose schema? Currently, I am only seeing a promise inside. I'm using async/await correctly, but why does it seem like I'm getting just a promise? I als ...

Bringing the Jquery cursor into focus following the addition of an emoji

Looking to add emojis in a contenteditable div but facing an issue with the cursor placement. Here is a DEMO created on codepen.io. The demo includes a tree emoji example where clicking on the emoji adds it to the #text contenteditable div. However, after ...

Is it acceptable to compare a boolean with a string?

In my code, I have a variable called isRefreshed which is initially declared like this: var isRefreshed = ''; Sometimes, in certain scenarios, isRefreshed can be assigned a boolean value, for example: isRefreshed = false; Now, there is an if ...

Having trouble with table sorting in Jquery?

I am a beginner in the realm of Jquery and web programming. Recently, I attempted to implement the tablesorter jquery plugin for one of my projects but encountered issues with making it work properly. In search of a solution, I turned to Stack Overflow. C ...

Maximizing the potential of Bootstrap slider within OpenCart

Has anyone attempted to use Bootstrap slide with the Opencart slideshow module? Here is my code, but I am getting all active classes. Can someone please help me with this? <div id="carousel-example-generic" class="carousel slide" data-ride="carousel"& ...

Ways to verify an iCheck located on the following page

Here is the code snippet I am currently working with: $("#add-new-size-grp").click( function (event) { event.preventDefault(); $.ajax({ type: "get", url:"ajax-get-sizes.php", success: function(result){ $("#sizeg ...

Loading Images in Advance with jQuery, Native JavaScript, and CSS

After successfully implementing a method to hover on a small image and load an additional image to the right side of the page, I am now looking to enhance user experience by preloading images. Is there a way to preload an image using JQuery, allowing it t ...

How to share information between ES6 classes?

Recently, I decided to create a node/express app just for fun. One of the components I built is an ES6 class called 'TwitterClient.es6' that interfaces with the Twitter API to fetch data. Now, in my 'server.es6', which handles the route ...

What is the method for aligning text to the right side within a ListItem?

Currently, I have these elements where the "YoYo" text is aligned to the left by default. However, I am looking to adjust the positioning of some "YoYo" texts so that they can appear on the right side. I attempted to provide a style object with justifyCon ...

Ways to create an object based on another object

Currently, I am teaching myself Javascript. My focus is on working with Vuejs and express for a CRUD App. In one of my components, I retrieve data from my backend using the API: localhost:3000/api/transport. The response contains all objects from the data ...

What is the method for assigning a string to module variable definitions?

As someone new to TypeScript and MVC, I find myself unsure if I am even asking the right questions. I have multiple TypeScript files with identical functionality that are used across various search screens. My goal is to consolidate these into a single fil ...

I am struggling to make my table adapt to different screen sizes and become

Here is an example of a table: <TABLE class=vysledky > <TR class=podtrzeni> <TD width="39" height="19">Order <br /> League</TD> <TD width="39" height="19">Order <br /> Team</TD> <TD width="3 ...

Here is a way to return a 400 response in `express.js` when the JSON request body is invalid

How can I make my application send a response with status code 400 instead of throwing an error if the request body contains invalid JSON? import express from 'express' app.use(express.urlencoded({ extended: false })) app.use(express.json()) ...

Using HTML and CSS to create a Contact Form

Greetings! I have come across this contact form code: /* Custom Contact Form Styling */ input[type=text], [type=email], select, textarea { width: 100%; padding: 12px; border: 1px solid #555; margin-top: 6px; margin-bottom: 16px; resize: v ...