Tabit.js multiple instances on same page with className

Using a tabs library called tabit.js. It initialises fine with ID and one tab but I’ve got multiple tabs now on one page and finding it difficult to make this work dynanically without fixing an ID for both. Thought about doing it as follows with each:

$('.tabs').each(function () {
  const element = $(this)
  const options = {
    buttonSelector: '[data-target]',
    buttonActiveClass: 'is-active',
    contentSelector: '[data-content]',
    buttonAttribute: 'data-target',
    contentAttribute: 'data-content',
    contentActiveClass: 'is-active',
  }
  if (element) {
    /* eslint-disable no-new */
    new Tabit(element, options)
  }
})

But Tabit implies it does not find a element initialise by outputting:

Uncaught TypeError: new Tabit requires a DOM element as its first
argument.

View JSFiddle here: https://jsfiddle.net/e8y0d5um/7/

Any ideas how to make this work? Finding it very difficult to find any solutions of multiple tabs on the same page that don’t have a unique ID.

Gatsby’s StaticQuery renders nothing

I’m able to log the data in the console but StaticQuery renders absolutely nothing (not even the “Hello”).

import React from "react";
import { graphql, StaticQuery } from "gatsby";

export default function Header() {
  return (
      <StaticQuery
        query={
          graphql`
          {
            allStrapiPage {
              nodes {
                id
                publishedAt
                slug: Slug
                title: Titulo
                body: Corpo {
                  Titulo
                  Texto {
                    data {
                      text: Texto
                    }
                  }
                }
              }
            }
          }
        `
        }
        render={data => {
          <header>
            <h1>Hello</h1>
            <h1>{console.log(data)}</h1>
          </header>
        }}
      />
  )
}

Here’s my index.jsx:

import * as React from "react"
import Header from "../components/Header"

const IndexPage = () => {
  return (
    <main>
      <Header />
    </main>
  )
}

export default IndexPage

I’ve already tried removing the node_modules and installing it again with different package managers.

How force object-cover image on div child with Tailwind?

I’m creating a flat listview for a React website.
This is a picture of my mockup: enter image description here

I succed to obtain this:
enter image description here

Next, I would like to limit the size of the flat list and display the overflow-x-scroll.
The problem is, when I put a size, my first image have a wrong display…
enter image description here

This is my code (I use tailwind):

import React from "react";

export type CarrouselProps = {
    images: string[],
    size: number
}
const Carrousel: React.FC <CarrouselProps>  = ({images, size}) => {

    return(
        <div>
            <div className="flex flex-row overflow-x-scroll w-[700px]">
                {images.map(url => 
                    <input className={`w-[${size}px] h-[${size}px] mr-4 object-cover rounded-md`} type="image" src={url} /> 
                )}
            </div>
            <div className="h-1 mt-3 bg-white w-[700px]"/>
        </div>
    );
}

export default Carrousel;

Could you help me to fix this wrong display on the first image ?
I specify that only the first image have portrait display

Thanks in advance, for your help

How can I use an array of indexes to nagivate an array of objects

I’m making a checklist app and need to navigate through my data to edit the complete:false

My data is structured with children being an optional key, and objects with children won’t have the completed key.

const TESTDATA = [
  {
    name: 'foo',
    path: [0],
    open: true,
    children: [
      { name: 'bar', completed: false, path: [0, 0] },
      { name: 'data', completed: false, path: [0, 1] },
    ],
  },
  {
    name: 'foo',
    path: [1],
    open: true,
    children: [
      { name: 'bar', completed: false, path: [1, 0] },
      {
        name: 'data',
        completed: false,
        path: [0, 1],
        children: [{ name: 'baz', completed: false, path: [1, 1, 0] }],
      },
    ],
  },
]

Is there a way to recursively (or not) search for a specific path/id in all the children keys and return the item so it could be modified?

In Mac OS, when can a mouse right click not be identical to a control-click?

I’m building a custom context menu in vanilla Javascript for a web app. Using the current version of Safari (15.5) on Monterey 12.4, it works just as it should when the user right clicks (i.e. clicks using the right side of Magic Mouse), but does something different when the user holds down the control key and left clicks. The puzzle is that it seems that these two actions should be identical in their effect. (I think that one difference is that control-click generates a contextmenu event and a click event).

In contrast, Chrome (v101.0.4951.64) just produces a contextmenu event for a control-click, the same as for a right click.

I have ‘Secondary click’ ticked in System Preferences > Mouse > Point & Click.

Is this a bug in Safari, or something weird about my system? Any suggestions for how to work around this (just ignoring the extra click won’t work, because left click on the element is used for another function)?

XMLHTTPrequest plain text to blob

I achieved to get a video from php using this code :

