Adjusting the Scroll on the Slider Container

I'm currently developing a dynamic news feed feature that incorporates slides to display a brief summary along with a "Read More" button. Clicking on the "Read More" button will expand the content, pausing the scrolling mechanism until minimized by clicking "Less".

Feel free to check out the live demo on jsFiddle: http://jsfiddle.net/pbunz5ue/1/

However, I've encountered an issue where the scroll alignment within the div is not consistent after the second round of story displays via the button. The initial display functions perfectly, but subsequent read more actions seem to disrupt this alignment. Can anyone shed some light on why this might be happening?

Below is the snippet of code used:

JS:

$(document).ready(function() {

    //User clicks Read More, add 'open' class to news item
    $('.news-read-more').on('click', function() {
        blockedSlider = true;
        clearInterval(myTimer);
        $('.news-list').children('li').each(function() {
            $(this).removeClass('open');
        });
        $(this).parent().toggleClass('open');

        var n = $(this).parent();
        var pos = n.position();
        $('.news-slider-wrapper').scrollTop(pos.top); 

    }); 

    //User clicks Less, remove 'open' class from news item
    $('.news-read-less').on('click', function() {
        if (blockedSlider == true) {
            blockedSlider = false;
            $(this).parent().removeClass('open');
            myTimer = setInterval(slideLoop, 2000)
        }
    });

    var myTimer = setInterval(slideLoop, 2000)
    var blockedSlider = false;

    function slideLoop() {
        // Work out width of current slider size
        var widthPx = $('.news-list-item').css('height');
        var width = parseInt(widthPx.substring(0, widthPx.length - 2));

        // Work out current top position
        var top = $('.news-list').css('top');
        top = parseInt(top.substring(0, top.length - 2));

        if (top <= -(width * 2)) {
            var neg = '-' + widthPx;
            $('.news-list').css('top', neg);

            var slide = $('.news-list li:first');
            $('.news-list').children('li:first').remove();
            $('.news-list ').append(slide);

            //User clicks Read More, add 'open' class to news item
            $('.news-read-more').on('click', function() {
                blockedSlider = true;
                clearInterval(myTimer);
                $('.news-list').children('li').each(function() {
                    $(this).removeClass('open');
                });
                $(this).parent().toggleClass('open');

                var n = $(this).parent();
                var pos = n.position();
                $('.news-slider-wrapper').scrollTop(pos.top - 360); 

            }); 

            //User clicks Less, remove 'open' class from news item
            $('.news-read-less').on('click', function() {
                if (blockedSlider == true) {
                    blockedSlider = false;
                    $(this).parent().removeClass('open');
                    myTimer = setInterval(slideLoop, 2000)
                }
            });         

            var move = "-=" + widthPx;
            $('.news-list').animate({ top: move }, "slow", "swing");

        } else {
            var move = "-=" + widthPx;
            $('.news-list').animate({ top: move }, "slow", "swing");
        }
    }

});

Answer №1

The issue arises from a negative "top" position in the .news-list, disrupting the positioning of the element that is opened.

-> I have made adjustments to your fiddle: http://jsfiddle.net/pbunz5ue/3/ <-

Changes I've Made

  1. Main Correction:

    When calculating the position, the negative top offset of the news container .news-list when it slides up was not being taken into account:

    I have modified these two lines:

    var pos = n.position();
    $('.news-slider-wrapper').scrollTop(pos.top); 
    

    to:

    var pos = n.position().top + parseInt($(".news-list").css("top")) || n.position().top;
    $('.news-slider-wrapper').scrollTop(pos); 
    

    If $(".news-list") has a top position, I include it in the position calculation (if the result is auto, there is a fallback to prevent a NaN result || n.position().top)

  2. You had redundant event handlers $('.news-read-more').on('click') and

    $('.news-read-less').on('click');
    . I removed those within the function as they appeared unnecessary.

EDIT:: Issue with .on click

Try these two methods to resolve your problem:

1.

If you encounter issues when a new item is added to your list, try binding the event to the "items" container .news-list and filtering the selector each time it fires:

