Is there a way to confine a jquery script within the dimensions of the container div?

I have recently created a gallery with navigation buttons in jQuery. As a newcomer to jQuery, I wrote a small script that adjusts the margin of a div container by a fixed amount. The script is functioning properly, but it extends beyond the top and bottom edges of the div content. While I could set a specific size for the div, my goal is to use this on multiple pages with varying amounts of content. How can I ensure that the button function does not exceed the boundaries of the content inside the div?

 $('.scrolltdup').click(function(event) {
  event.preventDefault();
  $('.wrap').animate({
    marginTop: "+=160px"
  }, "fast");
 });

$('.scrolltddown').click(function(event) {
  event.preventDefault();
  $('.wrap').animate({
    marginTop: "-=160px"
  }, "fast");
});

I have created a jsfiddle showcasing the page content. Any assistance would be highly appreciated. This project marks my first attempt at building a website from scratch using HTML5, CSS3, and jQuery; it's been a learning journey. :)

Thank you in advance.

Answer №1

To improve the functionality, simply include some if statements:

Check out the updated demo here: https://jsfiddle.net/2LcumL6p/4/

$('.scrolltdup').click(function(event) {
    event.preventDefault();
    if (parseInt($('.wrap').css('margin-top')) < 0) {
        $('.wrap').animate({
            marginTop: "+=160px"
        }, "fast");
    }
});

$('.scrolltddown').click(function(event) {
    event.preventDefault();
    if (parseInt($('.wrap').css('margin-top')) > -($('.wrap').height() - 160)) {
        $('.wrap').animate({
            marginTop: "-=160px"
        }, "fast");
    }
});

Answer №2

The container displays 3 visible boxes in a fixed shape at once, allowing you to determine the number of sets of 3 with the formula

var totalRows = Math.max( $(".box").length / 3 )
.

By calculating the maximum marginTop value before reaching the end of the projects, you can test this value before animating. One way to achieve this is by setting the maxScroll and minScroll values to the highest and lowest marginTop on page load, and then inserting a ternary operator into your animate code.

Replace marginTop: "+=160px"

With

