The functionality to move forward and backward in Modal Bootsrap seems to be malfunctioning

I am in need of assistance as I have encountered a major issue that has halted my work progress for several days. My goal is to implement a feature that allows users to navigate between different days both forwards and backwards. While the functionality itself is working fine, the main problem I am facing is related to displaying these days within a modal. Unfortunately, when the days are shown in the modal, the navigation between them does not function correctly.

If you would like to take a look at the complete code, it can be found here: Jquery, Css Moving between week days with previous next buttons - Carousel

Modal:

 <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-body">
            <!-- Indicators -->
            <div class="day-picker">
                <button type="button" class="day-picker-nav prev">
                    <svg width="12" height="14" xmlns="http://www.w3.org/2000/svg" transform="rotate(180)">
                        <path class="svg-stroke-container" stroke-linejoin="round" stroke-linecap="round" fill-rule="evenodd" fill="none" stroke="#D70F64" d="m3.5,1.5l5,5.5l-5,5.5"></path>
                    </svg>
                </button>

                <div class="day-picker-overflow">
                    <ul class="day-picker-week">
                        @foreach($calender_days as $key => $calender_day)

                        <li>
                            <label class="day-picker-day">
                                <input type="radio" value="" name="day-picker" />
                                <span class="day-value button-toggle">{{$calender_day['day_text']}} <span class="day-number">{{(int)$calender_day['day_date']}}</span></span>
                            </label>
                        </li>
                        @endforeach
                    </ul>
                </div>

                <button type="button" class="day-picker-nav next">
                    <svg width="12" height="14" xmlns="http://www.w3.org/2000/svg" transform="rotate(0)">
                        <path class="svg-stroke-container" stroke-linejoin="round" stroke-linecap="round" fill-rule="evenodd" fill="none" stroke="#D70F64" d="m3.5,1.5l5,5.5l-5,5.5"></path>
                    </svg>
                </button>
            </div>
        </div>
    </div>
</div>

Jquery:

    $(".day-picker").each(function() {
    const $week = $(".day-picker-week", this);
    const $days = $(".day-value", this);
    const $prev = $(".prev", this);
    const $next = $(".next", this);

    const visible = Math.floor($week.width() / $days.outerWidth(true));
    const perc = 100 / visible;
    const tot = $days.length;
    const steps = tot - visible;
    let c = 0;

    const anim = () => {
      $week.css({transform: `translateX(${-perc*c}%)`});
    }

    $prev.on("click", function() {
      c -= 1;
      if (c < 0) c = steps;
      anim();
    });

    $next.on("click", function() {
      c += 1;
      if (c > steps) c = 0;
      anim();
    });
  });

Answer №1

The issue arose because the width of $(".day-picker").width() was zero prior to displaying the modal, resulting in the value of perc becoming infinite.

Therefore, it is necessary to set their values after the modal has been shown using the shown.bs.modal event.

To enhance your script, make the following adjustments:

let visible,
    perc,
    steps,
    c = 0;
const tot = $days.length;

$('#myModal').on('shown.bs.modal', function () {
    visible = Math.floor($week.width() / $days.outerWidth(true));
    perc = 100 / visible;
    steps = tot - visible;
});

You can utilize code snippets as shown below:

$(".day-picker").each(function () {
    const $week = $(".day-picker-week", this);
    const $days = $(".day-value", this);
    const $prev = $(".prev", this);
    const $next = $(".next", this);

    let visible,
        perc,
        steps,
        c = 0;
    const tot = $days.length;

    $('#myModal').on('shown.bs.modal', function () {
        visible = Math.floor($week.width() / $days.outerWidth(true));
        perc = 100 / visible;
        steps = tot - visible;
    });

    const anim = () => {
        $week.css({ transform: `translateX(${-perc * c}%)` });
    }

    $prev.on("click", function () {
        c -= 1;
        if (c < 0) c = steps;
        anim();
    });

    $next.on("click", function () {
        c += 1;
        if (c > steps) c = 0;
        anim();
    });

});
/* QuickReset */

* {
    margin: 0;
    box-sizing: border-box;
}

body {
    font: 14px/1.4 sans-serif;
}

/* DayPicker */

.day-picker {

    --day-width: 70px;
    --day-spacing: 5px;
    --days-visible: 4;

    display: inline-flex;
}

.day-picker-overflow {
    overflow: hidden;
    width: calc(var(--day-width) * var(--days-visible) + var(--day-spacing) * var(--days-visible) * 2);
}

