Vue Prevent form submit when pressing enter inside form

I have a webapp with multiple forms and inside these forms multiple custom made components: input, textarea, selectbox, datepicker, radiobutton, checkbox, … .

I found out that the submit function is fired when pressing the enter key inside a child component of a form tag. Something I don’t want. I want to be able to use the enter key for other things like conforming a selection in a dropdown.

Form example

<template>
    <form @submit.prevent="handleLogin">
        <fieldset :disabled="isSubmitting" class="space-y-6">
            <Input :label="$tc('email', 1)" type="email" id="email" v-model="user.email" :error="errors.email" />
            <Input :label="$tc('password', 1)" type="password" id="password" v-model="user.password" :error="errors.password" />
            <Select :label="$tc('role', 1)" id="role" :options="roles" displayProperty="display_name" valueProperty="id" v-model="user.role" :error="errors.role" />
            <SubmitButton :label="$tc('register', 1)" :submittingLabel="$tc('register_loader', 1)" :isSubmitting="isSubmitting" />
        </fieldset>
    </form>
</template>

SubmitButton.vue

<button type="submit">{{ isSubmitting ? submittingLabel : label }}</button>

Therefore I’m looking for a way to prevent the default behaviour. Adding a keydown function and checking if the enter key is being pressed inside all the custom components followed by an event.preventDefault() didn’t do the trick.

A working solution should be to change the type of the button from ‘submit’ to ‘button’ and use an @click but that doesn’t sound like semantic html.

Any other suggestions?

how to position items inside css grid?

I’m learning the CSS grid and trying to position the items inside grid?

can get and see data from javascript:

const profileImg = document.createElement('img');
var profilePhotoUrl = post.user.get("photo").url();
profileImg.src = profilePhotoUrl;
profileImg.className = "profile";

const username = document.createElement('username');
username.className = "user";
username.innerText = post.name;
const content = document.querySelector('.content'); 
content.append(profileImg, username);

from CSS

body {
    display: grid;
    margin: 0;
    grid-template-columns: 20% auto;
    grid-template-rows: 60px auto 100px;
    grid-template-areas: 
        "header header"
        "sidebar content"
        "sidebar footer";
}
.content {
    grid-area: content;
    justify-self: center;
}

and it looks like this. how can I position them vertically?
(profile username) <–like this
(profile username)
(profile username)

enter image description here

Node – GifEncoder has a delay or lags when creating a gif

i want to render a Gif with GifEncoder (older version), but unfortunately the gif output is jittery or so to say, it lags. This is my code:

import GIFEncoder from "gif-encoder-2";
import fs from "fs";

import pkg from "canvas";
const { createCanvas } = pkg;

let frame = 0;
const size = 200;
const fr = 60; //starting FPS
const encoder = new GIFEncoder(size, size);

encoder
  .createReadStream()
  .pipe(fs.createWriteStream("my.gif"));

encoder.start();
encoder.setRepeat(0); // 0 for repeat, -1 for no-repeat
encoder.setDelay(0); // frame delay in ms
encoder.setQuality(10); // image quality. 10 is default.

var canvas = createCanvas(size, size),
  cw = canvas.width,
  ch = canvas.height,
  cx = null,
  fps = 60,
  bX = 30,
  bY = 30,
  mX = 10,
  mY = 20,
  interval = null;

function gameLoop() {
  cx.clearRect(0, 0, cw, cw);

  cx.beginPath();
  cx.fillStyle = "red";
  cx.arc(bX, bY, 20, 0, Math.PI * 360);
  cx.fill();
  if (bX >= cw || bX <= 0) {
    mX *= -1;
  }
  if (bY >= ch || bY <= 0) {
    mY *= -1;
  }

  bX += mX;
  bY += mY;

  encoder.addFrame(cx);

  console.log(frame);

  if (frame > 60) {
    clearInterval(interval);
    encoder.finish();
  }

  ++frame;
}

if (typeof canvas.getContext !== undefined) {
  cx = canvas.getContext("2d");

  interval = setInterval(gameLoop, 1000 / fps);
}

This is the output

gif output

I took the example from this fiddle, where you can see, how smooth the ball should look like.

