Dynamic jQuery snapping effect after scrolling horizontally

I'm currently working on a horizontal-scrolling site that utilizes the mousewheel jQuery Plugin. The scrolling functionality is functional, however, I am looking to implement a feature that snaps each "article" to the left side of the document when scrolling comes to a stop.

Here's the current markup:

CSS

#viewport {
width:100%;
height:100%;
overflow: hidden;
}

#stage {
height:100%;
width:400%;
position: absolute;
display:block;
overflow: hidden;
}

#stage article {
width:25%;
height:100%;
position: relative;
display:block;
float:left;
}

HTML

<div id="viewport">
<section id="stage" class="clearfix">
<article>
This block should snap to the left upon scrolling stopping.
</article>

<article>
This block should snap to the left upon scrolling stopping.
</article>

<article>
This block should snap to the left upon scrolling stopping.
</article>

<article>
This block should snap to the left upon scrolling stopping.
</article>

</section>
</div>

JQUERY

$(function() {
$("html, body").mousewheel(function(event, delta) {
this.scrollLeft -= (delta * 30);
event.preventDefault();
});
});

After attempting to implement the script provided above, I did not achieve the desired results. It seems that the use of percentages may be hindering the ability to determine the previous/next location.

Thank you for any assistance in advance.

Answer №1

I'm unsure about your reference to the previous or next location.

However, one approach could be to check at the end of each scroll if the left side of the screen aligns with the nearest article. If not, adjust the scroll position slightly.

Perhaps something like this:

$(function() {
    $("html, body").mousewheel(function(event, delta) {

        var theBody = $('body');
        theBody.scrollLeft(this.scollLeft() - delta * 30);

        /* Determine how close you are, number of articles nearby, and direction of the scroll */
        var tolerance = 10;
        var numberOfArticles = 4;
        var signDelta = number?number<0?-1:1:0;

        /* Continuously adjust until within acceptable tolerance range */
        while (!((theBody.scollLeft()%(theBody.width() / numberOfArticles))  > tolerance))
        {
            theBody.scrollLeft(theBody.scollLeft() - signDelta * 1);
        }

        event.preventDefault();
    });
});

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

What is the method for looping through and inserting objects into an array using JavaScript's $.each function?

As a novice programmer, I am tackling the challenge of transferring four properties from my JSONP array into a new array for each item. $.ajax({ url: etsyURL, dataType: 'jsonp', success: function(data) { if (data.ok) { ...

Has the jQuery plugin object misplaced a variable?

I am in the process of developing a basic plugin using jQuery. My current approach involves creating private functions and storing variables within the jQuery object itself. (function($) { var somePrivateFn = function() { alert(this.x); } ...

Incorporate user input into Alert Dialog Boxes

Would you be able to assist me in displaying the input value from the "email" field in my alert box? The code seems to be working fine, but I'm having trouble getting the alert box to show the email form value. I decided to use Bootstrap for som ...

What is the best way to extract data for the x-axis and track the frequency of occurrences for the y-axis using crossfilter in JavaScript

My current project involves using crossfilter to analyze data on the x-axis and the frequency of occurrences on the y-axis. var data = [{ Owner: "Alyssa", ID: "A" }, { Owner: "Alyssa", ID: "A" }, { Owner: "Alyss ...

Incorporate a dynamic HTML attribute into the ChildComponent

I am looking to include a dynamic HTML property called 'hits' in my ChildComponent within the HTML code: <child-component test={{ variable }}></child.component> I do not intend to use it as an input, but rather just for testing p ...

Transfer a file from the file:///var/mobile/Applications/ directory to an accessible location for reading in Cordova/PhoneGap

I have a unique 'whitelabel' app that customizes itself for each client by downloading image files from a configuration server. However, I am facing an issue where the images are not displayed and instead showing a "Not allowed to load local reso ...

Sending data from a dynamically created PHP table to a modal

In my PHP-generated table, I have: <tbody> <?php $results = DB::select()->from('users')->execute(); foreach ($results as $user) { echo "<tr id='".$user['id']."'> <input type=&bs ...

Is it possible to utilize razor syntax within a jQuery template?

Just dipping my toes into the world of web development! I've been playing around with jquery templates and they seem to be working well for me. However, I've come across a markup code that includes things like this: @Html.ActionLink("MyAction", ...

Jquery UI - selection buttons

Greetings everyone, Hey there, so on this particular page, I've got some radio buttons and sliders courtesy of jQuery UI. Here's the issue I'm facing: When I select an answer for the first question (yes/no) and then move on to the second qu ...

What could be causing the appearance of two vertical scrollbars after transitioning from ReactJS to NextJS?

During the development of a project in plain ReactJS, I added these two lines to my index.css: overflow-y: scroll; overflow-x: hidden; The purpose was to ensure a vertical scrollbar always appeared without causing a horizontal scrollbar even when there wa ...

Solving issues with jQuery AJAX request through a Generic Handler in ASP.NET

Need help troubleshooting a jQuery AJAX call with ASP.NET. The error function is triggered, but it's not reaching the handler. Why is that? The error function is only executed every other click on the search button (BtnUCSSearch). The error popup fla ...

Concealing options within Select2

Is there a way to hide certain Select2 options? When I attempt to use CSS like this: <option style="display: none;">...</option> Select2 does not seem to recognize it, unlike when an option is disabled or set as "readonly". Does any ...

create a layout with intersecting divs to display a table/chart

Lately, I have been pondering how to achieve a design similar to the one shown below. Specifically, I am interested in the "sparkline/area" chart that appears at the bottom of the table/divs. I can't seem to figure out how to code something like this ...

Preventing Broken URLs in Jquery each

What is the best way to prevent taking images with broken URLs? jQuery.each(jQuery('img'), function(index, obj) { imageStack.add(jQuery(obj)); }); ...

Which is the better option for opening a link in a button: using onclick or href?

What is the most effective way to open a link using a button? <button type="button" onclick="location='permalink.php'">Permalink</button> <button type="button" href="index.php">Permalink</button> ...

Leverage AJAX for real-time Django Model updates

Seeking insights on how to effortlessly update a Django model through AJAX without reloading the page or requiring user input for saving. Various tutorials address fetching data from Django models using AJAX, yet resources on updating models remain scarce. ...

What are some tips for utilizing CSS sprites with finesse within an inline element?

Although I am familiar with this workaround for the inline-block property due to poor browser support, I am curious if there is a more sophisticated solution for using CSS sprites without the need for block elements to have line breaks. For example, in th ...

Tips for vertically aligning text in the center with bootstrap

When creating a portfolio with bootstrap, I encountered an issue where I couldn't get the text to be vertically centered. Even after trying align-items-center and justify-content-center, I still couldn't achieve the desired result. Here is the sn ...

What are the different ways to programmatically change CSS rules using JavaScript in a Firefox Add-on, leveraging XUL, SDK, or WebExtensions methods?

Looking to dynamically alter a CSS rule set through JavaScript within a Firefox Add-on using XUL, SDK or WebExtensions techniques. Specifically targeting support for Firefox versions 29.0b1 through 49.0a1. The main issue I want to address is modifying the ...

Is it possible to implement custom classes in @apply within a SCSS file in a Tailwind Next.js project?

Having trouble implementing a custom class overflow:inherit as @apply overflow-inherit in my next.js project with tailwind. It seems to be causing an error. Strangely, I can successfully use pre-built tailwind classes like @apply flex flex-col md:h-full h- ...