Interactive JQuery plugin for scrolling through thumbnails with customizable buttons

I am attempting to create a jQuery thumbnail scroller with buttons that respond to mousedown and mouseup events. I have successfully implemented the scrolling functionality, but I am facing issues when trying to refactor it into a reusable function. Below is the code for my scroller:


var $wrapper = $('.my_ul');
var $div = $('.my_div');
var $ul = $('.my_ul');

function scrollRight() {
  var divLeft = $ul.css('marginLeft');
  divLeft = Math.abs(parseInt(divLeft)) - 60;

  var width = $div.width();
  var ulwid = $ul.width();

  var ulWidth = $ul.width() - width;
  
  if (divLeft >= ulWidth) {
    stopScrolling();
  } else {
    $wrapper.animate({'margin-left': '-=10'}, 1, scrollRight);
  }
}

function scrollLeft() {   
  var divLeft = $ul.css('marginLeft');
  divLeft = parseInt(divLeft);

  if (divLeft >= 0) {
    stopScrolling();
  } else {
    $wrapper.animate({'margin-left': '+=10'}, 1, scrollLeft);
  }
}

function stopScrolling() {
  $wrapper.stop();
}

$('.scroll_right').mousedown(scrollRight).mouseup(stopScrolling);
$('.scroll_left').mousedown(scrollLeft).mouseup(stopScrolling);

I have tried creating a parameterized function without success, and I have noticed that the animation slows down due to recursive calls. If anyone has alternative solutions or suggestions, please share them with me.

Answer №1

This method is proven to be effective:

function scrollFunction($rightSide, $leftSide, $wrapperElement, $divElement, $ulElement) {

    $rightSide.mousedown(scrollRight).mouseup(stopScrolling);
    $leftSide.mousedown(scrollLeft).mouseup(stopScrolling);

    ... insert custom functions here ...

}

Simply call the function with the output of a jQuery selection for the desired elements.

scrollFunction($(".scroll_right"), $(".scroll_left"), ...);

Answer №2

If we want to increase the speed, we can make this adjustment:

 $wrapper.animate({'margin-left' : '+=20'}, 1, scrollLeft);}

To add a slight delay of 1/60 second, we can do this:

$wrapper.animate({'margin-left' : '+=10'}, 16, scrollLeft);}

Another optimization suggestion is to extract this part out of the function to avoid redundant jQuery calls. This section remains constant throughout scrolling and even after loading the div and ul elements:

var width = $div.width();
var ulwid = $ul.width();
var ulWidth = ulwid - width;

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

Convert specific form inputs into an array

I have a form that includes various inputs, but the ones I am focusing on are labeled attributes[] and options[$index][]. Here is an example of the data found in my attributes[] input: Array ( [0] => Size [1] => Color [2] => Material ) Not ...

The effective method for transferring a PHP variable value between two PHP files using jQuery

I am looking to transmit the variable "idlaw" from base.js to the PHP page edit.php. modifyLegislation.php <input class='btn btn-primary buttonBlue' type='button' name='btnAcceptPending' value='Edit' onClick="ja ...

Choose to either push as a single object or as individual items

I have a quick question that I'd like to get some clarity on. Can someone explain the distinction between these two code snippets: export const addToCart = function(product, quantity){ cart.push({product, quantity}); console.log(`${quantity} ...

Fresh Redux shop in stealth mode

I am managing a Single Page Application using React and Redux. Some customers have expressed interest in keeping two separate instances open with distinct credentials (one in normal view and one in incognito mode on Chrome). As both instances can access t ...

Understanding and aggregating data from JSON files