$('.news-read-more').on('click', function() { //...
$('.news-read-less').on('click', function() { //...

changes to:

$('.news-list').on('click','.news-read-more', function() { //...
$('.news-list').on('click','.news-read-less', function() { //...

The container .news-list remains constant during your animation and DOM manipulation.

2.

Another approach is to modify these lines in your code:

 var slide = $('.news-list li:first');
 $('.news-list').children('li:first').remove();
 $('.news-list ').append(slide);

becomes:

 var slide = $('.news-list li:first');
 $('.news-list ').append(slide);

or:

 $('.news-list ').append('.news-list li:first');

If you use .remove on the element, (I believe) you unbind all events because you are removing the element from the DOM, but instead of removal, you should move it from top to bottom. This method prevents the unbinding of the click event.


I hope I have correctly grasped the issue :).

Apologies for any errors in my English

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

Java - RESTful API endpoint that serves images when available and JSON data when images are not available

I am currently working on incorporating a mobile front-end using the Ionic Framework along with the $cordovaFileTransfer plugin. My focus is on fetching and uploading a person's Profile Photo. Uploading the photo is functioning properly, but I am enco ...

Detecting collisions on a pixel-by-pixel basis within Javascript/Jquery/Gamequery

Currently, I am working on developing a web game using Jquery with the GameQuery plugin. However, I have encountered an issue where the GameQuery plugin does not support per pixel collision detection, only bounding boxes collision detection. Is there a way ...

arranging texts in a vertical stack with wrapping

Looking to change the orientation of my horizontally wrapped list items from vertical to horizontal. Take a look at my code snippet: HTML <ul> <li>Long text goes here.</li> <li>Another Longer Text Goes Here</li> < ...

Is it better to use enum rather than ul for inline lists within paragraphs in HTML5?

Reflecting on the passage below: So in the initial group, we merge these 3 codes: - AA - BB - CC with the following codes: - Aa - Ab - Ac to achieve the desired outcome. Is this paragraph semantically incorrect? If not, how should it be written in H ...

What is the best way to send back data as a response after making a $.post request in PHP?

Looking to set up a basic post function using jQuery that takes the client's name as input and returns their information (address, phone, age, etc.). Here's what I have so far: Script: $(document).ready(function(){ $("#getClientInfo").on(&a ...

How can I dynamically generate multiple Reactive Forms from an array of names using ngFor in Angular?

I am in the process of developing an ID lookup form using Angular. My goal is to generate multiple formGroups within the same HTML file based on an array of values I have, all while keeping my code DRY (Don't Repeat Yourself). Each formGroup will be l ...

Identify which anchor tag from the group with the matching class was selected and retrieve its unique identifier

There are multiple anchor tags with the same class in my code. <a href='' id='id1' class='abc'>Link 1</a> <a href='' id='id2' class='abc'>Link 2</a> <a href='&apos ...

The value of a Highcharts series does not match that of a Data Source

Encountering an issue with Highcharts where the value of this.y does not reflect the data source. The discrepancy is apparent in the image below. Uncertain if this is a bug or user error. Screenshot illustrating the problem You can view my Demo here: htt ...

Performing a C# server-side AJAX post request processing

I am currently tackling a new challenge that I have not encountered before. After doing some research, I found solutions suggesting the use of .aspx pages to process forms. My goal is to send form input via ajax (with jquery) to the server for processing ...

Support for numeric font weights in web browsers

Which browser versions have full support for using numeric values for the font-weight property? This includes Internet Explorer, Firefox, Chrome, Safari, iOS Safari, and Android Browser. While most browsers support the keyword values 'bold' and ...

Error: Namespace declaration does not have a type annotation - TypeScript/Babel

After creating my app using the command npx create-react-app --typescript, I encountered an issue with generated code and namespaces causing Babel to throw an error. Here are the steps I took to try and resolve the issue: I ejected the project Updated b ...

When it comes to creating a CSS drop-down menu, don't forget to incorporate an additional <ul

I've created a drop-down menu using CSS with 5 visible list items. When hovering over one of the list items, it highlights and triggers a drop-down effect to display another list underneath. Essentially, you have an initial set of options, and upon ho ...

Display a fixed legend on Google Chart without showing percentage values

<script type="text/javascript"> // Loading the Visualization API and the piechart package. google.load('visualization', '1', {'packages':['corechart']}); // Setting a callback to run when the Goo ...

What sets returning a promise from async or a regular function apart?

I have been pondering whether the async keyword is redundant when simply returning a promise for some time now. Let's take a look at this example: async function thePromise() { const v = await Inner(); return v+1; } async function wrapper() ...

Outlook failing to recognize text dimensions

Implementing: <html> <head> <style> p { font-size: 16px; } .font-size-16 { font-size: 16px !important; } </style> </head> <body> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspend ...

Error: AJAX requesting page not listed in manifest

When using a cached HTML page and JQuery, I've encountered difficulty accessing a page from the server that is not listed on the manifest. Every attempt I make to access a page not included in the manifest results in a return of null or an empty strin ...

How can I stack a div on top of two columns in Bootstrap?

My goal is to design something like this: I want to have a single-color strip that extends over three columns: https://i.sstatic.net/1XfAu.png What I am aiming for is a layout where the grey line overlaps columns 2 and 3. /* added by editor for demo p ...

IE-7 z-index problem - Dropdown section obscured by banner with missing content in IE-7

I have set up a test case at . The dropdowns are not displaying over the banner image in IE-7, but they work fine in Firefox and Chrome. Can anyone help me identify and resolve this issue? ...

Seamless transitions while deactivating a conditionally displayed component in React

Here is my code snippet from App.js: export const App = () => { const [toggled, setToggled] = useState(false); const [ordering, setOrdering] = useState(false); const handleColorModeClick = () => { setToggled((s) => !s); }; const ha ...

What is causing my Nuxt.js application to show a blank page following deployment on Netlify?

Currently, I am facing an issue while trying to deploy a Nuxt.js site using Netlify and Heroku. Although my build passes on Netlify, the link displays a blank page (). Despite following various online tutorials and adapting solutions from SO for react apps ...