Scroll the page only when the first radio button is clicked

After selecting a radio button with the ID "yourgoal", a div is displayed on my page. I want the page to scroll to that div only the first time a button in "yourgoal" is clicked. Below is the code I am currently using. However, I do not want the page to scroll to the div after the initial click.

$('input:radio[name="yourgoal"]').change(function() {
                 if ($('#calculations1').css('display') == 'none') {
                            $('html, body').animate({
                            scrollTop: $("#scrollto").offset().top
                            }, 1500);

                    }

The issue I'm facing is that it disrupts the other functions within the .change() method. I don't want to include all the functions inside the if statement and then duplicate them in an else {} block as it seems like too much repetitive code (which also causes issues). Is there a way to have a simple if statement that doesn't interfere with the rest of the actions in the .change function?

I might be overcomplicating this – perhaps there's a simpler solution?

Thank you in advance!

Answer №1

$('input:radio[name="yourgoal"]').one('change',
    function () {
        if ($('#calculations1').css('display') == 'none') {
            $('html, body').animate({
                scrollTop: $("#scrollto").offset().top
          }, 1500);
       }
    }
);

If you want the event to trigger only once and be automatically removed afterwards, using .one() is recommended.

To keep additional code that needs to stay after the first change event, you can use event namespacing and attach multiple change events.

$('input:radio[name="yourgoal"]').one('change.firstChange',
    function () {
        if ($('#calculations1').css('display') == 'none') {
            $('html, body').animate({
                scrollTop: $("#scrollto").offset().top
            }, 1500);
        }
    }
);
$('input:radio[name="yourgoal"]').on('change.allChanges',
    function () {
        // Additional code that stays attached
    }
);

It seems like using .one() won't work in this case because it will be attached to each radio button individually with the same name. If you only want to scroll upon the first selection of any radio button sharing the yourgoal name, you can implement it as shown below:

Fiddle: http://jsfiddle.net/31s3LLjL/3/

$('input:radio[name="yourgoal"]').on('change.firstChange',
    function () {
        $('input:radio[name="yourgoal"]').off('change.firstChange');
        $('html, body').animate({
            scrollTop: $("#scrollto").offset().top
        }, 1500);
    }
);
$('input:radio[name="yourgoal"]').on('change.allChanges',
    function () {
        // Other change actions
    }
);

Answer №2

If you want to prevent other callbacks from being executed on a specific event, you can utilize event.stopImmediatePropagation().

$('input:radio[name="yourgoal"]').one('change',function(event) {
  event.stopImmediatePropagation();
  if ($('#calculations1').css('display') == 'none') {
    $('html, body').animate({
      scrollTop: $("#scrollto").offset().top
    }, 1500);
  }
});

Just remember to ensure that your code comes before any other change handler definitions.

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

ensure that mocha does not consistently skip tests

When working with mocha, I include several unit tests that incorporate the skip it.skip('login (return photo)', function(done) { ... At times, I need to prevent skipping certain tests, such as right before a deployment. Is there a specific flag ...

Create a Bootstrap div containing a button that adjusts to different screen sizes on the

Struggling with an issue in Bootstrap on how to create an input group with responsive content and a button on the right side. I want the button to always be on the right side and also responsive. I attempted to achieve this with the code below, but it does ...

Ways to achieve outcomes from functions employing concatMap within rxjs?

When calling two functions, I make use of fn1 and fn2. To execute them one after the other, I utilize concatMap. I choose not to use exhaustMap and switchMap as they can result in nested "callback-hell". exhaustMap(() => fn1().pipe( swit ...

Why isn't this button aligning in the center properly?

I'm currently using Bootstrap V5 and trying to center the login button in the div. I've attempted using mx-auto and text-center, but so far, none of them seem to be working. Can anyone point out where I might be going wrong? <div class='c ...

Detecting page scrolling in Angular can be a challenging task

Having some issue with detecting scroll events in Angular. Here's the code snippet: @HostListener("window:scroll", []) onWindowScroll() { console.log("hello"); } Can anyone spot what I'm doing wrong? ...

Unable to properly shut the sliding-over modal

I have implemented a customized version of the codrops slide & push menu (http://tympanus.net/codrops/2013/04/17/slide-and-push-menus/) to create an overlay on my webpage. However, I am facing difficulty in closing it using another link. Any assistance on ...

Step-by-step tutorial for making a mesmerizing fade out grunge background

How can I achieve a fading grid background effect? I have experimented with using a conic-gradient for the background, but I am unsure how to make it fade out. background: conic-gradient(from 90deg at 1px 1px,#0000 90deg,grey 0) 0 0/50px 50px; ...

jQuery's visibility check function is not functioning properly

I am developing a web application for managing orders and finance in a restaurant. To enhance the functionality of my application, I require more screens to operate with. To facilitate this, I have implemented a small function to toggle between visibility: ...

My function won't get called when utilizing Angular

My Angular code is attempting to hide columns of a table using the function shouldHideColumn(). Despite my efforts, I am unable to bind my tags to the <th> and <td> elements. An error keeps popping up saying Can't bind to 'printerColu ...

Modifying the value of an HTML5 input type 'color' using JavaScript

In the image, there are pencil and eraser buttons. I would like the input value to change to black when the pencil button is clicked, and white when the eraser button is clicked. Here's what I've tried: <button onclick="$('#color-select& ...

Struggling with flipping div functionality in IE9 on flipping content demo

I recently developed a flipping div using transitions and 3D transforms based on the Flipping Content Demo 1 from . While this works smoothly on most browsers, unfortunately IE 9 does not support transitions and 3D transforms. In order to address this iss ...

The XMLHttpRequest's readystate gets stuck at 1 stage

Feeling a bit out of practice here - used to work with AJAX directly, but then spent a few years on a jQuery site and now my native JS skills are rusty. I've simplified my code as much as possible, but it's still not functioning: var rawfile = ...

Setting up Geolocation

I have been utilizing an APM tool for my work. The tool currently requires a pop-up in order to capture the user's location. However, there is now a need to capture the user's location without the pop-up appearing. Is there a method or workaroun ...

Access PDF files with parameters using ASP.NET MVC and AJAX technology

Currently, I am utilizing ASP.NET MVC and have created a controller that is able to return a PDF file. The PDF is constructed using PDFsharp: public ActionResult GenerateReport(string Param) { // Create a new PDF document PdfDocument document = n ...

Dynamic progress bar based on time remaining

Is it possible to create a progress bar that reflects the countdown timer displayed in a div? The timer counts down from 7 minutes and is shown as follows: <div id = "quiz-time-left"> 0:06:24 </ div> I want to ensure that if the page is reload ...

Errors in AJAX calls can sometimes result in an "ERR_EMPTY_RESPONSE" being

I'm currently working on a small CMS/Social network project for a school, which is quite complex and heavily relies on AJAX technology. Randomly, I encounter issues where calls are blocked and the browser displays an error message like net :: ERR_EMPT ...

Condensing an Array of Objects into a solitary result

Hey there, I'm currently exploring the most efficient method to accomplish a task. The data I am dealing with looks something like this: [ { name: 'email.delivered', programme: 'Email One', timestamp: 2022-03-24T18: ...

Jquery UI sortable not detecting changes in attributes of list items

Currently, I am dealing with a list that has both selectable (via checkboxes) and sortable (using jQuery 'sortable') items. The structure of the list is as follows: <ul id="dragdrop"> <li id="1290"><input type="checkbox" id=" ...

Issue with directive not activating when attribute is changed

I am facing an issue with my website where users can make selections from two dropdowns, and based on those values, attributes are sent to directives for a corresponding function to be called. The problem I'm encountering is that the directives are n ...

What is the best way to set an object's value to null in AngularJS?

Check out this code snippet var data={}; data={stdId:"101"}; data={empId:"102"}; data={deptId:"201"}; In my project, I'm receiving data from services into a data object with differing key names such as stdId or empId, etc. I need to set empty val ...