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

How come my wrapper box doesn't extend to the full width of the screen when I set it to width: 100%?

Can someone explain why my wrapper box doesn't fill the whole screen when I use width: 100%, but it does when I use width: 100vw? I have set "width=device-width" on my page and the minimum width for the page is 1400px. Thank you all for your assistan ...

I am working on a NodeJs code that utilizes (Array)Buffers and native readUInt16BE. However, since I am working within a browser context, I plan to opt for DataView.getUint16 instead

While working on adapting a JPEG parsing function in Node.js for use in a browser environment, I discovered that the original code can be found here. The challenge lies in using Node.js' Buffer class. To make it compatible with a browser environment, ...

The current status of an ASP.Net Mvc Ajax request

Currently, I am utilizing @Ajax.ActionLink to invoke a controller action in an ajax manner. Is there a method to identify if there is already an ongoing/pending ajax request on the page? The desired functionality is simple: when a user clicks the link, the ...

Border utilities in Bootstrap 4 provide easy ways to add borders

I have been searching for a solution, but I can't seem to find it. Bootstrap 4 offers utility classes for adding and removing borders, but is there a way to define the border width or style like solid or dashed? <span class="border"></span&g ...

Puppeteer is unable to detect the node.js handlebars helpers

I'm utilizing puppeteer in NodeJs to generate a PDF file. I use handlebars to render the template and pass variables during compilation for handlebars to access them. Here is the current code snippet: const browser = await puppeteer.launch({ he ...

Creating packing features specifically designed for resolution within a reusable module

I've decided to revamp my Angular application based on John Papa's style guide (well, mostly) and my main focus is on improving modularity. The stumbling block I've encountered is with route resolves. So far, I've been using a global ap ...

Encountering an error message stating 'click' property is undefined when implementing Java Script Executor in Selenium

I encountered an issue: Cannot read property 'click' of undefined when attempting to click a button using JavaScript executor. Despite trying multiple approaches such as action classes and WebDriverWait, I have been unable to successfully click ...

Configuring Chart.js in Laravel to Initialize with Value of Zero

I'm struggling to set my Chart.js chart to zero in my Laravel project. Could someone please help me with this? $chartjs = app()->chartjs ->name('lineChartTest') ->type('bar') ->size(['width' => ...

The button functionality gets hindered within the Bootstrap well

I'm trying to figure out what's wrong with my code. Here is the code: https://jsfiddle.net/8rhscamn/ <div class="well"> <div class="row text-center"> <div class="col-sm-1">& ...

Consolidate HTML project into a unified HTML file

In my current project, I am working with a static HTML report that is organized in the structure outlined below: 1.css 2.font 3.js 4.pages 5.attachments 6.index.html I would like to know how I can combine all these elements to create a unified 'repor ...

Tips for circumventing CORS in an ajax request using various browser extensions or add-ons

I am encountering a cross-origin problem with my WCF service. Despite adding an extension in chrome to bypass CORS, the issue persists. Is there any other extension/add-on/plugin available to test the service locally and bypass the CORS problem? Edit Aft ...

When I click on a tab section to expand it, the carat arrows all point upwards. Only the arrows corresponding to the selected section should

click here for imageIt appears that there are four tabs, each with a click function on the carat icon. When I expand one tab, all carats point upwards instead of only the selected one appearing. accountSelection(account) { if (!this.selectedAccoun ...

Jquery code not responding to ajax callback

i have the following two functions defined: function populateTableData(){ jQuery('select[name="drg-select"]').change(function() { drgValue=jQuery(this).val(); url="http://localhost/ur ...

How to have multiple versions of grunt coexisting on a single machine

I am involved in two different projects that have unique requirements for Grunt versions: Project A specifically needs Grunt v0.3.2 Project B requires Grunt v0.4.1 Both of these projects are managed in separate workspaces. Currently, I have Grunt v0.4. ...

Adding event listener to a dynamically created video element

Could you provide any insight as to why I'm encountering an error message "Can't create event listener on null" when using the following code: var my; my.newVidObj = document.createElement('video'); my.newVidObj.src = "vid- ...

Transforming Lapton images into JPEG format on the fly

I have been working on a project where I am compressing jpeg images to .lep format. Now, I have created an .exe file that can convert the .lep image back to jpeg. My goal is to write a simple JSP script that can decode the .lep image on-the-fly and displ ...

Creating a circular image with a vibrant color light effect that seamlessly runs across all browsers: What you need to know

Recently, I was working on a project involving this website that utilizes the Bootstrap framework. One interesting feature of the website is circle-shaped images that create a color light effect when hovered over. To achieve this, I decided to use the CSS ...

Angular Floating Panels: A Guide to Creating Dynamic User Interfaces

In the process of developing an angular app, I require a dock-able panel. After researching available controls online, I found them difficult to use and they compromised our screen layout. As a result, I am considering building a custom dock panel from s ...

Creating an expo apk using eas buildWould you like a tool for generating

Following an update to Expo, the process of building apk files using expo build:android -t apk is no longer supported. Instead, it now recommends using eas builds with the command eas build -p android --profile preview. However, this resulted in building a ...

Revamping an npm package on GitHub

Currently, I am managing a project that has gained popularity among users and has received contributions from multiple individuals. The next step I want to take is to convert the entire library into TypeScript, but I am unsure of the best approach to ach ...