Navigate through elements in jQuery by scrolling both up and down

Is there a way to create a scroll function similar to WhatsApp's search feature?

When the user clicks on the search (located at the bottom), I want it to automatically scroll to the last element.

For example, if the user clicks the up button, it should scroll to chat-6, then chat-5, and so on. Similarly, clicking the down button should scroll downwards unless it is the last item.

function scroll(id){
    console.log(id);
    $(".container").animate(
        { 
            scrollTop: $("#"+id).offset().top
        },
        "fast"
    );
}

You can find the full code and try it out here: http://jsfiddle.net/p3kar5bb/231/

Unfortunately, the current code is not functioning correctly as intended.

Answer №1

Because the container in your div .container does not have a scroll bar, there are two options to consider.

1. Animated Scroll on Body

$("body").animate({ scrollTop: $("#"+id).parent('.item').offset().top}, "fast");

View Demo

2. Set Maximum Height for the Div

.container{
   height: 100%;
   overflow-y: scroll;
   max-height:200px;    
  }

View Demo

Answer №2

Adjust the animation to target the body element rather than the .container

function scroll(id){
console.log(id);
$("body").animate({ scrollTop: $("#"+id).offset().top}, "fast");

}

Ensure that the

var pointedPosition=0;

Check out the Fiddle here: http://jsfiddle.net/p3kar5bb/234/

Answer №3

$('html, body').animate({
scrollTop: $("#"+id).offset().top
}, 500);

If you view the code in http://jsfiddle.net/p3kar5bb/231/, you'll notice that the animate() function has been updated as shown above.

After testing, it was discovered that using $('html') alone doesn't work in Chrome and $('body') doesn't work in Firefox. To ensure compatibility, $('html, body') is used instead. Additionally, it's recommended to include .stop() for better performance.

Answer №4

If you've obtained the element id from a buttons click event, consider modifying the scroll function code like this:

 function scrollToElement(id){
      $('html, body').animate({ 
      scrollTop: $("#"+id).offset().top
        }, 2000);
}

I have made updates to your code available at http://jsfiddle.net/p3kar5bb/231/.

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

Transferring an array from PHP to jQuery

How can I pass an array from PHP to jQuery within the same file? I have an array named $array2 with data that I want to use to create a graph. The code below is currently using predefined chartData, but I would like to use a variable from my PHP script i ...

Python - Syntax Error - Unable to Locate Element by XPath

Attempting to gather all elements of a webpage with the assistance of Selenium web driver and utilizing XPATH. Each row that needs to be gathered commences with the same text. Therefore, the following code was implemented: container = driver.find_elements ...

React in 2022 has encountered an unexpected expression when it was expecting either an assignment or function call

I am having difficulty updating a chart with values received from an API. I am unsure about how to adjust the useEffect hook in my code. Any advice would be greatly appreciated. Here is a snippet of my code: import React, { useEffect, useState } from &quo ...

Automatically change a text based on its location

Currently leveraging the amazing flexible-nav to showcase the current subtopic within my post. I am also considering the possibility of extracting this current-string and showcasing it at the top of the page in my main navigation bar. This way, the text w ...

Resizing columns in HTML table remains effective even after the page is refreshed

I've created HTML pages with tables that have multiple columns, but I'm experiencing an issue. The columns are not resizable until I refresh the page. Could someone assist me in fixing this problem and explaining why it's happening? ...

What is the secret to creating double-width characters that are precisely double the size of single-width characters?

When using terminal, many fonts that support double-width characters display them as exactly twice the width of single-width characters. For instance, these two lines should appear with the same width: あああ aaaaaa However, this consistency is not ma ...

Unraveling encoded characters in URLs using Node.js

When I try to send a cookie back using res.cookie(JSON.stringify({bar: "baz"}), the value that I get in return is %7B%22bar%22%3A%22baz%22%7D. How can I decode this in a Javascript setting like node.js? ...

Unable to assign a class to the menu option

I'm encountering an issue with the following code: JavaScript $(document).ready(function() { var url = window.location; var element = $('#nav1 li a').filter(function() { return this.href == url || url.href.indexOf(this.href) == 0; ...

Bulma's Grid System Spans Columns Across the Entire Viewport

Utilizing the Bulma CSS framework. In my attempt to arrange some elements, I am puzzled as to why, in a desktop view, the items do not transition to the next row once they exceed the viewport. Below is a snippet of code along with a link to a JS Bin exam ...

Display the LOADING indicator until the entire page has finished loading

Here is the JavaScript code that I am currently using: function generateRequest(){ var request; if(window.XMLHttpRequest){ // Works with Firefox, Safari, Opera request = new XMLHttpRequest(); } else if(window.ActiveXObject) ...

Sending a PHP variable to jQuery using AJAX

I am working on a project where my ajax function in jquery is calling a php file to interact with the database. However, the result of this operation can vary. Depending on whether it succeeded or not, I want to output a different message. Currently, I ha ...

Change the color of a c3js chart when it loads

I have been searching for a way to customize the color of a scatter chart's plot, and I came across an example that uses d3 code within the chart http://jsfiddle.net/ot19Lyt8/9/ onmouseover: function (d) { d3.select(d3.selectAll("circle ...

Navigation menu with submenus containing buttons

I attempted to incorporate a dropdown into my existing navigation bar, but unfortunately, the dropdown content disappeared after adding the necessary code. I am now at a loss on how to troubleshoot this issue and make the dropdown function properly. Despit ...

Troubleshooting 500 Internal Server Error when using Codeigniter CSRF token with an AJAX request

I'm struggling with making an ajax request through my CI form while having the csrf token enabled. Despite extensive research, I keep encountering the same issue that has been addressed in various related problems - which involves adding the token val ...

Utilizing jquery and ajax to showcase a series of images prior to uploading them

I have been attempting to create a feature that allows for the preview of multiple images before uploading them to my website. Unfortunately, it's not working as expected and I am unable to identify any errors in the console. Below is the JavaScript c ...

React unable to properly render Array Map method

I am currently working on a project using ChakraUI and React to display a list of team members as cards. However, I am facing an issue where only the text "Team Members" is being displayed on the website, and not the actual mapped array of team members. Ca ...

What techniques can be used to resize an image to perfectly fit a square on a webpage?

A challenge on the web page is to display images in a square format of 90 * 90 pixels. However, the sizes of these images are not consistent and may vary from 80*100 to 100*80 or even 90 * 110. The requested solution is to stretch the image as follows: ...

How can I adjust the transparency in a JavaScript popup modal window for an ASP.Net GridView?

Recently, I added an 'onclick' event to every row of an asp gridview and the popup window that appears is functioning perfectly. Now, I'm interested in adding a transparency level to the body of the popup window for a translucent effect. Can ...

How can a JQuery slideshow be programmed to only iterate once?

Looking to create a slideshow that transitions between images every two seconds? Check out the code snippet below: HTML: <div class="fadeIn"> <img src="img/city.png" class="remimg" id="city"> <img src="img/shop.png" class="remimg" ...

Is it wrong to use <match v-for='match in matches' v-bind:match='match'></match>? Am I allowed to incorporate the match variable from the v-for loop into the v-bind attribute on the

I am attempting to display HTML for each individual match within the matches array. However, I am uncertain if <match v-for='match in matches' v-bind:match='match'></match> is the correct syntax to achieve this. To clarify, ...