var some_video_element = document.querySelector('video')
var req = new XMLHttpRequest();
req.onload = function () {
    var blob_uri = URL.createObjectURL(this.response);
    some_video_element.src = blob_uri;
    some_video_element.addEventListener('oncanplaythrough', (e) => {
       URL.revokeObjectURL(blob_uri);
    });
};
req.open("get", "vid.php", true);
req.overrideMimeType('blob');
req.send(null);

However, the loading is long so I want to show data as soon as I get it. From Mozilia, it is indicated we can use plain or “” as mime to get the text in progress. However, I can’t achieve to convert plain/text to video/mp4 using a blob. Currently this is the code that doesn’t work.

var some_video_element = document.querySelector('video')
var req = new XMLHttpRequest();
req.onprogress = function () {
    var text = b64toBlob(Base64.encode(this.response), "video/mp4");
    var blob_uri = URL.createObjectURL(text);
    some_video_element.src = blob_uri;
    some_video_element.addEventListener('oncanplaythrough', (e) => {
       URL.revokeObjectURL(blob_uri);
    });
};
req.onload = function () {
    var text = b64toBlob(this.response, "video/mp4");
    var blob_uri = URL.createObjectURL(text);
    some_video_element.src = blob_uri;
    some_video_element.addEventListener('oncanplaythrough', (e) => {
       URL.revokeObjectURL(blob_uri);
    });
};
req.open("get", "vid.php", true);
req.overrideMimeType('text/plain');
req.send(null);

Thanks.

HTMLElement prototype method loses scope of ‘this’ to Window

I want to modify the HTMLElement prototype to have a custom function in an instance of HTMLELement. I need for that function to be able to access the HTMLElement Instance’s properties like the tagName. The problem is that inside the custom prototype function this points to the Window object instead of the HTMLElement instance. How can I achieve this?

HTMLElement.prototype.doSomething = () => {
  console.log(this)
  // Here I need to do something like console.log(this.tagName)
} 

let elem = document.createElement('div')
elem.doSomething()
// -> Window Object, instead of HTMLElement Instance object.

Thank you

Call function when resizing window but revert back after event – Javascript

I am trying to make a div id visible only during a resizing event using javascript. I have code written that triggers when I resize the window – but I wish for this to stop triggering and revert back to hidden for the div style after the resize event.

window.addEventListener('resize', animateWindow);

function animateWindow(){
    var x = document.getElementById("resize-text");
    x.style.visibility = "visible";
}

The CSS code is set to this:

#resize-text{
    visibility: hidden;
    width: 100%;
    height: 100%;
    background-color: blueviolet;
}

Should I do an if else statement using an event listener? Or what is the best approach for this?

Many thanks!

Circular Dependency in node.js

I have two functions inside to separate .js files, and each of the files needs to use the other file’s function. Each of the files also needs to use its own function. Is it possible to do this? I thought about moving the functions to a new file, but that would make my code a LOT more complicated. Thanks so much for the help!

Jquery draggable booking system grid problem

Basically, i’m trying to create a simple booking system with a drag and drop jquery script.

I want that each event starts from almost half of each cell and also ends in the same way.

See the picture below.
enter image description here

I’ve implemented a draggable script but the problem is that, i don’t know why, the grid seems not working correctly and when the event gets moved it gets stuck on the beginning of the cell. Then i added a resizable to allow the user to enlarge each event but the resize doesn’t follow the grid.

enter image description here