.day-picker-week {
    list-style: none;
    display: flex;
    padding: 0;
    transition: transform 0.4s;
}

[name="day-picker"] {
    /* Hide radio buttons */
    position: absolute;
    width: 1px;
    height: 1px;
    opacity: 0;
    clip: rect(1px, 1px, 1px, 1px);
}

.day-value {
    display: block;
    color: #d85c54;
    cursor: pointer;
    user-select: none;
    margin: 0 var(--day-spacing);
    width: var(--day-width);
    text-align: center;
    padding: 20px 0;
    box-shadow: inset 0 0 0 1px currentColor;
    transition: 0.3s;
}

[name="day-picker"]:checked~.day-value {
    color: #000;
    font-weight: bold;
    box-shadow: inset 0 0 0 2px currentColor;
}

.day-number {
    display: block;
}

.day-picker-nav {
    cursor: pointer;
    display: block;
    min-height: 100%;
    border: 0;
    background: transparent;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>

<body>
    <button type="button" class="btn btn-primary" data-target="#myModal" data-toggle="modal">Open modal</button>

    <div class="day-picker">
        <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-body">
                        <!-- Indicators -->
                        <div class="day-picker">
                            <button type="button" class="day-picker-nav prev">
                                <svg width="12" height="14" xmlns="http://www.w3.org/2000/svg" transform="rotate(180)">
                                    <path class="svg-stroke-container" stroke-linejoin="round" stroke-linecap="round" fill-rule="evenodd" fill="none" stroke="#D70F64" d="m3.5,1.5l5,5.5l-5,5.5"></path>
                                </svg>
                            </button>
            
                            <div class="day-picker-overflow">
                                <ul class="day-picker-week">
                                    <li>
                                        <label class="day-picker-day">
                                            <input type="radio" value="" name="day-picker" />
                                            <span class="day-value">SAT<span class="day-number">11</span></span>
                                        </label>
                                    </li>
                                    <li>
                                        <label class="day-picker-day">
                                            <input type="radio" value="" name="day-picker" />
                                            <span class="day-value">SUN<span class="day-number">12</span></span>
                                        </label>
                                    </li>
                                    <li>
                                        <label class="day-picker-day">
                                            <input type="radio" value="" name="day-picker" />
                                            <span class="day-value">MON<span class="day-number">13</span></span>
                                        </label>
                                    </li>
                                    <li>
                                        <label class="day-picker-day">
                                            <input type="radio" value="" name="day-picker" />
                                            <span class="day-value">TUE<span class="day-number">14</span></span>
                                        </label>
                                    </li>
                                    <li>
                                        <label class="day-picker-day">
                                            <input type="radio" value="" name="day-picker" />
                                            <span class="day-value">WED <span class="day-number">15</span></span>
                                        </label>
                                    </li>
                                    <li>
                                        <label class="day-picker-day">
                                            <input type="radio" value="" name="day-picker" />
                                            <span class="day-value">THU <span class="day-number">16</span></span>
                                        </label>
                                    </li>
                                    <li>
                                        <label class="day-picker-day">
                                            <input type="radio" value="" name="day-picker" />
                                            <span class="day-value">FRI <span class="day-number">17</span></span>
                                        </label>
                                    </li>
                                </ul>
                            </div>
            
                            <button type="button" class="day-picker-nav next">
                                <svg width="12" height="14" xmlns="http://www.w3.org/2000/svg" transform="rotate(0)">
                                    <path class="svg-stroke-container" stroke-linejoin="round" stroke-linecap="round" fill-rule="evenodd" fill="none" stroke="#D70F64" d="m3.5,1.5l5,5.5l-5,5.5"></path>
                                </svg>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
    </div>


    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="67170817170215490d1427564956514957">[email protected]</a>/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</body>

</html>

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

Enhance your viewing experience with the Zoom feature that activates when

I recently noticed on that I am able to zoom/enlarge a photo by clicking on it. Is there a way for me to incorporate this feature without purchasing the entire theme? While I understand the theme is designed for purchase, I only need this specific functi ...

"Encountered a Json error with a bizarre character causing the string

After extracting some json data from a website, I encountered an issue when trying to parse it using vscode. I kept getting an 'unexpected end of string' error on the "content" line: Here is the json: { "name": "Anna Vergnas", "date" ...

Perform encryption and decryption of a JSON file on separate webpages

Situation : Is there a way to encode JSON data in the getuser.php page and then decode it in index.php? In my getuser.php file, I use echo (json_encode($data)); which produces the following example output: { "id": 2, "username": "Teeto", "sur ...

Redux: One container for many components

I am new to React and Redux, and I am currently working on a project where I am unsure of the best practices and technical solutions. I am following Dan Abramov's definitions of "smart" and "dumb" components which can be found here. The component I a ...

html transparent div element

I'm encountering an issue with this specific code snippet: <li class="nav-item dropdown" id="noti_Container" > <div id="noti_Counter" style="opacity: 1; top: -2px;"></div> <a style=" ...

Show a persistent header once you scroll past a certain point using Bootstrap

Utilizing Bootstrap affix property to reveal a header after scrolling down by 100px has been successful for me. However, I encountered an issue when trying to set the opacity property to 0.0001, it works as expected. But when setting it to 0 or changing di ...

What is the best way to insert horizontal padding into each line of a single sentence that is wrapped on multiple lines

Below is the code snippet I am working with: <div><p><span>... highlighted text ...</span></p><p>Chapter info</p></div> Here is a screenshot of how it currently appears: I am looking for a way to add paddi ...

Discover the Practical Utility of Maps beyond Hash Tables in Everyday Life

I am currently attempting to explain the concept of Maps (also known as hash tables or dictionaries) to someone who is a beginner in programming. While most people are familiar with the concepts of Arrays (a list of things) and Sets (a bag of things), I ...

Utilize a Web Api controller to authenticate and verify the data input in

Currently, I am working on a web API application that includes the following form: <form id="editForm"> <input id="editid" type="hidden" name="id" /> <p><label>Numéro cnss </label&g ...

What could be the reason why this function in jQuery is not functioning properly?

I am trying to duplicate the span element inside the `test` element using the .clone method. It seems like it works as expected. However, when I try to use .html in a `.click` function, it doesn't work. Can someone point out where I went wrong and sug ...

Animating HTML 5 canvas with keydown events

As a newcomer to programming, I've been experimenting with HTML 5 and canvas. My goal is to make a simple rectangle move when a key is pressed, but I'm facing difficulties in achieving this. I tried following the instructions provided in this gui ...

Exploring the Time Interval Between Sending GET and POST Requests in Node.js and Express

I'm currently in the process of creating a quiz platform with Node/Express. Is there a way to guarantee that users complete the quiz within a specific timeframe without utilizing client-side javascript? For example, if the quiz is set for 10 minutes, ...

Navigation that sticks and changes upon hovering over div elements

Just delving into the world of jQuery and JS, so I appreciate your patience:) Currently, I have a sticky navigation bar positioned at the top of my webpage that links to different sections of content below. I am looking to create an effect where the corr ...

A guide on extracting specific text from a div class

<div class="col_5"> <br> <i class="phone"> :: Before </i> 0212 / 897645 <br> <i class="print"> ...

Stop the creation of new div elements once the minimum height has been reached or when text is past

Here is the HTML code I am working with: <div id='parent' align='right' dir='rtl' style=padding:0px;margin:0px;font-weight:bold;width:300px;height:auto;min-height:300px; "'<div align='right' dir='rt ...

Tips for implementing a custom filter in an AngularJS JavaScript controller

Can anyone help me with creating a custom filter in an AngularJS JavaScript controller? I need to be able to search for items in an array called segments by their SegmentId. The filter should iterate through the segments array and return the segment that ...

When trying to use bootbox.confirm within a dynamically loaded AJAX div, the modal unexpectedly opens and

I have implemented bootbox into my project, which was downloaded from . user_update.php is being loaded in a div within users.php using ajax functionality. Within user_update.php, there is a JavaScript function called validateForm(). Right after the functi ...

Determine the Number of Table Columns Using jQuery

I'm curious, with jQuery how can one determine the number of columns in a table? <script> alert($('table').columnCount()); </script> <table> <tr> <td>spans one column</td> <td ...

reveal a hidden div by sliding it during an onclick action

My PHP while loop code is as follows: while (...($...)){ $convid = $row['ID']; echo" <button onclick='getconvo($convid)'>open</button> <div class="convowrap"></div> "; } Here is the correspond ...

Exploring HTML5 Canvas - Focusing on a Specific Point

There have been discussions on this topic before, like this particular one. I followed the suggestion from that discussion and it did the trick. However, I'm still puzzled about the reasoning behind why it works. Here's an illustration: Imagine ...