how it should look like

What I tried so far without success,

  • Not creating a stream, when using GifEncoder
  • Collecting cx in an array and use GifEncoder afterwards, but it seems the ctx is a reference object and I could not find a way how to copy it
  • Playing around with P5 in hope, they have an internal calculation, when the deltaTime is to high between the frames

Can anyone help me here or give me an advice what to do?

Connecting mongodb to nodejs

  1. Restarted MongoDB server (it keeps running when error occurs).

  2. Using MongoDB server on windows as a service (started it manually)
    Established the connection via MongoDB Shell CLI Package by hitting enter in the comand prompt to establish the default connection.

  3. (mongodb://127.0.0.1:27017/directConnection=true&serverSelectionTimeoutMS=2000 )
    Called npm install and npm start (my dependencies are listed below)

  4. Checked that MongoDB is running

  5. Checked via the windows resource monitor that the port 27017 is occupied by mongod.exe using TCP and is not restricted by the firewall

  6. Checked that I am not using a VPN nor a proxy connection that could interfere.

  7. Then I opened http://localhost:3000/ to which I am listening (app.listen(3000);)

Why am i still getting this error even after trying all of the above steps?


MongoServerSelectionError: connect ECONNREFUSED ::1:27017
    at Timeout._onTimeout (C:UsersridwaanDocumentsweb devtestnode_modulesmongodblibsdamtopology.js:330:38)
    at listOnTimeout (node:internal/timers:557:17)
    at processTimers (node:internal/timers:500:7) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) {
      'localhost:27017' => ServerDescription {
        _hostAddress: HostAddress { isIPv6: false, host: 'localhost', port: 27017 },
        address: 'localhost:27017',
        type: 'Unknown',
        hosts: [],
        passives: [],
        arbiters: [],
        tags: {},
        minWireVersion: 0,
        maxWireVersion: 0,
        roundTripTime: -1,
        lastUpdateTime: 1717487,
        lastWriteDate: 0,
        error: MongoNetworkError: connect ECONNREFUSED ::1:27017
            at connectionFailureError (C:UsersridwaanDocumentsweb devtestnode_modulesmongodblibcmapconnect.js:293:20)
            at Socket.<anonymous> (C:UsersridwaanDocumentsweb devtestnode_modulesmongodblibcmapconnect.js:267:22)
            at Object.onceWrapper (node:events:510:26)
            at Socket.emit (node:events:390:28)
            at emitErrorNT (node:internal/streams/destroy:164:8)
            at emitErrorCloseNT (node:internal/streams/destroy:129:3)
            at processTicksAndRejections (node:internal/process/task_queues:83:21)
      }
    },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    logicalSessionTimeoutMinutes: undefined
  }
}

Node.js v17.1.0

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request. React JS error

Hope you all are doing well.

I have deployed my react app in Bluehost, having a URL https://lanterncapitalpartners.com/
Now I am facing an issue while reloading pages, it throws an error

Not Found
The requested URL was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to
use an ErrorDocument to handle the request.

For the homepage, it reloads ok, while for other pages, it throws the error mentioned above.
I don’t know whether it’s a server issue or an app issue.

Help in that matter would really be appreciated.

Regex valid IP address

Can anyone pls confirm is this a valid IP address validator, does it verify all the IP addresses. If not pls suggest a regex (am using JS), which validates all IP addresses

        regExp:/^((([a-fA-F0-9][a-fA-F0-9]+[-]){5}|([a-fA-F0-9][a-fA-F0-9]+[:]){5})([a-fA-F0-9][a-fA-F0-9])$)|^([+-]?(?=.d|d)(?:d+)?(?:.?d*))(?:[eE]([+-]?d+))?([a-zA-Z](([+-]?(?=.d|d)(?:d+)?(?:.?d*))(?:[eE]([+-]?d+))?[a-zA-Z])+)$|(^([a-fA-F0-9][a-fA-F0-9][a-fA-F0-9][a-fA-F0-9]+[.]){2}([a-fA-F0-9][a-fA-F0-9][a-fA-F0-9][a-fA-F0-9]))$|(^([0-9]){15}$)/,