I attach the entire Jquery Script.

            var width = 200;
            var correction_morning_evening = 30;

            var events = [
                {
                    title: 'Test 1',
                    vehicule: 1,
                    start: moment().add(4, 'days'),
                    end: moment().add(6, 'days'),
                },
                {
                    title: 'Test 2',
                    vehicule: 5,
                    start: moment().add(2, 'days'),
                    end: moment().add(4, 'days'),
                },
                {
                    title: 'Test 3',
                    vehicule: 5,
                    start: moment().add(7, 'days'),
                    end: moment().add(8, 'days'),
                }
            ];

            var now = moment().startOf('week');
            var after = moment().add(11, 'days');

            $('#table-left').find('tbody tr').each(function () {
                $table.find('tbody').append($('<tr class="tr-event-timeline" id="tr-' + $(this).data('id') + '" style="display: flex"/>'));
            });

            var maxWidth = width * after.diff(now, 'days');
            $table.css('width', maxWidth);

            var week = null;
            while (now.isBefore(after)) {
                // render cell
                var $tdBody = $('<td class="td-event" data-date="' + now.format('YYYY-MM-DD') + '" />');
                //$tdBody.text(now.format('ddd'));
                $tdBody.attr('width', width);

                // Collapsed thread
                var $tdHead = $('<td />');
                $tdHead.append(now.format('ddd D') + '<br />' + now.format('MMM'));
                $table.find('thead tr.tr-day').append($tdHead);
                $table.find('tbody tr').append($tdBody);
                if (week !== now.format('W')) {
                    var $tdHeadWeek = $('<td colspan="7" />');
                    $tdHeadWeek.html('WEEK ' + now.format('W'));
                    $table.find('thead tr.tr-week').append($tdHeadWeek);
                }

                week = now.format('W');
                now.add(1, 'days');
            }

            // render events
            $.each(events, function (i, event) {
                var start = event.start;
                var end = event.end;

                // create div inside first $td
                var $tr = $('#tr-' + event.vehicule);
                var $tdFirst = $tr.find('td[data-date="' + start.format('YYYY-MM-DD') + '"]');
                var eventWidth = end.diff(start, 'days');

                var $eventDiv = $('<div class="label trs" />');
                $eventDiv.html('<div class="event-item">' + event.title + '</div>');
                $eventDiv.find('.event-item').css('width', "100%");

                $eventDiv.css('width', (width * eventWidth) - (correction_morning_evening*2));
                $eventDiv.css('left', correction_morning_evening);

                $tdFirst.append($eventDiv);

                // block every td
                while (start.isBefore(end)) {
                    $tr.find('td[data-date="' + start.format('YYYY-MM-DD') + '"]').addClass('td-event-booked');
                    start.add(1, 'day');
                }
                $('.calendar-grid').height($('.calendar-grid').height() + 60);
            });

            // manage rendezvous
            //$('.tr-event-timeline').selectable({
            //    filter: '.td-event-booked'
            //});

            $('.label').draggable({
                snap: '.td-event:not(.td-event-booked)',
                snapMode: "inner",
            })

            $('.label .event-item').resizable({
                handles: 'e',
                grid: [100,20],
                stop: function (e, ui) {
                    $(this).parent().width(ui.size.width);
                }
            });

Do you have any ideas? How to fix this?

I’m getting an object even though I’m returning an array from my javascript function

I have a function in a javascript file where I return an array. But when I call this function, when I look at the type with the “typeof” command, it returns an object instead of an array.

My javascript file is here.

import {useStore} from "vuex";
import {computed} from "vue";

export const getActions = (menuId) => {
   const store = useStore()
    const loginInfo = computed(() => {
        return store.state.Identity.loginInfo
    });
    const actions = []
    loginInfo.value.Authorization.forEach((x)=>{
        let splitData = x.Id.split('-')
        if(splitData[0] === '02' && splitData[1] === menuId){
            if(!actions.some(item => item.Id === splitData[2]))
                actions.push({
                    Id:splitData[2],
                    Definition: x.Definition,
                    Clicked:false
                })
        }
    })
    return actions;
}

Here is where I call and use this function.

 let actions =[]
    actions =  getActions(props.menuId)
      for(let i=0; actions.length;i++){
        if(props.actionId === actions[i].Id)
          return isAuth.value = false
        else
          isAuth.value = true
      }

Although my variable named actions is an array, it sees it as an object and my computer starts freezing. My computer’s fan starts running very fast and chrome starts to freeze.

deployed() is not a function – Truffle Solidity Javascript

code:

 loadContract: async ()=>{
     //Create JS version of smart contract
     const todoList = await $.getJSON('TodoList.json')
     App.contracts.TodoList = TruffleContract(todoList)
     App.contracts.TodoList = web3.setProvider(new Web3.providers.HttpProvider("http://127.0.0.1:7545"))
 
 //getting values from blockchain
 App.todoList = await App.contracts.TodoList.deployed()
 console.log(todoList)

error:
TypeError: App.contracts.TodoList.deployed is not a function

i am able to call TodoList.deployed() in the truffle dev environment but not in the javascript file. i am trying to to set all the data from the deployed smart contract to App.todoList so i can work with the values in the javascript file and render them to the html. I am completely stuck. when i console.log(todolist) i receive the jSON of the smart contract.

Here is my migrations file. ANY insight would be appreciated.

//need migration to update state of blockchain

const TodoList = artifacts.require("./TodoList.sol");

module.exports = function (deployer) {
  deployer.deploy(TodoList);
};
//run migration and deploy contract to blockchain

Nodejs: Cannot set headers after they are sent to the

I write this code with NodeJS:

const setOutput = (res, req, data) => {
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify(data));
}

app.post('/getDb', async (req, res, next) => {
    if (!req.body.hasOwnProperty('key')) {
        setOutput(res, req, {
            error: true,
            message: 'You must send key'
        })
    }
    
    const db = openDb(req.body.key);
    
    if (!db) {
        setOutput(res, req, {
            error: true,
            message: 'Not found key'
        })
    }

    setOutput(res, req, {
        error: false,
        message: 'DB create successful',
        data: {
            min: 0.1
        }
    });
})

This code work fine, but I get this error:

(node:253965) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

How can I stop anything after call setOutput?

Note: I don’t want use switch or a lot of if else