Automatically focus on input when scrolling reaches a specific element using jQuery

I have been utilizing a jQuery plugin called Waypoints to handle scroll actions.

My goal is to focus on the first input element of a section that is currently visible on the screen and then shift the focus to the input of the next respective sections as the user scrolls down. If the user scrolls back up to the first section, the focus should return to the input of that section.

Below is the code snippet from my working setup using the mentioned plugin. I have been unable to replicate the functionality in my JS Fiddle.

While this code successfully sets focus on page load and shifts focus to the targeted input when scrolling down, it does not return focus to the top section when scrolling back up.

(function($) {

var firstInput = $('section').find('input[type=text]').filter(':visible:first');

if (firstInput != null) {
    firstInput.focus();
}

$('section').waypoint(function () {
    var getFocus = $(this).find('input[type=text]').filter(':visible:first');
    getFocus.focus();
});

$('section').waypoint(function () {
    var getFocus = $(this).find('input[type=text]').filter(':visible:first');
    getFocus.focus();
}, {
    offset: function () {
        return -$(this).height();
    }
});

});

Here is the link to my JS Fiddle without the plugin implementation.

If anyone can provide guidance on how to achieve this using standard jQuery methods rather than relying on this specific plugin, it would be greatly appreciated.

Answer №1

Utilizing jQuery Waypoints is a breeze. While I haven't tested it with your specific code, I achieved the desired outcome using the following approach:

$('input:first').focus();

$('section').waypoint(function() {
    $(this).find('input:first').focus();
});

Take a look at this example.

One issue encountered when scrolling down using the mousewheel is that the scroll occasionally resets to the middle part. This behavior may be related to how the browser handles input focus. While I haven't thoroughly reviewed the documentation, it seems there are no specific examples addressing input focus.


If your goal is solely to accomplish this simple task, considering bypassing the plugin. I can demonstrate how to achieve the same result using jQuery alone.

You can manage scrolling using jQuery's scroll() function. By obtaining the scrollTop() during scrolling events, you can then compare it to the top offset() of the <input> element.

$(window).scroll(function(){
    var st = $(this).scrollTop();
    $('input[type=text]').each(function(){
        var offset = $(this).offset();

        if(st >= offset.top -20 && st < offset.top + $(this).height()){
            $(this).focus();  
        } 
    });  
});

View this demonstration.

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

Is it possible to have numerous HTML files and directories in Phonegap/Cordova along with plugins?

As I transform my web app from HTML to Cordova for enhanced device functionality, including background audio and other features, I'm encountering some challenges. Due to the original structure of my application, which consists of multiple HTML files, ...

There seems to be a problem with the JavaScript function as the indexOf property is undefined

function filteredArray(arr, elem) { let newArr = []; Iterating through each element of the multidimensional array. for (let i=0;i<arr.length;i++){ for (let j=0;j<arr[i].length;j++){ If the value matches the argument passed, assi ...

Is there a way to verify whether a user is currently logged in? (Using everyauth in node.js)

Previously, I relied on client-side auth for my application. Recently, I integrated server-side everyauth and it's functioning well. However, I'm unsure how to perform a function similar to FB.getLoginStatus (which I used in the client-side) when ...

Utilize Mongo's $facet feature to retrieve and calculate the number of tags associated with the products that have been

My current aggregation pipeline looks like this: aggregate.lookup({ from: 'tags', localField: 'tags', foreignField: '_id', as: 'tags' }); aggregate.match({ productType: 'prod ...

Looking to tally up the variety of items in Django?

Before, I had a table with a client summary list. One column showed object types and the other displayed the quantity of each object type. @login_required def client_summary(request, client_id): client = models.Client.objects.get(pk = client_id) i ...

Trouble accessing webpage on Apple devices

I recently created a website using Django and Bootstrap 5. Everything seems to be working perfectly as intended, except for when it is viewed on older iPhone models such as 6 or 7. The gifs and pictures that are dynamically fetched from the DjangoDB do not ...

What methods can be used to enable automatic data updating in angular.js?

What is the correct way to update the view when new data is created on the server? Here is my controller code: app.controller('MainController', ['$scope', 'games', function($scope, games) { games.success(function(data) { ...

Halt execution of routes using backbone.js

Is it feasible to halt route execution within backbone.js solely using the router? I understand there is a callback function for each route where I could verify if routing is permitted, but I am unsure how to prevent execution based on a property (such as ...

Is it possible to update the .reduce() method in React similar to how useState() is

Currently, I am immersed in a small project focusing on the "Cart" feature. The only missing piece of the puzzle at this point is calculating the total price for each product. I've managed to calculate it, but when adding multiple units of a single p ...

Determine whether the input fields contain specific text

I'm currently working on a script that checks if the user input in an email field contains specific text. It's almost there, but it only detects exact matches instead of partial matches. If the user enters anything before the text I'm trying ...

Jade: Incorporating a JavaScript file at a specific location

Is there a way to include a file that is specifically used when rendering a jade file on the client side? Here is an example of the .jade file: button(type="button")#start.flex p#timer.flex button(type="button" )#stop.flex script(src='../public/js/ti ...

Web view that remains fixed regardless of resolution, compatible with both iPhone and iPhone4 devices

Looking to create a webview with one HTML and one CSS file that displays graphics at the same size, but in their native resolution. Currently, my webviews built for 320x480 appear sharp when scaled up (text and border-radius), but images are displayed at ...

What is the best method for obtaining the HTML content of a webpage from a different domain?

I'm in the process of creating a website where I have the requirement to retrieve the HTML content of a different site that is cross-domain. Upon researching, I came across YQL. However, I don't have much experience with YQl. Is it possible to ad ...

What is the best way to display the complete text or wrap a menu item in an Angular Material menu?

Is it possible to display the full text of a menu item instead of automatically converting it to ellipses or breaking the word? I've tried various CSS methods without success. Any suggestions? https://i.stack.imgur.com/3l7gE.png #html code <mat-m ...

What is the best way to increase the spacing between inline-block elements?

Just to clarify, I am not looking to delete space between inline-block elements - rather, I want to insert it. My goal is to create a grid of menu items that can accommodate 2, 3, or 4 items per row, and I hope to achieve this using media queries. Is the ...

Concealing a DIV element when the value is not applicable

I'm currently working on a website for a coffee shop product. On this site, each product has a coffee strength indicator that is determined by the database. The strength can be categorized as Strong, Medium, Weak, or n/a (for non-coffee products). If ...

Choose JSON information and modify it utilizing NODE.js with identical data

Feeling stuck.. I have a JSON file with some data and I need to manipulate it. Take a look at my JSON structure: [{ "method": "GET", "path": "/", "aliases": "", "name": "rootPath", "handler": "generatedApps/avion01/actions.HomeHandler" }, { "method": "GET ...

Analyzing string values in Cypress

When attempting to compare two values within a page and make an assertion, my goal is to retrieve the value of one text element and compare it with another value on the same page. While I find this process straightforward in Java/selenium, achieving the ...

What is the best way to extract data from a JSON object in JavaScript?

let result = JSON.parse(data.d); The current code doesn't seem to be working.. Here is the structure of my JSON object: [{"ItemId":1,"ItemName":"Sizzler"},{"ItemId":2,"ItemName":"Starter"},{"ItemId":3,"ItemName":"Salad"}] Any suggestions on how I ...

The useEffect hook is failing to trigger

Currently, I am attempting to retrieve data from an API using Redux for state management. Despite trying to dispatch the action within the useEffect hook, it does not seem to be functioning properly. I suspect that the issue lies with the dependencies, but ...