rely on a fresh event starting at one

Despite my limited knowledge in javascript, I managed to create a simple js calendar that I am quite proud of. However, I have been facing a challenge for the past few days.

You can view my calendar here: https://jsfiddle.net/ck3nsemz/

The issue I'm encountering is related to sorting the calendar events so that multi-day events are displayed at the same height. To address this, I implemented the "days[x]["grid"]" variable.

If you review my calendar, you'll notice that the "party" event correctly uses the days[x]["grid"], but the "new" event is assigned grid:3 when it should actually be grid:1.

I hope my problem is clear - the "new" event should have grid:1!

.grid1, grid2, grid2 {
  position:relative;
}
.grid1 {
  top:0px;
}
.grid2 {
  top:20px;
}...

Answer №1

To start off, here's a friendly suggestion regarding how to fill the objects. Instead of using sub arrays, consider defining objects directly. For instance:

days[0] = {
    start: "9-3",
    title: "Fritz",
    dur: 1
};

Another approach would be to define an object and then create the array from it

function Event(start, title, duration){
    this.start = start;
    this.title = title;
    this.dur = duration;
}

var days = [
    new Event('9-3', 'Fritz', 1),
    new Event('9-5', 'huhu', 3),
    new Event('9-5', 'dieter', 1),
    new Event('9-7', 'party', 8),
    new Event('9-8', 'new', 2),       
];

This method streamlines the initialization process, and interestingly, your current code will still function properly when using these objects (as JavaScript automatically matches key names to property names in the objects)

Going a step further, the object definition could handle date parsing and determine the end time. This way, any other necessary values can be stored as well.

Returning to the main issue at hand, instead of immediately adding the events to the days, we need to identify the grids that are already in use. One way to do this is by first determining all the days with assigned grids. To accomplish this without affecting the days variable outside its scope, it's best to first filter out all events for a specific day, followed by collecting the events that already have a grid assigned. The filter function in JavaScript (for arrays) comes in handy for this task:

var events = days.filter(function(e){ return e.start <= d && e.end >= d;});
if(events.length){
    var grid = 1,
        gridstaken = events.filter(function(e){return e.grid}),
        getfreegrid = gridstaken.length ?
            function(){while(gridstaken.some(function(e){return e.grid===grid;})){grid++;}return grid++;} 
            :  function(){return grid++;}; 
    //etc

FIDDLE / FIDDLE2

In the first filter, an 'end' property is utilized, which was added in the example code but can also be achieved in your original code by comparing start and incrementing accordingly. In the example fiddle, I've demonstrated moving much of the logic to the Event object to showcase the benefits of this approach, although you can selectively incorporate parts into your existing code. The second filter generates an array of events with an allocated grid. Lastly, the getfreegrid function increments the grid index if it's already taken. Additionally, I've included a skip mechanism if no grids are assigned, though this is optional.

edit As seen in the initial example, the code primarily modifies the text of 'grid' without specifically handling positioning. For an illustration involving positioning, refer to this link: click here. It features an encapsulating div with relative positioning, sets the CSS of the title class to absolute, and manipulates the style.top attribute during addition for positioning. While not the most conventional CSS approach, it serves the intended purpose effectively.

A quick side note: When dealing with overlapping months, ensure that the previous month has been added for the above code to function correctly.

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 the method for importing .scss files throughout a Next.js application?

I'm looking to transform my React app into a Next.js app. In the current React setup, I have .scss CSS files being imported in various components. However, once I transfer the code to a Next.js environment, I encounter an error: Global CSS cannot be ...

Adjusting the amount of rows and columns in a fluid manner with CSS grid (updated)

After conducting my research, it seems that the most effective way to set the final value of a CSS grid is either by directly specifying it or by creating/manipulating the css :root value. A similar query was previously raised here, although the answers p ...

Utilizing Angular JS to ensure services are universally accessible across controllers and views

Imagine we have a service like this: myApp.factory('FooService', function () { ... Now, from a controller, the code would look something like this: myApp.controller('FooCtrl', ['$scope', 'FooService', function ($s ...

How to automatically disable a button in reactjs when the input field is blank

I have a component called Dynamic Form that includes input fields. The challenge I am facing is how to disable the submit button when these input fields are empty, although the validateResult function fails to return false. import cn from "classname ...

Utilizing a class instance as a static property - a step-by-step guide

In my code, I am trying to establish a static property for a class called OuterClass. This static property should hold an instance of another class named InnerClass. The InnerClass definition consists of a property and a function as shown below: // InnerC ...

Permanently removing artwork from the Canvas

I am facing an issue with my canvas drawing function. Whenever I clear the drawings on the background image by clicking a button, the old drawings reappear when I try to draw again. How can I permanently delete the cleared drawings so that I can start fr ...

Incorporating external JavaScript into a Rails application

Having trouble with the syntax on this simple problem. Struggling to find examples of externally linked files, all solutions online involve storing a local copy instead. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" typ ...

Establishing a connection between HTML and MySQL database

I've been researching how to create a login system on my HTML page. From what I've learned, it seems I need to use an intermediate script to allow my HTML access to the database. So, I've created a PHP page that verifies the username and pas ...

Using template literals with Optional chaining in Javascript does not yield the expected results

Trying to implement template literal with optional chaining. type Item = { itemId:number, price: number}; type ItemType = { A:Item, B:Item }; const data : ItemType = { A:{itemId:1, price:2}, B:{itemId:2, price:3} }; let key = `data?.${variable}?.ite ...

Transitioning from the traditional LeftNav menu style to the more versatile composability feature using Reactjs with Material-ui

Hey there, I'm facing a bit of confusion while trying to create a LeftNav menu using material-ui. I recently joined this project and updated reactjs and material-ui. Unfortunately, many things related to LeftNav in material-ui have been deprecated, ...

Date Range Selection Widget malfunctioning when used within a popup modal

Having trouble with integrating the rsuite daterangepicker and antd's daterangepicker into a React Material UI Dialog/Modal. The date picker popup seems to either not show up or appear outside of the modal window. Take a look at the image below: Clic ...

Assign a variable to a dynamic model within an AngularJS scope

I am facing an issue with scope closure. ... function(scope) { ... }); Within the scope, I need to achieve the following: $scope.favoriteTitle = 'some value' The challenge is that favoriteTitle cannot be static. It needs to be generated d ...

Align labels on top and inputs at the bottom using Bootstrap

I'm facing an issue with alignment in my form using Bootstrap 4.4. Whenever a select element is included, it disrupts the layout by breaking the alignment of labels and inputs on the same row. Is there a way to always keep the labels at the top and t ...

Employ the express platform to refrain from responding to particular inquiries

Is there a way for my server to not respond at all when receiving a specific user-agent in the request header, while still serving HTML normally for other browsers? I tried different methods like using res.status(404).end() and res.destroy(), but they did ...

Scale first, then drag and drop to fix a faulty registration

I'm currently working on a project that involves dragging and dropping the correct items onto a technical drawing, such as a motherboard. The user is presented with pictures of components like CPUs or DDR memory and must drag these items to their corr ...

Combining Option Value and Name Selection Using React Hooks

Currently, I am facing a situation where I need to retrieve two different values (item.id and item.name) to set the State when selecting an item from my dropdown menu. Right now, I am only able to do this for one value (item.id). Is it possible to achieve ...

Learn how to increase a value with each dynamically clicked button in JavaScript

Whenever I try to increment the value by clicking the like button, it seems to be increasing but not in sync with the actual button count. How can I fix this issue? index.html <div class="row"> <div class="col-md-4"> ...

Having trouble getting static serving to work on Express.js when custom middleware is added

Seeking assistance with creating a middleware for my express js website to incorporate subdomains and serve static image, css, and js files. While my HTML pages load properly, I encounter long page load times and the javascript files fail to load. Any gui ...

Ensure that you do not display the result until all Ajax calls have finished processing

When faced with a challenging problem, I persist through multiple attempts and seek your assistance in finding a solution. My current goal is to populate a table with the number of viewers for a specific streamer using the Twitch API. To achieve this, I ...

Determining the largest range possible in a sorted array of integers

I need help with a JavaScript implementation for the following challenge. Imagine we have a sorted array: [1,2,5,9,10,12,20,21,22,23,24,26,27] I want to find the length of the longest consecutive range that increments by 1 without duplicates. In the ...