Can the .scroll function be turned off when a user clicks on an anchor link that causes the page to scroll?

I am currently developing a timeline page and I want to implement a feature similar to the chronological list of years displayed on the right side of this webpage:

As part of this feature, I have set up a click event which adds a circle border around the selected date and removes it when another date is chosen. Additionally, using this viewport plugin, the page is configured to show the circle border around the year/date that is currently visible on the screen.

However, I am encountering an issue where clicking on a specific year triggers the scroll function, causing the circle border to appear and disappear for each year in the list until reaching the desired year. Essentially, the click action is also initiating the scroll function.

My objective is to prevent the scroll function from triggering when a user clicks on a year, and then resume once the page has scrolled to the correct position. Any suggestions or recommendations on how to achieve this would be highly appreciated!

Below is the script for the scroll function:

        $(window).scroll(function (){
            if($("#intro:in-viewport").length > 0){
                $('.tNavIntro').css({border: '2px solid #50b855'});
                $('.tNav2012').css({border: ''});
            }

            // Other conditions for different years go here...

        });

And here is the click function:

  $('.timeLineNavWrap div').on('click', function(){
        $('div.selected').removeClass('selected');
        $(this).addClass('selected');
    });

Lastly, I added the following line of code as a workaround to remove the #links from anchors in the URL when a link is clicked:

$(document).ready(function(){
    $('.link').on('click',function (e) {
        $('html, body').stop().animate({
            'scrollTop': $($(this).attr('rel')).offset().top
        }, 900, 'swing', function () {
            clicked = false;
        });
    });
});

Answer №1

To manage the clicking functionality, you can create a global state variable in your click function that tracks whether the user has clicked or not. If a click is detected, you can temporarily disable the scroll function by wrapping it within an if (!clicked) statement. Remember to reset the variable to false once the click action is completed and manually trigger the scroll function.

Here's how you can implement this in your code:

var clicked = false;
$('.timeLineNavWrap div').on('click', function(){
    clicked = true;
    $('div.selected').removeClass('selected');
    $(this).addClass('selected');
    // Additional code for scrolling may be added here
    clicked = false;
    $(window).scroll();
});

$(window).scroll(function (){
    if (!clicked) {
        if($("#intro:in-viewport").length > 0){
            $('.tNavIntro').css({border: '2px solid #50b855'});
            $('.tNav2012').css({border: ''});
        }
        // Add more conditions as needed
    }
});

Answer №2

If you want to remove a scroll event listener using jQuery, you can utilize the .off() function.

Let's say that your button for removing the scroll event is labeled as .button.

 $('#button').on('click', function(){
        $(window).off('scroll');
 });