Thanks in advance

Passing bearer token in WebSockets, Angular

I want to get notifications from the backend using sockets and to get these notifications you have to be authenticated. To mean you have to pass token with the sockets to get notifications from the back end.
Here is the code i wrote:

    const headers = {
      Authorization: "bearer " + this.authService.getToken()
    };

    const protocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
    const endpoint = protocol +'localhost:8000/channel/on/notification/';
    
    const socket = new WebSocket(endpoint, ['access_token',this.authService.getToken()]);

    socket.onopen = function (e) {
      console.error('WebSockets connection created.');
    };

    socket.onmessage = function (e) {
      const data = JSON.parse(e.data);
      console.log(data)
    };

    socket.onclose = function (e) {
      console.log('Chat socket error ===>>', e)
    };

  }

I still keep getting errors. Any help?

Collision calculation faulty when using getLocalBounds in PIXIJS

I have a query regarding the sizes of Graphics. I’m trying to code collision detection, my code is as follows:

const collided = (objectBounds, bounds) => {
  return (
    objectBounds.x + objectBounds.width > bounds.x &&
    bounds.x + bounds.width > objectBounds.x &&
    objectBounds.y + objectBounds.height > bounds.y &&
    bounds.y + bounds.height > objectBounds.y
  );
};

const restrictPosToObjectBounds = (objectBounds, bounds, oldBounds) => {
  if (collided(objectBounds, bounds)) return oldPos;
  else
    return {
      x: bounds.x,
      y: bounds.y
    };
};

And then I’ll call it like this:

const objectPosition = object.getLocalBounds()
const oldPosition = object.getLocalBounds()
restrictPosToObjectBounds (
    objectPosition,
    {
      ...getNewPos(oldPosition),
      width:oldPosition.width,
      height:oldPosition.height,
    },
    oldPosition
  )

Which kinda works, but it there would be a big gap around the object I’m colliding with, leaving me unable to properly collide with it

enter image description here

If I change my collide function to this (dividing the width and heights by half)

const collided = (objectBounds, bounds) => {
  return (
    objectBounds.x + objectBounds.width / 2 > bounds.x &&
    bounds.x + bounds.width / 2  > objectBounds.x &&
    objectBounds.y + objectBounds.height / 2  > bounds.y &&
    bounds.y + bounds.height / 2  > objectBounds.y
  );
};

enter image description here

Then it works properly, any idea why? Is the scale of a Graphic rendered differently or something, how do it get its accurate width and height?

remove gsap TweenMax animation

I have this javascript code.

How would i remove the animation from it and just show and hide the elements

here is just the javascript code.

If needed i can post the html

………………………………………………………………………………………………………………………………………………………………………………………………………………………………….

var $allTiles = $(".js-tile");
var $Tiles = $(".Tiles");

$(".Tiles > .Tile").each(function(i, el) {  
  
  var $tile = $(el);
  var target = $tile.children(".Tile-flyout");
  
  // get each items flyout height with extra buffer
  var thisHeight = target.children(".Tile-content").outerHeight()+20;
  
  // Create ne timeline in paused state
  var tl = new TimelineMax({
    paused: true,
    reversed:true//,
    //forward: true // not a valid GSAP property 
  });

  TweenLite.set(target, {
    height:0,
    autoAlpha: 0,
    display: "none"//,
  });    
  // animate stuff
  tl.to(target, 1, {
    delay: 0.5,
    height: thisHeight,
    autoAlpha: 1,
    display: "block",
    ease: Cubic.easeInOut,
    overwrite: "none"
  });
  // store timeline in DOM node
  el.animation = tl;
  
  // create element event handler
  $(el).on("click", function(event) {
    
    event.preventDefault();
    
    var that = this;
    var currentTile = $(this);
    
    $(".Tiles > .Tile.is-expanded").not(this).each(function(i, element){
        console.log('reverse?');
        element.animation.reverse();
        currentTile.removeClass("not-expanded");
    }); 
     
     $allTiles.not(currentTile).removeClass("is-expanded");
     $allTiles.not(currentTile).removeClass("not-expanded");
    
     currentTile.toggleClass("is-expanded");

     if (this.animation.reversed()) {
          console.log('1');
          $allTiles.not(currentTile).addClass("not-expanded");
       
          this.animation.play();
          target.removeClass("reversing");
     } else {
          console.log('2');
          this.animation.reverse();
          target.addClass("reversing");
     }
  });  
});