I am in possession of a group of json values outlined below {"labels":[ "time", "softirq", "user", "system", "nice", "iowait" ], "data":[ [ 1490088352, 0, 14.64646, 3.53535, 0, 1.0101 ], [ 1490088351, 0, 27.77778, 3.0303, 0, 0 ], [ 1490088350, 0.49751, 12 ...

Prevent jQuery from overriding CSS styling

Having an issue with adding a <p> tag before each jQuery accordion on my MVC page. No matter what I try, the jQuery styling keeps interfering with the classes and styles of my <p> tag. Is there a way to make it look like the other non-jQuery & ...

Modifying the app.css file in the source tab of dev tools does not cause any changes in the DOM when working with a

Just starting out with react js here. While exploring developer tools in Chrome, I attempted to tweak some CSS in the elements panel and noticed the changes reflecting above in the DOM. However, when I navigate to the sources tab, I'm unable to modify ...

I would like to take the first two letters of the first and last name from the text box and display them somewhere on the page

Can anyone help me with creating a code that will display the first two letters of a person's first name followed by their last name in a text box? For example, if someone enters "Salman Shaikh," it should appear somewhere on my page as "SASH." I woul ...

Unable to retrieve input using jquery selector

I am attempting to detect the click event on a checkbox. The Xpath for the element provided by firebug is as follows, starting with a table tag in my JSP (i.e. the table is within a div). /html/body/div[1]/div/div/div[2]/div/div[2]/div[1]/div/div[2]/table ...

Template7 produces a bizarre outcome referred to as "each this" whenever JSON is utilized

Currently, I am experimenting with dynamically loading content on Framework7/Template7 pages. Everything works perfectly fine when using static "context" in JSON format. However, when attempting to test it with real-world data from an API, I encounter a st ...

Display an alert when no matches are found in autocomplete suggestions

I am implementing the code below to populate a textbox with data. If I input a, all records starting with a are displayed in the dropdown from the database. However, if I input a value that does not exist in the database, there is no message like "No Recor ...

Offsetting absolute elements in a horizontal landscape view

When I view my page on a mobile browser (tested on Android JB and iOS 6), it renders fine initially in both portrait and landscape modes. However, the issue arises when I switch from landscape to portrait - the absolute positioned divs are offset from thei ...

JQuery can be used to query a JSON array

Seeking assistance in extracting JSON data from my WordPress site to determine the number of posts with a specific custom field value. Here is an example of the JSON output: {"posts":[ { "id": 21831, "custom_fields": { "us_congress_chamber": [ ...

Checking the Signature with Elrond in the Backend using PHP

My latest decentralized application allows users to log in using their Elrond wallet and generate a unique signature containing their wallet address and additional data. As part of the authorization process, the signature is included in the payload of req ...

Significant delay in fetching model data for controller via XHR

My controller is designed to make an ajax call to retrieve its model, which is a 4.5k json containing a 2d array. This data is then used to create a combo displaying a series of labels in the html below: <select data-ng-controller="CGSimpleXHRComboCont ...

Invoke a function within one component using another component

I am facing an issue with deleting playlists displayed on my page. These playlists are fetched from an external API and each playlist has a delete button which is supposed to remove the playlist both from the API and the view. The deletion process works s ...

What steps can I take to resolve the issue of a Promise that remains in a

Currently, I am working on implementing a protected route feature in React. My goal is to modify the result variable so that it returns a boolean value instead of a promise without converting the ProtectedRoute function into an async function: import Reac ...

Javascript - formatting numbers with decimals

This question is not related to math or operators, but rather a formatting or masking issue. I am working on creating an order form that uses Javascript to tally and display the quantity and cost of each column in separate fields. I am trying to format th ...

Transferring a Query between Domains with the Help of JavaScript

It is necessary to develop a function that generates a query based on the user's input of "Test" in an INPUT on Site A (SiteA.com) and then redirects to Site B within the same window, passing along the query (SiteB.com/search.aspx?k=test). Code snipp ...

Discovering and substituting a specified text in JQuery

I am facing a particular issue that I need help with. My task involves locating and replacing a specific string obtained through an AJAX request. Code: JQuery: if(!countflag) { $('.panel-body > p').each(function() { var content ...