marginTop: "+=" + ( $(".wrap").css( "margin-top" ) > maxScroll ? "0px" : "160px"
;

And apply the same logic for marginTop: "-=160px".

Answer №3

When considering each row containing two divs with the class 'box', the following code is a functional solution for finding the maximum height between the two divs and animating accordingly:

let presentRow = 1;
function getHeight(elem1, elem2){
  return Math.max($(elem1).outerHeight(), $(elem2).outerHeight()) + 10;
}

$('.scrolltdup').click(function(event) {
      event.preventDefault();

      let height = getHeight($(".wrap .box:nth-child(" + presentRow + ")"), $(".wrap .box:nth-child(" + (presentRow + 1) + ")")); 
      $('.wrap').animate({
        marginTop: "+=" + height + "px"
      }, "fast", function(){
          presentRow = presentRow - 2;
      });

   });
   $('.scrolltddown').click(function(event) {
      event.preventDefault();

      let height = getHeight($(".wrap .box:nth-child(" + presentRow + ")"), $(".wrap .box:nth-child(" + (presentRow + 1) + ")")); 
      $('.wrap').animate({
        marginTop: "-=" + height + "px"
      }, "fast", function(){
          presentRow = presentRow + 2;
      });
   });

To add validation, you can check the value of the presentRow variable.

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 preventing the input box from shrinking further?

I created a search box using CSS grid that is supposed to shrink when the page is resized. However, it doesn't seem to shrink as much as I expected it to. Here is how it appears when fully extended: https://i.stack.imgur.com/tPuCg.png And here is how ...

How to retrieve the value of an observable from a regular JavaScript array in Knockout JS?

Context In my project, I am working with a plain JavaScript array that starts off empty but gets populated with Knockout observables later on. These values are numbers and I need to compare them with values in another Knockout observable array. The issue ...

When making an Ajax call to an ASP.NET MVC controller, the Access-Control-Allow-Origin error is commonly encountered

Currently, I am facing an issue with my ajax call in the view script. The problem arises when attempting to retrieve data from a controller action within the same website, resulting in a Cross-Origin error message. The JavaScript code snippet is as follow ...

The storage capacity of localStorage is insufficient for retaining data

While I was trying to troubleshoot an error, I encountered another issue. var save_button = document.getElementById('overlayBtn'); if(save_button){ save_button.addEventListener('click', updateOutput);} This led to the following ...

Leverage the power of personalized SCSS styles in combination with Bootstrap-Vue, Webpack, and

I have been working on an application using VueJS with Bootstrap-Vue and I encountered a challenge while trying to import a SCSS file to customize the Bootstrap variables and add some custom styles. Here are the steps I have taken so far: Installed node ...

In JavaScript, the task involves filtering through multiple arrays of objects to calculate the average value based on the contract number

Every object in the Array contains a contractNumber, but with repeated values. I am attempting to determine the average value of each unique contractNumber. var vendorArr=[{ "contractNumber":5258, "monthId":0, "value":2}, { ...

What is the suitable condition necessary for optimal functionality?

Greetings all! I am a newbie in the world of development and also new to Stack Overflow. This is my maiden post seeking assistance on the following issue: $(document).ready(function() { $(".header").click(function() { if ($(".header-content"). ...

Error: react/js encountered an unexpected token

While attempting to execute my project, I encountered an error in the console related to a function within the code. The exact error message reads as follows: "63:25 error Parsing error: Unexpected token, expected (function toggleDrawer = (open) => () ...

Validation with Jquery in an ASP.NET C# login form utilizing a webservice

Hi there, I've been working on a login form in asp.net that should redirect to another page. To handle user validation, I created a webservice using jQuery but I'm facing an issue where the ajax data is returning undefined and the page is not red ...

Using 'interface' declarations from TypeScript is unsupported in JS for React Native testing purposes

I have a ReactNative app and I'm attempting to create a test using Jest. The test requires classes from a native component (react-native-nfc-manager), and one of the needed classes is defined as follows export interface TagEvent { ndefMessage: N ...

Having trouble with my basic jQuery Ajax call not functioning as expected

When accessing this URL http://schooltray.com/VsStWsMblApps/SayHello?fullName=Joe%20Smith The response is: {"SayHelloResult":"{\"Status\":1,\"Message\":\"Hello Joe Smith\"}"} However, my JQuery call seems to be failing. Bel ...

Eliminate the CSS triggered by a mouse click

Having some difficulty toggling the switch to change the background color. Struggling with removing the applied CSS and getting it to toggle between two different colored backgrounds. Code Sample: <!Doctype html> <html lang="en"> <head> ...

Counting the elements on a page using Selenium and Node.js: A step-by-step guide

I've been experimenting with Selenium in Javascript using NodeJS and I'm trying to tally up some elements based on CSS selectors. So far, I've attempted a few methods: client.findElements(By.css(".some-class")).size(); However, I encounte ...

Exploring how to iterate through multiple arrays simultaneously in JavaScript

I have a specific problem with processing two sets of array objects to achieve a desired output. var parts={"Glenn": [12,22,32], "Ryan": [13,23,33], "Steve K": [14], "Jerom":[15,25,35], }; var labor={ "Glenn": [12,22,32], "Ryan": [13,23,33], "Steve K": [ ...

Utilizing a fallback option for HTML5 video with a flash player and the ability to manipulate the

My dilemma involves an HTML5 video where I am utilizing jquery to interact with the player using the code snippet: video.currentTime += 1;. However, when Internet Explorer switches to Flash plugins, my JQ commands cease to function. How can I manage and co ...

Preventing HTML form from being resubmitted upon page refresh after submission

I am facing an issue with my HTML form. Whenever I click submit, the form data is sent to the same php page. However, after submitting, when I refresh the page, the web browser shows a re-submission dialog. How can I prevent the form from submitting again ...

Activate event using jQuery in webpack and manage it on the page

I'm currently in the process of revamping a large application using React. One challenge I've encountered is refreshing a datatable on the page after a successful form submission, as the datatable isn't controlled by React or webpack. I trie ...

Is it possible to enter NaN in Vue3?

Is there a way to handle NaN values and keep a field blank instead when calculating margins with a formula? https://i.stack.imgur.com/JvIRQ.png Template <form> <div class="row"> <div class="mb-3 col-sm ...

Calculate sums in ReactJS without the need for a button

Adding a few numbers might seem like an easy task, but I've been unable to do so without using an explicit button. // Using useState to handle state changes const [ totalCount, setTotalCount ] = useState(0) // Function to add numbers of differ ...

Position the Crossmark to align with text using CSS styling

How can I properly align a crossmark and a checkmark with the text behind them? The checkmark looks aligned well, but the crossmark appears to be slightly off to the top-right. I'm hesitant to adjust margins and paddings as it may cause issues when th ...