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

Is the ClientScriptmanager operational during a partial postback?

After successfully completing an ASP.NET operation, I want to automatically close the browser window. The following code is executed by a button within an Ajax UpdatePanel: Page.ClientScript.RegisterClientScriptBlock(typeof(LeaveApproval), "ShowSuccess", ...

Managing window popups using WDIO - tips and tricks

Having some trouble handling a facebook auth dialog popup through webdriverio. Struggling to target the email and password fields for the facebook signup process. Below is the code in question: it('redirects after signup', () => { browse ...

Inline CSS alignment

While experimenting with layout inline elements, I came across some unusual behavior. Can someone please explain why there is a difference? I have applied the following CSS to both HTML structures: .time { position: relative; top:100px; heigh ...

Is it possible for jquery.find() to only target immediate children?

How can I use jQuery.find() to specifically target only the direct children of an element without selecting their descendants? Leading the selector with '>' or using '*' doesn't give me the desired result. While I know about jQuer ...

Encountering an unhandled runtime error while importing the Client component into the server component: The JSON format is invalid, with the error message stating "undefined"

I've been attempting to create a basic counter component that increments the count of a state variable when a button is clicked. To achieve this, I created a separate file named Counter.tsx and placed it in the components folder at the root of my next ...

Is there a way to create an X shape by rotating two divs when I click on the container div?

I currently have this setup: code Below is the HTML code: <div id="box"> <div id="line1" class="line"></div> <div id="line2" class="line"></div> <div id="line3" class="line"></div> </div> My go ...

Does Google's web crawler have the ability to index content created by javascript?

Our web app generates content using javascript. Can Google index these pages? In our research on this issue, we primarily found solutions on older pages suggesting the use of "#!" in links. Within our app, the links are structured as follows: domain.co ...

.malfunctioning in Internet Explorer due to compatibility issues

While I have not personally experienced this issue, there seems to be a problem with a form on our website. After changing the value (using .change()), the field is supposed to update by sending data to save.php. However, some users have reported that this ...

Apply a specific CSS class to a division depending on the currently active cookie

I have implemented cookies on specific pages using https://github.com/carhartl/jquery-cookie. Could someone guide me on how to apply a CSS class to an ID (e.g., adding class .red to #mouse if the cookie named "socks" is active)? For example: If there is ...

The issue with the callback function not being triggered within a self-repeating loop

As I work on creating a user-script to incorporate a trailer video into a website, I encountered an issue with the callback function in my script. The goal is to filter the real source of the video from different URL formats, but for some reason, the callb ...

Unable to update a single object within an array using the spread operator

I am currently working on updating an object within an array and have encountered some issues. In my initial code, I successfully updated a specific property of the object inside the array like this: var equipment = this.equipments.find((e) => e.id === ...

What could be the reason behind ng-bind-html only displaying text and not the link?

Utilizing ng-repeat to exhibit a list on my webpage. One of the fields in my data contains a URL that I want to display as an actual link within my HTML page. Please refer to the screenshots below: My HTML: My rendered page: I have included the angular- ...

Can you eliminate the commas and turn it into a string?

function EncryptMessage(message) { var encryptedArr = []; for(i=0;i<message.length+1;i++){ var unicode = message.charCodeAt(i); var encryptedUnicode; var newCharacter = String.fromCharCode(encryptedUnicode); if( ...

The most efficient method for retrieving data in React

Recently, I started working on a React App integrated with Riot API to display users' recent games and more. As part of this project, I'm utilizing React and NextJS (fairly new to NextJS). However, I'm contemplating the most efficient way to ...

Learn how to upload an image from Express.js to Google Cloud Storage or Firebase Storage

Currently, I am delving into the world of ExpressJS and attempting to upload an image to Firebase storage using Node. However, I encountered the error message: firebase.storage().ref() is not a function. After researching this issue, I stumbled upon this ...

Combine the text value from a textbox and the value from a checkbox into a single

I'm trying to solve a challenge regarding appending values from text fields (excluding empty ones) and checkboxes in a specific order to form a string. It should be in the format: name|T|F_name|F|F. Once I've created this string, I plan to send i ...

Running a Vue.js application on a hosting platform

I am currently facing an issue with my Vue.js application. I have set up a domain and subdomain for the application and now I want to host it. However, when I try to add the subdomain name, I keep encountering 500 Internal server errors. This is my first t ...

Transferring array data between two distinct click actions

Is there a way to transfer values between click events in jQuery? For example, on the first click event I want to add or remove values from an array based on whether a checkbox is checked. Then, on the second click I would like to iterate through all the ...

Angular does not delay for promises to settle

Issue I am facing is related to Angular not waiting for promises to be resolved. The console inspection reveals that the provider and skills objects are not retrieved before the promises are returned. I have included the key parts of the code below. The s ...

What is the reason behind FieldSelect returning a string instead of an object like FieldCheckbox?

FieldSelect component from Sharetribe documents is giving me a string, while FieldCheckbox is returning a JSON object. In a specific scenario, I want FieldSelect to store a JSON object. How can I achieve this? Below is the code snippet for reference: I& ...