How do I use the following JQuery plugin in React app?

I want to use the following JQuery plugin as part of my React app, and haven’t had success in doing so: http://viima.github.io/jquery-comments/#link-3. This is a comments plugin that creates threads/replies.

Currently, I’ve tried to integrate it as follows, but to no avail:

import React, { Component } from "react";
import $ from "jquery";
import "./jquery-comments.css";
import "./jquery-comments";

class Comments extends Component {
  componentDidMount() {
    this.$el = $("#comments-container");
    this.$el.comments({
      profilePictureURL:
        "https://viima-app.s3.amazonaws.com/media/public/defaults/user-icon.png",
      getComments: function (success, error) {
        var commentsArray = [
          {
            id: 1,
            created: "2015-10-01",
            content: "Lorem ipsum dolort sit amet",
            fullname: "Simon Powell",
            upvote_count: 2,
            user_has_upvoted: false,
          },
        ];
        success(commentsArray);
      },
    });
  }

  render() {
    return <div ref={(el) => (this.el = el)}></div>;
  }
}

export default Comments;

I am getting the date instead of date and time data in a POST request

I have a date range picker on my website.

When a user inputs the date and time range, I want to send separately within the form the startDate and the endDate

daterangepicker code:

    $('input[name="datetimes"]').daterangepicker({
        timePicker: true,
        timePickerIncrement: 5,
        startDate: moment().startOf('hour'),
        endDate: moment().startOf('hour').add(32, 'hour'),
        locale: {
          format: 'YYYY-MM-DD hh:mm'
        },
        opens: 'center',
        drops: 'auto'
    });

And this is what I tried:

$('#formid').submit(function(e) {
    e.preventDefault();
    let startDate = ($('#datetimes').data('daterangepicker').startDate).format('YYYY-MM-DD hh:mm');
    let endDate = ($('#datetimes').data('daterangepicker').endDate).format('YYYY-MM-DD hh:mm');
    $(this).append('<input type="hidden" name="start_date" value='+startDate+' /> ');
    $(this).append('<input type="hidden" name="end_date" value='+endDate+' /> ');
    this.submit();
});

Before the this.submit(); I did a console.log(startDate) and thi is what I am getting:

enter image description here

I am getting the date and the time (as expected), but then if I try doing a print(request.POST) in the view (django back-end), this is what I get:

enter image description here

Somehow, during the POST the HH:mm disappeared.

How can I keep the values of hh:mm during the POST?

What is the function( factory ) pattern for in JS plugins? [duplicate]

I’m seeing a lot of Javascript plugins utilizing a pattern like the one below in the beginning of the main plugin script.

I’ve tried looking up the Internet but couldn’t find any explanation and I don’t have any idea why this is needed.

Excerpt from Datatables:

(function( factory ) {
    "use strict";

    if ( typeof define === 'function' && define.amd ) {
        // AMD
        define( ['jquery'], function ( $ ) {
            return factory( $, window, document );
        } );
    }
    else if ( typeof exports === 'object' ) {
        // CommonJS
        module.exports = function (root, $) {
            if ( ! root ) {
                // CommonJS environments without a window global must pass a
                // root. This will give an error otherwise
                root = window;
            }

            if ( ! $ ) {
                $ = typeof window !== 'undefined' ? // jQuery's factory checks for a global window
                    require('jquery') :
                    require('jquery')( root );
            }

            return factory( $, root, root.document );
        };
    }
    else {
        // Browser
        factory( jQuery, window, document );
    }
}
(function( $, window, document, undefined )
...

Excerpt from Slick.js

;(function(factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        define(['jquery'], factory);
    } else if (typeof exports !== 'undefined') {
        module.exports = factory(require('jquery'));
    } else {
        factory(jQuery);
    }

}(function($) {
...