Fading colored images and backgrounds using Javascript

Although js and html are not my strong points, I am attempting to create two simple effects on a single page.

As the user scrolls down the page, I want the background image or color to change as different divs come into view and then move off the screen.

The colors represented by the .panel class are working perfectly fine, but I'm having trouble with the background image specified in the .fadeimage class.

Here is an example of the HTML code:

<div class="fadeimage">
  <h2>image panel</h2>
</div>
<div class="panel" data-color="green">
  <h2>Indigo panel</h2>
</div>
<div class="panel" data-color="blue">
  <h2>Blue panel</h2>
</div>
<div class="fadeimage">
  <h2>image panel</h2>
</div>
<div class="panel" data-color="yellow">
  <h2>Yellow panel</h2>
</div>

Additionally, here is the CSS code snippet:

body {
  color: #000;
  background-color: #f4f4f4;
  transition: background-color 1s ease;  
}

.panel {
  min-height: 100vh;
}

.fadeimage {
  opacity: 0;
  transition: 0.3s;
  background-image: url("/New Page/images/testtakeall.jpg");
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

/* colours */
.color-blue {
  background-color: #2F8FED;
}
.color-green {
  background-color: #4DCF42;
}
.color-yellow {
  background-color: #FAEB33;
}

In terms of Javascript, there seems to be an issue with the implementation. The opacity of the divs with the class .fadeimage remains at 0 throughout.

Answer №1

To optimize your code, consider consolidating multiple scroll functions into one for better performance. Here's an example:

$(window).scroll(function () {
    // Include $fadeimage in the existing scroll function
    var $window = $(window),
      $body = $("body"),
      $panel = $(".panel"),
      $fadeimage = $(".fadeimage");

    var scroll = $window.scrollTop() + $window.height() / 3;

    $panel.each(function () {
      var $this = $(this);

      if ( $this.position().top <= scroll && $this.position().top + $this.height() > scroll ) {
        $body.removeClass(function (index, css) {
          return (css.match(/(^|\s)color-\S+/g) || []).join(" ");
        });

        $body.addClass("color-" + $(this).data("color"));
      }
    });

    $fadeimage.each(function () {
      var $this = $(this);

      if ( $this.position().top <= scroll && $this.position().top + $this.height() > scroll ) {
        $this.css("opacity", 1);
      } else {
        $this.css("opacity", 0);
      }
    });
}).scroll();

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

Adjust the content size to 100% based on the quantity of items in a row

I've been having a hard time creating an image gallery that adjusts its size automatically (width: 100%) based on the number of items it contains. For example, take a look at this gallery: http://codepen.io/anon/pen/eNMOEz .item { width: 75px; h ...

The sticky positioning in <table> element fails to function properly in Firefox as well as Chrome version 58

Visit the website Scroll down until you see the "The First 40 Elements" table. Continue scrolling to reach the end of the page. In Chrome version 57, the table header stays sticky, but in Chrome 58 it does not. Interestingly, the table header also does n ...

Update the ngView content on the fly

My project requires dynamic routes to be generated when specific URLs are requested in order to customize the view and display corresponding data uniformly. While adding manual routes with the same templateUrl and controller would have made this task simpl ...

Retrieving the real server response using Angular's $resource

I have developed an API using Laravel which provides JSON data in the following format: { "data":{ "errors":{ "username":"The username you entered has already been taken.", "email":"The email address provided is already in use." } ...

Vue.js component still not transitioning out despite using mode="out-in"

As I navigate my way through learning about vue.js, one issue that has been puzzling me is how to make routed pages fade in and out when a user switches to a new page. Despite thinking it would be a simple task with vue, I have been struggling quite a bit ...

React with TypeScript - Troubleshooting TS Error when Iterating over List Item (LI) Elements

Iterating through a group of <li> elements to strip away a specific class, then applying the same class to a different <li>. See the snippet below: useEffect(() => { if (dnArrowIdx === undefined) { const allLi = Array.from(document. ...

Error message: "When using selenium-webdriver in JavaScript, the findElement method for <a> tags cannot be used as a function."&

Seeking the website URL for brand information from this website, I attempted to retrieve it using JavaScript in the console: document.getElementById('phone_number').getElementsByTagName('a')[1].getAttribute('href') However, ...

Exploring the synergies between Angular Dragula and utilizing the $index property

Currently, I have implemented an ng-repeat of rows that can be rearranged using Angular Dragula. Despite successful drag-and-drop functionality, the $index in ng-repeat remains constant for each item even after reordering. The screenshot below depicts the ...

Is it possible to use JavaScript to append elements with a fade-in effect

I'm looking to add an element with a fade-in animation to another class using JavaScript. Can anyone provide guidance on how to achieve this? Here is what I've tried: success:function(data){ $(".new_posts").append(data); $(".new ...

Arranging the placement of an arrow within an HTML dropdown menu

I'm struggling with positioning my custom arrow in select elements. Each select has a different width, and I need to ensure that the distance from the right edge of the select to the arrow is consistent across all of them. Currently, I am using backg ...

Enhancing the pagination look and feel in Laravel 5.1

Is it possible to customize the paginator layout in Laravel 5.1? I am looking to include first and last links along with the default previous and next links. I would like to change the previous and next links to show icons instead of text, while still ma ...

.post method reveals parameter in URL upon submission

Currently, I am utilizing the $.post method to send a value to a PHP page for processing after replacing the serialize utility with a more specific element: $("button").click(function(event) { $.post( "php/index.php", { seq: $("seq").v ...

Running a JavaScript animation within an Electron environment

My curiosity lies in developing man-machine interfaces using Electron. Currently, I am experimenting with a Star Trek life signs monitor demo. I came across this code that can be easily customized to create vertical and horizontal movements: http://jsfiddl ...

Discover the secrets of extracting the ID from a MenuItem within a Menu

Table Ui with menu Struggling with fetching the correct user ID in the edit button The edit button for all users is only displaying the last user's ID If the edit button is not nested inside the Menu, it works fine. However, within the Menu, it onl ...

React.js - keeping old array intact while using array map

I am currently experiencing an issue where I have two arrays, and I need to map through one of the arrays when navigating the page. However, instead of replacing the old array with the new one, it is just keeping the old array and adding the new one. Here ...

We apologize, but the module you are looking for cannot be found: Unable to locate 'fs'

Trying to create a new MDX blog website using Next.js 13 with the latest app router, but encountering an error message saying "Module not found: Can't resolve 'fs'". It was working fine in Next.js 12 and pages directory, but not in the lates ...

Discrepancy in Angular Material Buttons with theme design

I recently installed Angular 10 along with Angular Materials using the command ng add @angular/material I opted for the custom theme: Purple/Green The next step was to add a Toolbar by simply copying and pasting code from Google's site. However, I a ...

When attempting to capture an element screenshot as PNG, a TypeError occurs indicating that the 'bytes' object is not callable

Can someone please help me figure out how to save a screenshot of a specific element in Selenium using Python3? Here is the code I am trying: from selenium import webdriver import pyautogui as pog import time options = webdriver.ChromeOptions() options ...

Encountering an issue: Unable to load resources - Server returned a status code of 500

Struggling with implementing ajax code in my app development. I've encountered an issue where the ajax code that works fine in the video tutorials I'm following doesn't seem to work for me. It's really frustrating! Here is a snippet of ...

jQuery - accessing a different class within the object

Let me explain the scenario: I have a website that will delve into 4 different subjects. Initially, I have 4 divs each representing the title of those subjects. For instance, <div><p> Physics </p></div> <div><p> Chem ...