Display all dates within a specific range using the indexOf method

I am working on creating a datepicker in vue3. As part of this, I want the days between two selected dates to be highlighted when hovered over. I have attempted to achieve this using the "indexOf" method, but unfortunately, I am not getting the desired result.

<div
            v-for="date in daysInMonth(currentYear, currentMonthInNumber, firstDay, lastDay)"
            :key="date"
            ref="date"
            class="day"
            :class="{ active: date === firstDay || date === lastDay, between: between.indexOf(date)}"
            @click="choosingDates(date)" > {{ date }} </div>
<script>
      data() {
        return {
          firstDay: false,
          between: [],
          lastDay: false,
          firstDaySelected: false,
        };
      },
      methods: {
        choosingDates(date) {
          if (this.firstDay === false) {
            this.firstDay = date;
          } else if (this.lastDay === false) {
            this.lastDay = date;;
          }
        },

After implementing this code, I noticed that all days of the month are being considered as "between" (css styles are written). :class="{ between: between.indexOf(date)} " I'm not sure where I may have gone wrong with this. Can you provide any guidance?

Answer №1

Check out this code snippet for a datepicker component:

<template>
  <div class="datepicker">
    <div class="month-header">
      <i class="prev-month" @click="prevMonth"></i>
      {{ currentMonth }} {{ currentYear }}
      <i class="next-month" @click="nextMonth"></i>
    </div>
    <div class="weekdays">
      <div class="weekday" v-for="weekday in weekdays" :key="weekday">
        {{ weekday }}
      </div>
    </div>
    <div class="days">
      <div
        v-for="date in daysInMonth(
          currentYear,
          currentMonthInNumber,
          firstDay,
          lastDay
        )"
        :key="date"
        class="day"
        :class="{
          active: date === firstDay || date === lastDay,
          between: between.includes(date),
        }"
        @click="chooseDate(date)"
      >
        {{ date }}
      </div>
    </div>
    {{ between }}
  </div>
</template>

<script>
export default {
  data() {
    return {
      weekdays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
      months: [
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December",
      ],
      currentMonth: "",
      currentMonthInNumber: "",
      currentYear: "",
      firstDay: false,
      between: [],
      lastDay: false,
    };
  },
  mounted() {
    const date = new Date();
    this.currentMonth = this.months[date.getMonth()];
    this.currentMonthInNumber = date.getMonth();
    this.currentYear = date.getFullYear();
  },
  methods: {
    prevMonth() {
      this.currentMonthInNumber--;
      if (this.currentMonthInNumber < 0) {
        this.currentMonthInNumber = 11;
        this.currentYear--;
      }
      this.currentMonth = this.months[this.currentMonthInNumber];
    },
    nextMonth() {
      this.currentMonthInNumber++;
      if (this.currentMonthInNumber > 11) {
        this.currentMonthInNumber = 0;
        this.currentYear++;
      }
      this.currentMonth = this.months[this.currentMonthInNumber];
    },
    daysInMonth(year, month, firstDay, lastDay) {
      let date = new Date(year, month, 1);
      let days = [];
      while (date.getMonth() === month) {
        days.push(date.getDate());
        date.setDate(date.getDate() + 1);
      }
      return days;
    },
    chooseDate(date) {
      if (this.firstDay === false) {
        this.firstDay = date;
      } else if (this.lastDay === false) {
        this.lastDay = date;
        this.setBetween();
      } else {
        this.firstDay = date;
        this.lastDay = false;
        this.between = [];
      }
    },
    setBetween() {
      if (this.firstDay > this.lastDay) {
        [this.firstDay, this.lastDay] = [this.lastDay, this.firstDay];
      }
      let date = new Date(
        this.currentYear,
        this.currentMonthInNumber,
        this.firstDay
      );
      while (date.getDate() <= this.lastDay) {
        this.between.push(date.getDate());
        date.setDate(date.getDate() + 1);
      }
    },
  },
};
</script>

<style scoped>
.datepicker {
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  text-align: center;
}

.month-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.prev-month,
.next-month {
  cursor: pointer;
}

.weekdays {
  display: flex;
}

.weekday {
  flex: 1;
  font-weight: bold;
  padding: 10px 0;
}

.days {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  grid-gap: 10px;
  margin-top: 20px;
}

.day {
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 5px;
  cursor: pointer;
  height: 40px;
  line-height: 40px;
  text-align: center;
  user-select: none;
}

.day.active {
  background-color: #3c8dbc;
  color: #fff;
}

.day.between {
  background-color: #ddd;
}
</style>

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

Showing dynamic html based on conditions using Knockout

I am working with a knockout observable array that contains both audits and comments. After receiving the data from the server, I have sorted the array based on the timestamp of the objects. My goal is to display html conditionally based on the type of ac ...

