When the condition fails to activate

I am encountering an issue with my code that involves an if statement checking the value of a variable and binding a mousewheel event based on its true or false value. The problem is, the if condition only triggers on load and not when the value changes to true.

Below is an example of the code inside the controller:

$scope.first = angular.element(document.querySelector('#first'));
$scope.second = angular.element(document.querySelector('#second'));

$scope.firstActive = true;
$scope.secondActive = false;

angular.element($window).bind("scroll", function () {
    var scrollTop = angular.element($window).scrollTop();
    var firstO = $scope.first.offset().top;
    var secondO = $scope.second.offset().top;

    var firstDistance = (scrollTop - firstO);
    var secondDistance = (scrollTop - secondO);

    if (firstDistance < 600) {
        $scope.firstActive = true;
        $scope.secondActive = false;             
    }

    if (secondDistance >= 0) {
        $scope.firstActive = false;
        $scope.secondActive = true;                
    }
});

if ($scope.secondActive) {
    html.css('overflowY', 'hidden');
    whatIDo.css('display', 'block');

    angular.element(whatIDo).bind("mousewheel", function (e) {
        if (e.originalEvent.wheelDelta < 0) {
            //scroll down
            console.log('Down');
            $scope.secondSlide = true;
            $scope.firstSlide = false;
            whatIDo.css('display', 'none');
            html.css('overflowY', 'auto');

        } else {
            //scroll up
            console.log('Up');
            $scope.secondSlide = false;
            $scope.firstSlide = true;
            whatIDo.css('display', 'none');
            html.css('overflowY', 'auto');

        }
        $scope.$apply();
    });
}

The goal is to trigger the mousewheel on an overlay to switch content between first slide and second slide, and then continue scrolling the page. However, despite setting the variable to true, the if statement is not triggering as expected.

Answer №1

Your code currently does not have anything that will activate the if statement, and the statement itself cannot detect changes in your secondActive property. To achieve this, you can utilize $scope.$watch:

This function registers a listener callback that will be triggered whenever the watchExpression changes.

$scope.$watch('secondActive', function() {
  alert('I can now perform any actions when the variable changes!');
  // Insert your if statement logic here
});

Answer №2

Develop a single function that includes the if statement code and invoke it from both onload and event listener.

$scope.first = angular.element(document.querySelector('#first'));
$scope.second = angular.element(document.querySelector('#second'));

$scope.firstActive = true;
$scope.secondActive = false;

angular.element($window).bind("scroll", function () {
        var scrollTop = $window.pageYOffset;
        var firstO = $scope.first.offset().top;
        var secondO = $scope.second.offset().top;

        var firstDistance = (scrollTop - firstO);
        var secondDistance = (scrollTop - secondO);

        if (firstDistance < 600) {
            $scope.firstActive = true;
            $scope.secondActive = false;             
        }

        if (secondDistance >= 0) {
            $scope.firstActive = false;
            $scope.secondActive = true;                
        }
       onChange();  // call on event
});

function onChange(){
       if ($scope.secondActive) {
        html.css('overflowY', 'hidden');
        whatIDo.css('display', 'block');

        angular.element(whatIDo).bind("mousewheel", function (e) {
            if (e.originalEvent.wheelDelta < 0) {
                //scroll down
                console.log('Down');
                $scope.secondSlide = true;
                $scope.firstSlide = false;
                whatIDo.css('display', 'none');
                html.css('overflowY', 'auto');

            } else {
                //scroll up
                console.log('Up');
                $scope.secondSlide = false;
                $scope.firstSlide = true;
                whatIDo.css('display', 'none');
                html.css('overflowY', 'auto');

            }
            $scope.$apply();
        });
    }
}
onChange(); // call on load

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

Using highlights in an external template does not function as expected

I am new to using AngularJS and I have encountered a problem. I am currently incorporating Prism.js or Highlight.js into my website (same result). It works perfectly in index.html, but it doesn't seem to work in other templates that are loaded with n ...

Retrieving a specific Project ID from Asana Task API using Node.js and parsing the JSON response

Utilizing the Asana Task API, we have the capability to retrieve a task's associated projects along with their GID and Notes (description text). The main objective Our aim is to extract the GID of the project containing #websiteprojecttemplate in its ...

Is there a way to display the drawer component from Material UI only on specific routes using routing in ReactJS with MaterialUI?

In my react project, I have implemented a material-UI drawer component. The issue I am facing is that the drawer component contains the page content within itself. Previously, I managed to integrate routes using react-router-dom with the drawer. My current ...

