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

Employ variables as a jQuery selector

let myLink = "#portfolio-link-" + data[i].pf_id; I am storing an ID in a variable. $("#pf-container-1").append(portfolio); console.log(myLink); $(myLink).append(function(){ $("<button class='btn btn-inverse' id='portfo ...

What are some ways we can enhance Map.get for react-router using ES6 Maps?

I recently implemented a map using new Map() to store my RR4 configuration within my application. My goal is to retrieve the values associated with /countries/:id when accessing /countries/1. routesMap.get('/countries/1') // should provide the ...

Is there a way to horizontally align the content in my footer section?

I am currently exploring React Material UI for the first time. The table I am working with can be found here under the "Custom pagination actions" section. Within this section, there is footer content containing buttons for rows per page, next, previous, ...

When using `npm publish`, any files located within the `node_modules

After developing an npm package, I included some modules in the node_modules directory to make them accessible as "modules". For instance, I have a module called my-module.js in node_modules which I require in my code using require('my-module'). ...

The Bootstrap dropdown feature is acting up when included in the header PHP file

I'm having an issue where the dropdown in my header.php file is not working when I include it in my home.php page. The navigation bar appears correctly, but the dropdown feature doesn't work. Can someone please assist me with this? Below are the ...

What causes the variance in outcomes between employing a literal string versus a local variable?

Here is a loop that I am working with: for (var key in criteria) { var exists = Object.keys(item).some(function(k) { return item[k] === "Test"; }) } Initially, this loop functions as expected and returns 15 trues based on the number of i ...

Differences between jQuery and Google Closure in terms of handling AJAX

Recently, I've been exploring the Google Closure Library for handling ajax calls. I came across an example that piqued my interest: goog.events.listen(request, "complete", function(){ if (request.isSuccess()) { // perform a cool action } els ...

Angular directive does not focus on the text box

I've been working on creating text boxes using a directive and I want only the first text box to be in focus. To achieve this, I am utilizing another directive for focus control. Below is my script: <script> angular.module('MyApp',[]) ...

Modifying the default error message in Yup: A step-by-step guide

What is the process for modifying the default error message to a custom error message? Specifically, my custom message. const VALIDATION_SCHEME = Yup.object().shape({ numOne: Yup.Number().required('!'), numTwo: Yup.Number() .r ...

On screens with smaller dimensions, the divs intersect with each other

I have a project where I need to style each letter in its own box, arranged next to each other or in multiple rows with spacing between them. Everything looks great until I resize the screen to a smaller size or check it on mobile - then the letters in the ...

Utilize a jQuery selector on the element that matches the hover event

Issue with the .add method on the final line where it is affecting all :first-child elements in the document instead of just the one being hovered over. Different attempts have been made to solve this, but so far no success has been achieved. jQuery.fn.im ...

It seems that Ionic 2 does not support the registration of custom HTML tags

Encountering a problem with Ionic 2 and custom components. Developed a component to show in a list, serving as the list item. However, my app crashes when attempting to use the custom HTML tag. The stack trace is provided below. Uncertain about the issue. ...

Trigger a JQuery selector when a click event occurs

I'm trying to set up an event trigger when clicking on a specific class within a div. Here's what I've attempted: $("div .event").click(function() { alert($( this ).text()); }); And also tried the following: $("div").on("click", $(&a ...

Arrange the keys of a map in ascending order, prioritizing special characters and their precedence

JavaScript ES6 Map Example: const map = new Map(); map.set('first', ['1', '2']); map.set('second', ['abc', 'def']); map.set('_third', []); map.set(')(*', []); map.set('he ...

Provide all information in a single entry rather than going through a list multiple times

My current process involves using AJAX to submit data to a script for updating my database. Although the process is usually straightforward, in this particular case, I have to iterate through a list of selectors to gather values when clicking the submit b ...

Discovering image file extensions in JavaScript using regular expressions

Can anyone provide me with a javascript regular expression to validate image file extensions? ...

Expanding the input focus to include the icon, allowing it to be clicked

Having trouble with my date picker component (v-date-picker) where I can't seem to get the icon, a Font Awesome Icon separate from the date-picker, to open the calendar on focus when clicked. I've attempted some solutions mentioned in this resour ...

Uploading a file to a URL using Node.js

Looking for a way to replicate the functionality of wget --post-file=foo.xpi http://localhost:8888/ in nodejs, while ensuring it's compatible across different platforms. In need of assistance to find a simple method for posting a zip file to a specif ...

Add a class by utilizing the :class attribute

I reviewed the documentation, but I am still struggling to implement this in my project. Initially, I simply want to display a specific class using vue.js that I can later modify dynamically. I just need to establish the default behavior of that class, so ...

Delaying the form submission with jQuery ajax

I am facing an issue with my jQuery AJAX code that automatically submits my form when it is changed. The problem arises when I have a country selection in the form, and clicking on an autocomplete suggestion results in the form being submitted with the o ...