Changing the background color of a fixed header in AngularJS based on the current page

I designed my homepage with a full-height div featuring a video. The header is fixed in position and has a transparent background with white text when positioned over the video. As I scroll down, I dynamically adjust the background to white with black text based on the window height.

Here is how my current header configuration looks:

<header id="masthead" class="site-header onVideo" role="banner" menuscript>

When I scroll, the "onVideo" class gets removed like so:

app.directive('menuscript', function ($window, $timeout) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs){
            var w = angular.element($window);

            w.bind('scroll', function(){
                if (w.scrollTop() < w.height() - $('#masthead').height()) {
                    $('#masthead').addClass("onVideo");
                }else{
                    $('#masthead').removeClass("onVideo");
                }
            });
        }
    }
});

Although this setup works well for the homepage, I am facing challenges when clients navigate to other pages without videos. These pages should have a header with a white background and black text without the "onVideo" class. Additionally, scrolling should be disabled on these pages. Once users return to the homepage, the original functionality should resume.

I'm struggling to find a solution to handle these scenario transitions smoothly.

@TL;DR; I need assistance in removing a class from the header and unbinding the scroll event when users switch routes. A check should be performed to determine if the destination page is the homepage. If it is, the class should be added back and the scroll event reactivated. If not, the header should remain unchanged and scrolling disabled.

Answer №1

If you take a glance at this AngularJS documentation regarding the $route service, you will find that you can leverage $routeChangeStart event like so:

$rootScope.$on('$routeChangeStart', function(evt, next, current) {
  if (next) {
    if (next.templateUrl === 'home.html') {
      $rootScope.showVideo = true;
    } else{
      $rootScope.showVideo = false;
    }
  }
}

This functionality allows you to track when users are navigating between pages. By determining the destination page, you can adjust variables on your $rootScope which can then be utilized in your header controller to control the display of videos and other elements.

For illustration purposes:

angular.module('myApp')
  .controller('CtrlHeader', function CtrlHeader($log, $rootScope, $scope) {

    $scope.showVideo = $routeScope.showVideo;
  });

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

Utilize jQuery to append YQL output in JSON format to specific IDs in your code

I have a YQL output JSON string at this URL: Check out the YQL JSON here I encountered some other I am exploring why I am facing difficulties in extracting certain items from the returned JSON. For instance, when using jQuery to access the H1 tag within ...

What is the best approach for maximizing user experience: setting a maximum screen width or allowing for auto-width?

I manage a blog with responsive design that adjusts to the width of the screen. The majority of our blog posts consist of lengthy content, often reaching over 1000 words, along with user comments. My main concern is about the reading comfort and usability ...

What could be causing the error message 'Alias configuration for Field browser is not valid' to appear when attempting to compile SCSS using Webpack through the terminal?

Recently, I decided to try using webpack to compile my scss files for the first time. However, when attempting to start it, I encountered an error message stating: Field 'browser' doesn't contain a valid alias configuration In addition, ano ...

JavaScript horizontal slider designed for a seamless user experience

Currently, I am in the process of developing a slideshow that includes thumbnails. While my slideshow is functional, I am facing an issue with limited space to display all thumbnails horizontally. I am considering implementing a horizontal slider for the t ...

Tips on choosing a child element with a parameter in React

Is it possible to pass a parameter in my function and use it to select a child of my JSON parse? I want to create a function (checkMatch) that can check if a username in my database matches with the input value. It should return 1 if there is a match, oth ...

Centering Multiple Lines of Items in an Unordered List with Horizontal Alignment

Looking for a solution to center an unordered list horizontally within the containing UL, especially when the list wraps onto a second line. Each LI has a set width and height. I've tried various methods that work for a single line but have had no luc ...

What is the best way to ensure that an element remains active even after a page refresh?

I have been using this code to activate the current element, which I came across on a website called "w3schools.com". However, whenever I refresh the page, the currently active element disappears. Is there a way to ensure that the active element remains hi ...

Animations and transitions for cards

import Section from '@/components/section' import {Card, CardHeader, CardBody, CardFooter, Divider, Link, Image, Button} from "@nextui-org/react"; import { CSSProperties, useState } from 'react'; const Index = () => { c ...

Setting the CSS position to fixed for a dynamically generated canvas using JavaScript

My goal is to fix the position style of the canvas using JavaScript in order to eliminate scroll bars. Interestingly, I can easily change the style using Chrome Inspector with no issues, but when it comes to implementing it through JS, I face difficulties. ...

Initiate a click on a radio button while also retaining the selected option when the page is

This is a unique question. In my scenario, there are two radio buttons: "radio1" and "radio2." I have successfully implemented the following actions individually: Automatically triggering a click on "radio1" upon page load. This ensures that the button ...

Resource file for locating the mappings

As a beginner in sourcemapping, I have been tasked with saving the sourcemap in an external file. However, up to this point, I have only been able to concatenate the sourcemap to the minified .js file. What changes should I make to my approach? Am I miss ...

Using JavaScript and Tampermonkey to convert strings from an HTML element into an array

I am trying to change the names of months into numbers and place them in a table cell on a website. I thought using an array would make it easier to reference the month names by their corresponding array numbers, allowing me to add table tags before and af ...

Applying unique textures to individual sides in Three.js

Here is the code for my textured cube: const textureLoader: TextureLoader = new TextureLoader(); const textureArray: MeshBasicMaterial[] = [ new MeshBasicMaterial({ map: textureLoader.load("./model/front.jpeg") }), new MeshBasicMaterial({ map ...

Dynamic form in Ant Design React for calculating total

In my Ant Design dynamic form, I have the capability to input both price and quantity in various rows. I can easily add new rows to the form. Upon submission, I was able to retrieve all the values from the rows using the following code snippet: const o ...

Error encountered with Content Security Policy while utilizing react-stripe

I am currently in the process of developing a React application that incorporates Stripe payments utilizing the @stripe/react-stripe-js (version "^1.9.0") and @stripe/stripe-js (version "^1.32.0") npm packages. While the payments are functioning correctly, ...

Solving templateUrl resolution of directives in Angular with RequireJS

Currently, I am using AngularJS and RequireJS in my single-page application (SPA). To organize imports efficiently, I rely on RequireJS. With RequireJS, I can utilize features like baseUrl to resolve import paths seamlessly. Now, I wish to apply the same r ...

Obtain the total by adding values from additional radio buttons selected

Need assistance with summing values from multiple radio inputs dynamically. Want to calculate the total price ('$res' variable) after checking them. Despite trying to change 'settype' to int, it didn't work out as expected. Any hel ...

What is the best way to incorporate the ion scroll directive into a div element?

I am currently working on implementing this example in the Ionic framework. I have been using the following code snippet from this link: http://plnkr.co/edit/LjAoAPFDx0eVPkx3dKfu?p=preview. The problem I am facing is that even though there are only six ele ...

Enhancing File Upload functionality with Struts 2 and jQuery

As a newbie to Struts2, I am attempting to upload a file in Struts 2 using the Struts2 jQuery plugin. My goal is to avoid page refresh during the file upload process. I understand that Struts 2 jQuery is supposed to facilitate AJAX requests to the action w ...

Can CSS be used to generate these shadows?

Check out this image I made showcasing a board with an elongated shadow cast behind it. The intention is to emulate the look of the board leaning against a wall, resulting in a triangular shadow on either side. I'm curious if it's achievable to ...