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

Dynamic tooltips with jQuery: enhancing user experience through mouseover and

I seem to have encountered a problem with the functioning of my tooltip. Everything works fine, except when I move my cursor towards the right side, it tends to be faster than the tooltip itself and ends up hovering over it momentarily. This results in the ...

Error: The variable 'error' could not be located

Below is the code that I am using: $(document).ready(function(){ var callPage = function(){ $.post('/pageToCall.php'); }; setInterval('callPage()', 60000); }); However, I encountered an error stating ReferenceErro ...

Investigate the dynamic form validation using jQuery

I have set up an input field using jQuery. When the button "add a step" is clicked, jQuery will generate the following structure in the div all_steps: <div class="step"> <div class="header_step">Step '+ (x + 1) +' of the Tutoria ...

Transmit a PDF byte array from JavaScript to PHP using Ajax, then utilize the PHP file to send an email

I am facing a particular issue. Currently, I am utilizing the pdf-lib library for JavaScript to generate a PDF. The last step involves creating a uint8array: const pdfBytes = await pdfDoc.save() My goal is to transmit these pdfbytes via AJAX to a PHP fi ...

Renewed Promises: Exploring Promises in Angular JS

Revised with HTTP and initial code inspired by requests/Refer to the end of the post: Lately, I have been seeking help from the amazing SO community as I navigate through my AngularJS learning journey. I used to be a traditional C programmer but recently ...

npm ERROR: Unable to install the package named "<packageName>" because it conflicts with an existing package of the same name

Currently, I am attempting to incorporate the jsonfile package into my project. However, I am encountering a couple of errors: An issue arises when attempting to install a package with the same name as another package within the same directory. (Despite ...

Exploring the mechanics behind ES6 Map shims

From what I've gathered from the documentation (here and here), it seems that having a reference to the memory address is necessary for the operation to work: const foo = {}; const map = new Map(); map.set(foo,'123'); // This action requi ...

Challenges Encountered with AngularJS $http Service

How do I pass my data from the http request to the $scope in the MainCtrl? The code below should fetch data from a MySQL Database with an $http-service, but somehow the data provided by the service doesn't go to the controller or gets displayed incor ...

Adding code containing various Google Maps elements in a fresh browser window using JavaScript

I've encountered an issue while trying to create a new page with a Google map and title based on the button clicked. Interestingly, when I copy/paste the HTML in the "newhtml" variable into an actual HTML file, it works perfectly fine. However, it doe ...

Separate .env configurations tailored for development and production environments

Managing different content in my .env files is crucial as I work with both next.js and node.js. The settings vary between development and deployment environments. During development: DOMAIN_URL=https://localhost:3000 GOOGLE_CLIENT_ID='abc' For ...

Tips for retaining focus on the same control following an asynchronous postback

I am experiencing an issue with my 3 textboxes, where one is placed in an update panel that refreshes every 4 seconds. Unfortunately, during the refresh process, the focus on controls outside of the update panel is being lost. I need a solution to maintain ...

Embracing async-await while awaiting events in node.js

I am attempting to incorporate async await into a project that is event-driven, but encountering an error. The specific error message I am receiving is: tmpFile = await readFileAsync('tmp.png'); ^^^^^^^^^^^^^ SyntaxError: Unexpec ...

The operation of Ajax can be intermittent, as it may run at

I'm encountering an issue with my ajax code. I am adding data from my database and attempting to refresh a div element. It seems to work sometimes but not consistently. Why is that? Here's the problem - I have a function called addtoqueue. Insid ...

Ways to show dynamic text according to slider adjustments

I am struggling with adding an if condition to my form that includes a horizontal slider. My goal is to display text based on the position of the slider. Can someone offer some guidance on this, please? Here's my HTML code snippet: <form method=" ...

When using AngularJS and Laravel together, the CORS functionality may cause the POST request to halt after the preflight

Once upon a time, there was a bird who dreamt of joining the postal service but failed his preflight test... Using Laravel as a RESTful API and AngularJS/ionic for the app, everything was working smoothly until suddenly... it stopped. The withCredentials ...

Placing a Fresh Item into a Designated Slot within an Array

Imagine having a MongoDB collection that consists of an array of objects being retrieved from an Angular Resource. [{_id: "565ee3582b8981f015494cef", button: "", reference: "", text: "", title: "", …}, {_id: "565ee3582b8981f015494cf0", button: "", ref ...

HOC that can be used with many different components

My Higher-Order Component is currently designed to accept a single component, but I want to modify it to handle multiple components dynamically. Here's the current implementation: let VerticalSlider = (Component) => { return (props) => ( ...

Error with AngularJS: IE not showing dropdown options for MultiSelect

My application features a multiselect dropdown menu that shows a list of countries. While this dropdown functions correctly in Chrome, it displays options differently in IE as shown below: https://i.stack.imgur.com/xhOmV.png I have attempted to adjust th ...

Adding elements to a multi-dimensional array that match elements from another array

I am working with two arrays: a = [ [a, b], [c, d], [e, f], [g, h] ] b = [ [a, 4], [1, 2], [e, 3] ] My challenge lies in updating the elements of array a when they match corresponding elements in array b. Specifically, I need to add a new ...

Steps for comparing two inputs and displaying a div:1. Obtain the values of

I am looking to create a basic JavaScript function that will show or hide an element based on whether two input values match. This needs to happen before the form is submitted. <form> <input type="number" name="some1" id="some1"> <input t ...