Issue with carousel functionality being disrupted by resizing of the window

I have lined up a series of 3 divs floating to the left in a straight line, each spanning the width of the page. Here is an example of the HTML structure:

<div class="Horizontal-Wrapper">
      <div class="Horizontal-Section">
        <div class="Project-Wrapper">
          <div class="Project-Box" id="PJB1"><div class="Project-Box-Overlay"><h2>Splash</h2><p>Industries define the ideal selection for both wholesale and retail quantities of high quality</p></div></div>
          <div class="Project-Box" id="PJB2"><div class="Project-Box-Overlay"><h2>Splash</h2><p>Industries define the ideal selection for both wholesale and retail quantities of high quality</p></div></div>
        </div>
       </div>
       <div class="Horizontal-Section">
        <div class="Project-Wrapper">
          <div class="Project-Box" id="PJB3"><div class="Project-Box-Overlay"><h2>Splash</h2><p>Industries define the ideal selection for both wholesale and retail quantities of high quality</p></div></div>
          <div class="Project-Box" id="PJB4"><div class="Project-Box-Overlay"><h2>Splash</h2><p>Industries define the ideal selection for both wholesale and retail quantities of high quality</p></div></div>
        </div>
       </div>
       <div class="Horizontal-Section">
        <div class="Project-Wrapper">
          <div class="Project-Box" id="PJB5"><div class="Project-Box-Overlay"><h2>Splash</h2><p>Industries define the ideal selection for both wholesale and retail quantities of high quality</p></div></div>
          <div class="Project-Box" id="PJB6"><div class="Project-Box-Overlay"><h2>Splash</h2><p>Industries define the ideal selection for both wholesale and retail quantities of high quality</p></div></div>          
        </div>
       </div>        
     </div>

When a button is clicked, it should move to the next div. I achieved this using the following script;

   var inner_width = $('body').innerWidth();
   $('#next').on('click', function () {
      $('.Horizontal-Section').animate({'left': 'inner_width' +'px'});
   });

The issue I am encountering is that the scrolling behavior gets disoriented when resizing the browser, as I cannot obtain the correct page width.

Answer №1

To ensure proper resizing and positioning of elements, you must adjust the inner_width value accordingly.

Assuming that .Horizontal-Section has a CSS width of 100%.

var inner_width = $('body').innerWidth();

$('#next').on('click', function () {
    $('.Horizontal-Section').animate({'left': inner_width +'px'});
});

$(window).resize(function () {
    inner_width = $('body').innerWidth();
    $('.Horizontal-Section').css({'left': inner_width +'px'});
});

Answer №2

The issue is caused by failing to continuously check the browser width after the initial load. The script only checks once and assigns the value to a variable.

To solve this problem, you can use the following code snippet:

var innerWidth = $('body').innerWidth();
$(window).resize(function() {
  innerWidth = $('body').innerWidth();
});

Answer №3

If you want to ensure your code runs when the document is ready or when the window is resized, you can encapsulate it in a function and then call that function using (document).ready(); and (window).resize();

Here's an example of how you can achieve this:

JavaScript

<script>
 $(document).ready(func_name);
 $(window).resize(func_name);

 function func_name(){
  var inner_width = $('body').innerWidth();
   $('#next').on('click', function () {
      $('.Horizontal-Section').animate({'left': 'inner_width' +'px'});
   });
 }
</script>

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

The DiscordAPIError occurred due to the incorrect placement of required options in the form body. In order to resolve this issue, ensure that required

Hey everyone! So, I've been trying to solve an issue I encountered after posting my initial question without receiving any answers. I've searched extensively online, formatted the code, but unfortunately, I still haven't been able to find a ...

Installation of a cloned Parse server

I downloaded the Parse server repository from parse-server-example and set up MongoDB, as well as installed Node.js packages using npm install. However, when I try to start the app with npm start, I encounter this error in the terminal!! How can I resolve ...

Is there an issue with retrieving data from asp.cs through ajax?

Currently, I am in the process of learning asp.net and trying to access server data to populate a textbox with the retrieved information. public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) ...

javascript onload select the text in the textarea