What is the best way to locate all mesh faces that are being lit up by a SpotLight

I am working with a THREE.Mesh that consists of a THREE.BufferGeometry containing "position" and "normal" THREE.BufferAttributes. This mesh is being lit by a THREE.SpotLight (which is a cone-shaped light source). Is there a method to ...

Is there a way for me to determine if an image created with Image() has had its source modified?

Is there a way to track changes in the src attribute of images created using the Image constructor on a webpage without needing the image to be fully loaded? I have attempted to override the Image.onload method, but it does not log anything: Image.prototy ...

Injecting resolve into Angular controller and encountering undefined value in logging operation

My setup involves the following: .state('posts', { url: '/posts/{id}', templateUrl: 'posts.html', controller: 'postsController as postsCtrl', resolve: { post: getSinglePostWrapper ...

Detecting the specific button that was selected with PHP

I am in the process of developing a website for a production company where, upon clicking on a director's name from the menu, all other menu items disappear and only the selected director's biography and work are displayed. My current challenge ...

Checking the submission text field with Javascript is being confirmed

It seems I've made a small mistake somewhere, and I would appreciate it if someone could help me find it. I'm attempting to validate a postcode in a form field once it's been entered. I've tried similar code in PHP, and it works fine, b ...

Show picture in web browser without the file extension

Is there a way to display an image in the browser without the file extension, similar to how Google and Unsplash do it? For example: Or like this: ...

Lock the initial column in an HTML table

Hey there! I've been trying to freeze the first column of my HTML table, and while I managed to do so after a few attempts, I encountered an issue. When I scroll the table horizontally, the columns on the left seem to overlap with the first column, an ...

Header fixed vertically

I am currently working on a webpage with a minimum width requirement of 1124px. This means that whenever the browser window is smaller than that, the content of the page needs to be scrolled horizontally instead of smoothly transitioning into a responsive ...

PHP AJAX Serial Port Text Input Command

Recently, I've been delving into the world of PHP and AJAX. Despite being a newcomer, I've managed to grasp some basic concepts over the past few weeks. Along the way, I've relied on various posts from this platform for guidance, so when a p ...

Binding Vue MultiSelect Checkboxes to Data Model

The data properties of the multi-select component are not updating when changed. The checkboxes are not being updated on the front-end. Expected Behavior: The checkboxes should get ticked when clicked. Link to code: https://jsfiddle.net/bzqd19nt/3/ < ...

Displaying a PHP variable within Leaflet.js on an OpenStreetMap using JavaScript

I am currently working on integrating an openstreetmaps set to a specific latitude and longitude using leafletjs. For the custom fields from the backend, I am retrieving them like this : $longitude = the_field('longitude','option'); $ ...

Retaining user interactions through cookies

Currently developing a notification for users on the homepage regarding the use of cookies on this site. I aim to provide an option for users to dismiss the message, with the browser remembering their choice so it does not reappear upon reloading the page ...

Differentiate the items within a list containing identical divs using JavaScript

Currently, I am expanding my knowledge in HTML, CSS, and JS by incorporating Angular and JQuery. In one of my projects, there is a div labeled "eventBoxes" where multiple divs known as "eventBox" can be added. I have created a template for the eventBox i ...

Learn how to navigate to another page after successful AJAX request handling

Upon deletion of a file, I am attempting to redirect to the admin_dashboard page using ajax. I have a function called in a button tag, and upon successful response, I want to redirect to the next page. While the value gets deleted successfully, I am facing ...

Tips for organizing vue.js components within laravel blade templates

Currently, I am delving into the world of vue.js while working on a laravel/vue.js Ad placement application. The way I have set up my app is by having the landing page (a laravel blade view) feature a prominent banner introducing the app, followed by a l ...

Eliminate any unnecessary zeros at the end of a number within AngularJS interpolation

Although there are solutions available for plain JavaScript code, unfortunately they are not applicable in this particular scenario. I have a table that needs to be populated with data. The current code snippet is as follows: <tr ng-repeat="rows in $ ...

Is the user currently browsing the 'Home screen webpage' or using the Safari browser?

In JavaScript, is there a method to determine if the user has accessed the website from their home screen after adding it to their home screen, or if they are browsing via Safari as usual? ...

The canvas is responsive to keyboard commands, however, the image remains stationary and unaffected

As I delved into the basics, incorporating canvas, CSS, and JavaScript, a question arose: should the image be housed in the HTML or the JavaScript code? Following this, I added a background color to the canvas and defined properties of the canvas in JavaSc ...

Conceal a div element dynamically when clicking on another div

<script type="text/javascript"> function displayBookInfo(str) { if (str == "") { document.getElementById("more-info").innerHTML=""; return; } if (window.XMLHttpRequest) { // code for m ...