The challenge of Cross-Origin Resource Sharing with AjaxSubmit compared to a traditional Ajax request

My dilemma involves two applications interacting on Google's App Engine, each operating within its own domain. To enable communication between them, I have successfully implemented CORS in Python using the following code: self.response.headers.add_he ...

The Alphavantage was acting strangely when I ran a Google script

After following a tutorial video on YouTube, I was confident that my Google script for Google Sheets was working perfectly. However, I encountered two strange issues that I just can't seem to figure out. The code below is exactly what I need - it ...

Having trouble retrieving the value of a constant within an AngularJS service

Within my module, I have included a constant as shown below: var app = angular.module("myapp", ["ngRoute"]).constant("myConfig", { "url": "http://localhost", "port": "80" }); I attempted to retrieve the value of the constant in my service like this but I ...

Issue with setting HTML content using jQuery's .html() method

I have a simple functionality. When a user clicks on the edit link, it transforms the previous element into an input element for editing, and changes the edit link into a cancel link. If the user decides not to edit, they can click on cancel and everything ...

Guide on passing a variable from AJAX response to a JavaScript function when a user clicks

I need to send the value of a variable as a parameter to a javascript function when clicking on a link. The value is obtained from an AJAX response. However, I am encountering an error in the console stating that 'test' is not defined. var test ...

How to activate the menu in AngularJS

Within my application, I have a header that contains various menu items. These menu items are fetched from a service and displayed in the header. When hovering over the main list, the submenus appear. My goal is to highlight the parent item as active when ...

The Node.js POST request is unexpectedly returning 'undefined'

I'm currently working on a project for an online course and I'm encountering an issue with making an API call. It seems that I am getting undefined responses to my post request because the user input is not being retrieved properly. Below are the ...

Using the Restangular response with ng-repeat

Currently, I am delving into the world of angularjs with restangular to interact with my RESTful API (sails). However, I have run into an issue where the ng-repeat does not refresh after modifying the list in the scope. Here is the Controller: app.contro ...

What is the hierarchy of fields in package.json?

After submitting a pull request to a repository to include a typings field in the package.json file, the maintainer suggested the following modification: - "typings": "./src/index.d.ts", - "main": "./src/index.js" ...

Using react-hook-form for form submission and managing state in React

I want a button that toggles between displaying "Edit" for entering Edit mode and "Save" for submitting the form. However, the issue is that when I press the button while it shows "Edit," it submits the form. Link to codesandbox with the code provided be ...

Creating dynamic bar chart visuals using Morris.js with JSON responses

Utilizing the morris.js library, I am extracting and plotting bar charts from data retrieved through a webservice. Issue: The format of my webservice URL is as follows: http://localhost:9999/hellowebservice/search?select=* I populate the select query ...

Tips for utilizing JavaScript getElementByClassName to retrieve all the elements within a ul without having to specify the class name in each li

Looking to tidy up my HTML/CSS. Is there a way to keep this JavaScript functioning without needing to add the class name to every li element within the ul? Any suggestions on how to improve the visual appeal and readability of the HTML code? const Profi ...

How can I retrieve an attribute from another model in Ember using the current handlebar in the HTML file?

I'm attempting to achieve the following: {{#if model.user.isAdmin}} <div> My name is {{model.user.name}} </div> {{/if}} within a handlebar that is being used in a controller unrelated to users: <script type="text/x-handlebars" data- ...

Having trouble importing SVG as a React component in Next.js

I initially developed a project using create-react-app with Typescript, but later I was tasked with integrating next.js into it. Unfortunately, this caused some SVGs throughout the application to break. To resolve this issue, I implemented the following pa ...

Issue with AngularJS filter not functioning properly

I have a specific situation where I am using an ng-repeat directive in the following manner: {"ng-repeat" => "city in cities() | filter: search"} In this context, each city object is structured like so: { attributes: {name: 'Boston'} } Furt ...

JavaScript and Ajax are functioning properly in Mozilla Firefox, however there seem to be some compatibility issues with Google Chrome

I have a form that serves the dual purpose of registration and login, and I am using JavaScript Ajax to submit it. While it works smoothly in Mozilla Firefox, it fails in Chrome and IE. The goal is to execute an AJAX and PHP script that checks the databa ...

Exploring the Power of Promise-Tracker in AngularJS

Having trouble with promise-tracker implementation. I am trying to track a conversation using the code below: JS: angular.module('myModule', ['ajoslin.promise-tracker']) .factory('Conversation', function (promiseTracker) ...