Is there a way to have JavaScript automatically highlight the text inside a textarea when the page is loaded? ...

Pictures do not adhere to the maximum width set on their parent elements

When the max-width CSS style is set on the body tag and an image within the body surpasses this maximum width, the image does not adhere to the set limit. Instead of resizing, it simply overflows. Why does this happen? So, what is the solution to this pro ...

camera equipped with a three.js skybox

I need help with creating a skybox attached to the player camera. When the camera moves, the skybox also moves causing the texture to stretch. How can I prevent this stretching issue? Here is the code snippet I'm using: var textureCube = THREE.Image ...

Why is it unnecessary to include a callback when using a setState function from useState as an argument in useEffect?

While working with a function from my component in the useEffect arguments, it is recommended to write a callBack so that it is memorized and used as a dependency of the useEffect. Without this, there is a warning. However, when using the setState of use ...

What is the correct way to display or hide a button based on my specific situation?

Creating a 'show more' button for my app has presented me with a challenge. I am using a directive to handle actions when the user clicks on the read more button: (function(window, angular) { var app = angular.module('myApp'); ...

Updating the information within a Div element through an Ajax call

I'm working on developing a profile picture editor that includes a dropdown with two options: Update your Profile Picture If there is already a profile picture, the Delete option will be displayed; otherwise, it will remain hidden. Here is the ...

Building a visual bubble representation with Reactjs and D3

I am currently encountering an issue while attempting to create a bubble chart using React + D3. Although there are npm modules available for this solution, I am unable to implement them in the project I am working on. Moreover, the lack of examples demons ...

What are the steps to connecting incoming data to an Angular view utilizing a reactive form?

Hello, I am currently fetching data from an API and have successfully displayed the teacher values. However, I am unsure of how to utilize the incoming array values for "COURSES" in my Angular view. This is the response from the REST API: { "courses ...

jQuery functions are malfunctioning on Firefox, yet they are functioning properly on Chrome

Hey guys, can you take a look at this website using both Firefox and Chrome? I've noticed that jQuery doesn't seem to be working properly on Firefox. Any ideas why? ...

Creating HTML Textarea to Show Text with Newline and Spacing

I would like to have a pre-populated text area on my webpage that says: Hi, enter some text here And press submit:) This is just an example, I realize it may seem silly. However, when I put this directly into the HTML code, it shows up like this: Hi ...

How about connecting functions in JavaScript?

I'm looking to create a custom function that will add an item to my localStorage object. For example: alert(localStorage.getItem('names').addItem('Bill').getItem('names')); The initial method is getItem, which retrieves ...

Resolving CSS Objects

If two CSS classes share the same derived class, how does CSS determine the correct class to apply? Consider the following example: .ClassA.Left {} .ClassB.Left {} .Left {} Given that the class 'Left' can be assigned to multiple elements, how ...

Tips on resizing images within a container to maintain aspect ratio

I am trying to create a layout with a flex container containing 2 divs - one with an image that floats left, and the other with some paragraphs floating right. How can I make sure that the image scales alongside the paragraphs while maintaining its aspect ...

When resizing the window, the width change in JQuery always resets to 0

I've been trying to adjust the width of a div element when the window is resized, but for some reason, the width always ends up being 0 after the resize event. function resizeUploadField() { var uploadInputField = $('.input-append&apo ...

Error: The variable "email" is not defined

Hey there, I could really use some assistance as a struggling developer. I've been at it all day trying to resolve this issue with no luck. It should be a simple task of posting from my AddUsers class and storing it in my SQL database. The state upda ...

Encountering a TypeError indicating that the asterisk is not functioning as a proper function

Whenever I run my server.js file, an error keeps popping up: TypeError: routing is not a function This occurs in the following line of code: routing(app); In my routing.js file, the content looks like this: // JavaScript source code var friends = requ ...

Encountering a mysterious error while attempting to access and modify a value stored in a useState hook using the keydown

I've been attempting to create a simple animation on canvas using React.js, but I'm facing an issue with integrating my Keydown function with my useState. It seems that my useState value is not being defined properly, preventing me from changing ...