When the page first loads, the slider is responsive, but it does not adjust

I installed the Moving Boxes plugin and customized it to create a full-width image slider. While it works well when the page loads, I'm facing challenges with making it responsive on resize. It appears that the JS script sets fixed widths upon load, which overrides the percentage widths defined in the CSS.

I would appreciate any assistance since I am still learning JavaScript. Thank you in advance!

View Testing Site

The CSS code:

.slider {
    width: 100%;
}

.slider li {
    width: 80%;
}

.mb-wrapper {
    margin: 0 auto;
    position: relative;
    left: 0;
    width:100% !important;
    top: 0;
}

/* Panel Wrapper */
.mb-slider, .mb-scroll {
    width: 100%;
    height: 100%;
    overflow: hidden;
    margin: 0 auto;
    padding: 0;
    position: relative;
    left: 0;
    top: 0;
}

/*** Slider panel ***/
.mb-slider .mb-panel {
    margin: 0;
    display: block;
    cursor: pointer;
    float: left;
    list-style: none;
}

.mb-panel.current img {
    opacity:1;
    filter: alpha(opacity=100);
    -webkit-transition: all 0.2s;
    -moz-transition: all 0.2s;
    transition: all 0.2s;
}

/*** Inside the panel ***/
.mb-inside {
    width:90%;
    margin:0 auto;
}

.mb-inside img {
    width:100%;
    opacity:0.4;
    filter: alpha(opacity=40);
    -webkit-transition: all 1s;
    -moz-transition: all 1s;
    transition: all 1s;
}

.mb-inside * {
    max-width: 100%;
}

The JS code that handles the generation of widths is possibly causing the issue. Access the full JS file temporarily linked here.

// defaults
                base.$window = base.$el.parent(); // mb-scroll
                base.$wrap = base.$window.parent() // mb-wrapper
                    .prepend('<a class="mb-scrollButtons mb-left"></a>')
                    .append('<a class="mb-scrollButtons mb-right"></a><div class="mb-left-shadow"></div><div class="mb-right-shadow"></div>');

                base.$panels = base.$el.children().addClass('mb-panel');
                base.runTime = $('.mb-slider').index(base.$el) + 1; // Get index (run time) of this slider on the page
                base.regex = new RegExp('slider' + base.runTime + '=(\\d+)', 'i'); // hash tag regex

                base.initialized = false;
                base.currentlyMoving = false;
                base.curPanel = (o.initAnimation) ? 1 : base.getHash() || o.startPanel;
                // save original slider width
                base.width = (o.width) ? parseInt(o.width,10) : base.$el.width();
                // save panel width, o.panelWidth originally a fraction (0.5 of o.width) if defined, or get first panel width
                // now can be set after initialization to resize using fraction (value <= 2) or px (all values > 2)
                base.pWidth = (o.panelWidth) ? (o.panelWidth <=2 ? o.panelWidth * base.width : o.panelWidth) : base.$panels.eq(0).width();

In the JS file, there are specific options that can be adjusted. At the end of these options, it mentions the following:

// deprecated options - but still used to keep the plugin backwards compatible
// and allow resizing the overall width and panel width dynamically (i.e. on window resize)
// width        : '100%',       // overall width of movingBoxes 
// panelWidth   : 0.8        // current panel width adjusted to 80% of overall width

When I uncomment 'width' and 'panel-width' and provide values, the outcomes are unexpected. I can provide more details if needed. It's possible that some conflicts between my CSS and how these options are handled in the JS are causing the issue.

Answer №1

Here is a suggested code snippet to try:

$(function(){
    $('.slider').movingBoxes({
        startPanel   : 1,      // set the initial panel
        wrap         : false,  // do not wrap infinitely
        buildNav     : false,  // do not include navigation links
        navFormatter : function(){ return "&#9679;"; }
    });
});

$(window).on('resize', function() {
    $('.slider').movingBoxes();
});

This code initializes a plugin called movingBoxes. While it should work based on theoretical analysis, you may need to tweak parameters passed to the movingBoxes method for optimal functionality.

$.fn.movingBoxes = function(options, callback, flag){
    var mb;
    return this.each(function(){
        mb = $(this).data('movingBoxes');
        
        if ((typeof(options)).match('object|undefined')){
            if (mb && options instanceof $ && options.length) {
                mb.change(options, callback, flag);
            } else if (mb) {
                mb.update(callback, flag);
            } else {
                (new $.movingBoxes(this, options));
            }
        } else if (mb) {
            mb.change(options, callback, flag);
        }
    });
};

The issue highlighted here pertains to potential duplication of movingBoxes instances. Upon resizing the window, it's important to ensure that only one instance is active to avoid unexpected behavior. According to comments in the code, multiple initializations are guarded against to maintain stability.

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

Tips on how to retrieve the value of a number-type input within a custom attribute directive

I have successfully implemented this code in IE 11, but now we are looking to transition away from IE11 and address some of the issues that have arisen. <input type="number" evaluate-input="model.personalNumber" ng-model="model ...