Once you have removed the scroll handler, you can then reinitialize it at the desired location (it's recommended to wrap the initialization in a function).

To retrieve the current scroll position, you can use the following code:

$(window).on("scroll", function(){
    console.log($(document).scrollTop())
})

You can determine the position of an element on the page with the .offset() method, specifically by accessing the top property within the returned object.

$("#button").offset().top

After obtaining these values, you simply need to compare them within a function linked to the scroll event on the window.

Does this explanation make things clearer for you?

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

Receiving null value with Web API POST using [FromBody]

Below is the code for my WebAPI in C#: [Route("")] [HttpPost] public void SaveTestRun([FromBody] object data) { inputResultsToDatabase(data); } This is the ajax request I am making: sendTestData() { t ...

What is the best way to format dates in jQuery AJAX requests?

Utilizing jquery to interact with a REST API in (ASP.net Web API). I've constructed a basic object and then utilized jquery to 'PUT' it on the server: var myObject = { name: 'just a name', createDate: new Date() } $.ajax({ ...

What could be causing the lack of data with 'react-hook-form'?

I have encountered an issue while working with react-native and using 'react-hook-forms' for creating dynamic forms. The problem is that the data object returned is empty, even though it should contain the values entered in the input fields. When ...

Submitting a form using only input buttons to transfer parameters to an Action in ASP.NET Core

Currently, I am working on my thesis and developing a simple browser game. My project involves having a form with three buttons that need to trigger the same action with different parameters. Here is what I have come up with so far: @using (Html.BeginForm ...

Which kinds of data are ideal for storage within the Vuex (Flux) pattern?

Currently delving into the world of Vuex for the first time as I develop an application in Vue.js. The complexity of this project requires a singleton storage object that is shared across all components. While Vuex appears to be a suitable solution, I am s ...

What is the best way to exclude the bottom four rows when sorting with MatSort?

Is there a way for me to keep the last four rows fixed when sorting the table based on the column header? Here is an image of the table: table image <table mat-table [dataSource]="dataSourceMD" matSort (matSortChange)="getRowMaximoTable( ...

How about "Temporary and localized responses with Discord.JS?"

Recently, I've been diving into the world of localization on my Discord Bot and had a thought. Localization allows you to tailor replies in different languages based on the user's language settings. For example, take a look at this code snippet ...

Show basic HTML elements on a single page of an Angular Material web application

I am working on an Angular (6) web app with a customized theme using Angular Material. Currently, I am trying to incorporate a popup dialog that includes basic HTML elements like checkboxes, buttons, and inputs. Even though I have successfully displayed ...

Is it advisable to run this function asynchronously on the server?

I have limited experience with node js, but I am working on a project similar to how Uber shows their cars in real time on a map. Currently, I have an SQL database containing data for numerous cars along with their GPS locations. The client sends their GP ...

The requested Javascript function could not be found

I have the following JavaScript function that creates a button element with a click event attached to it. function Button(id, url, blockMsg){ var id = id; var url = url; var blockMsg = blockMsg; var message; this.getId = function(){ return id; }; th ...

Issue with accessing form in Angular 6 Reactive forms for custom validator functionality

I am facing an issue with creating a password validation for reactive forms in Angular. Every time I try to verify the password, I get a “Cannot read property 'get' of undefined” error in the console. I have tried different methods to access ...

Update DataTable 1.9 while preserving existing rows

I'm currently using dataTables js version 1.9 Periodically, an ajax call is made to the server to retrieve information that should be displayed in a table every 60 seconds or so. Although I can easily clear and repopulate the table like this: $(id) ...

What is the best way to retrieve a value from an asynchronous method in Node.js that is using promises and also calling another asynchronous method?

I have created two methods for verifying the availability of data in a database and storing the data. The methods are as follows: function IfUserExists(userId) { logger.info(`Checking If ${userId} exists`); return new Promise(resolve => { ...

The issue of duplicate CSS arising during the compilation of SASS into a single CSS file with G

Just getting started with Stack Overflow and Gulp (using version 3.9.1). My goal is to compile all of my scss files into a single css file for my website. Here's what I have in my gulpfile so far: var gulp = require('gulp'); var sass = requ ...

Executing ng-click to access outer controller from within nested ng-controllers

I'm exploring the potential of using angularjs to develop a dynamic page with the following capabilities: It starts off blank, except for a dropdownlist that automatically populates with various apps. Upon selecting an app from the list, relevant da ...

Renew the php blade foreach loop using jQuery to update data live

I have a foreach cycle in my HTML, and at one point, some data is posted from JavaScript. I would like to append it once it is added to the database. I need to find a way to refresh the foreach loop without reloading the entire page (I could simply use ap ...

Is the presence of a 'disabled' attribute on a non-input element enough to render your document invalid in HTML?

Originally intended for <input/> elements, the disabled attribute raises a question when applied to non-input elements. Could this potentially lead to document invalidation? ...

AJAX: Bringing in new content to display beneath the triggering page

Here is the code for my main page: <head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <style type="text/css"> div { width:100%; ...

Iterating through the sorted list in reverse order, retrieving the text of each list item

Is there a way to navigate through an ordered list, extract and return the text based on a scenario where the user clicks on an li element like Cat 1-2? The goal is to concatenate all parent li's text into either a string or an array. If an array is u ...

Utilize a single CDN or multiple CDNs to access and retrieve files

When I visit a standard webpage, I usually load the following resources from various CDNs: jQuery Angular Bootstrap Icomoon several Angular plugins Would it be more efficient to load all these resources from a single CDN, or is it fine to use multiple ...