Encountering an unexpected token error in Vercel during deployment, even though the code runs smoothly in the

I'm facing an issue with a SyntaxError: Unexpected token '??='. I am not sure how to resolve it, so any help would be greatly appreciated. Thank you in advance. SyntaxError: Unexpected token '??=' at wrapSafe (internal/modules ...

Upon submission in Vue, the data variable becomes undefined

I set isError to false in the data, but when there is an error from Laravel, I receive a 422 error. I want to then set isError to true, but when I do, I get an error in the console saying that isError is undefined even though it has been defined. What coul ...

Storing files in DynamoDB using Reactjs is a convenient and efficient way

Is there a way to store resume files in an existing DynamoDB table that currently stores name and email information? I have attempted to do so using React's AWS package with the following code: <input name="my_file" onChange={e => upd ...

Is it possible to make an element draggable after it has been prep

Seeking assistance with making a notification draggable when added to a webpage. The notifications are housed in a parent div named notification_holder Here is the structure: <div class="notification_holder"> <div class="container"><b ...

Adjusting the size of div content without changing its dimensions

I'm in search of a solution for resizing the contents within a fixed width and height div. Currently, my div looks like this: <div id="editor_preview" style="width:360px !important; color:gray; ...

What is the best way to deliver data from the main Vue instance to components that are being utilized by vue-router?

Currently, I am utilizing vue-router within a single HTML file instead of using separate file components. I am encountering an issue where I am unsure how to pass the data stored in the Vue data object to the component when loading it for a route. Oddly e ...

jQuery fails to apply a class if the input fields are not empty

I am currently working on a function that displays a login button only when both input fields are not empty. However, for some reason, jQuery seems to be giving me trouble with this task. Despite checking and ensuring that I am using the correct and updat ...

Error encountered: `npm ERR! code E503`

While attempting to execute npm install on my project, which was cloned from my GitHub repository, I encountered the following error: npm ERR! code E503 npm ERR! 503 Maximum threads for service reached: fs-extra@https://registry.npmjs.org/fs-extra/-/fs-ex ...

How can this be written in a shorter amount of CSS code?

Seeking a more optimized solution, I am attempting to write CSS transitions for five different elements (medals/badges). Is there a way to achieve the same effect with less code? Below is the current code: #nav .badges { float:left; height: 173px; width: ...

Retrieve the values of elements

Is there a reliable way to retrieve an element's clientWidth and scrollWidth? I've tried using getCssValue, but it doesn't seem to work. $('.grid-header-col .title').getCssValue('scrollWidth') ...

Emberjs promises are enhanced with a filtering feature

My goal is to develop a search functionality using a JSON API. After following tutorials and successfully implementing it with provided examples: export default Ember.ArrayController.extend({ searchText: null, searchResults: function(){ ...

Merging text and a JSON object to retrieve the information

Having some trouble with a JSON object and retrieving values. This is the syntax that works for getting the data I need. dataJSON.companies[0].fields.Internet.length I want to dynamically evaluate the object using a string variable, like this... var me ...

Tips for activating a function when the sidebar menu is opened in Ionic 2

How can I trigger a function when the SideMenu is open in Ionic 2? I came across this link here for Ionic-1, but I'm wondering how to accomplish this in Ionic 2. Any help would be appreciated. Thanks! ...

Modifying Data with MomentJS when Saving to Different Variable

After attempting to assign a moment to a new variable, I noticed that the value changes on its own without any modification from my end. Despite various attempts such as forcing the use of UTC and adjusting timezones, the value continues to change unexpec ...

retrieving dynamic data from an HTML form to JavaScript

Currently, I am dynamically adding elements using JavaScript. The count is defined and increases by one. <span style="margin-left:10px;">File Type : <select name="select_type_'+count+'" > <option value="select">Select</optio ...

Is there a way to use a less mixin or selector to adjust the position depending on the sibling

Currently, I am working on adjusting the position of multiple sibling divs depending on their order. Although they are all currently set to position: absolute, this may change. Each div is a few hundred pixels tall, but I want them to overlap in such a wa ...

Ways to eliminate double slashes from URL in Next Js. Techniques for intercepting and editing a request on the server side using getServerSideProps

Looking to manipulate a server-side request - how can this be accomplished? http://localhost//example///author/admin/// The desired output is: http://localhost/example/author/admin/ In Next Js, how can duplicate slashes in a URL be eliminated and req ...

Discovering Unconventional Columns Through Sharepoint REST Api Filtration

I am working on recreating SharePoint's front end in my app and want to add columns to my table just like a user would in SP. The challenge I am facing is determining which columns were custom generated by the user rather than standard ones. Although ...

Is there a way to trigger a Modal to open upon clicking a custom-designed button in MaterialUI?

In my React and Material-UI project, I am attempting to trigger a Modal to open using a custom button. The button also performs other functions, which is why it's important for me to combine the "Modal Opening" action with these additional functionali ...