Why is JS toDataURL showing an invalid link?

I’m working on a sketchpad app for practise. I have a canvas that the user draws on, but when it uses the getDataURL function, it gives me a URL that’s invalid. Here’s my code, the canvas ID is sketchpad, and if you try opening the URL, it won’t work:

canvasUploadId = document.getElementById("sketchpad");
dataImg = canvasUploadId.toDataURL("image/png");
alert(dataImg);

How to create draggable components with javascript and react hooks?

I need to add draggable divs, one for every image in an array of images, to a container.

The below works BUT only on the second drag. i.e. I have to drag the component twice for it to move. It obviously has something to do with the hooks used and how the divs are being created. Any help will be appreciated.

const App = () => {
  const { dispatch, images } = useContext(design)
  const [selectedImages, setSelectedImages] = useState(images)
  const [dragId, setDragId] = useState()

  const handleDrag = (ev) => {
    setDragId(ev.currentTarget.id)
  }

  const handleDrop = (ev) => {
    const newSelectedImages = mapImages(selectedImages, dragId)

    dispatch({
      type: 'REPLACE',
      images: newSelectedImages,
    })

    setSelectedImages(newSelectedImages)
  }

  return (
    <Container
      images={selectedImages}
      handleDrag={handleDrag}
      handleDrop={handleDrop}
    />
  )
}

export default App

const Container = ({ images, handleDrag, handleDrop }) => {
  const ref = useRef(null)

  useEffect(() => {
    if (containerRef.current) {

      for (let i = 0; i < images.length; ++i) {
        const draggable = document.createElement('div')
        draggable.ondragstart = handleDrag
        draggable.ondrop = handleDrop

        const style = 'position: absolute; ...'

        draggable.setAttribute('style', style)
        draggable.setAttribute('draggable', true)
        draggable.setAttribute('id', images[i].id)

        ref.current.appendChild(draggable)
      }
    }
  }, [images, ref, handleDrag, handleDrop])


  return (
    <div className={'relative'}>
      <div ref={ref} />
    </div>
  )
}

export default Container

Firebase Authentication via Server Side to access routes

I am using sessionStorage and also firebase authentication for email and password.

In my server.js I am wondering how can I make it so that if a user is not logged in they cannot access a route, or rather be redirected to the login route instead.
The firebase sdk I am using is only usable via the client side. Is there any documentation to help that I have been unable to find.

Please let me know if I need to clarify my question more and I will do my best to do so.

Here is my server.js:

const express = require('express');
const admin = require('firebase-admin');
const bcrypt = require('bcrypt');
const path = require('path');

let serviceAccount = require("./1234.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount)
});

let staticPath = path.join(__dirname,"public");

const app = express();

app.use(express.static(staticPath));
app.use(express.json());

    app.get('/login', (req,res) => {
        res.sendFile(path.join(staticPath, "form.html"));
    })
    
    app.get('/seller', (req,res) => {
    // if(!user) res.redirect('/login');
        res.sendFile(path.join(staticPath, "seller.html"));
    })

Keyboard event fires twice even when using !event.repeat

I’ve been making an online piano that uses the keyboard as input. Sometimes when you press a key, it registers two events instead of one.

The thing is, I’ve tried using e.repeat (where e is the keyboard event) to only register the first keydown event.

You can try using it at this temporary link: https://virtual-piano-demo.netlify.app/

I’m relatively new to JavaScript and web dev in general, so any advice on my code is appreciated.

if (!e.repeat && isValidInput(e.key)) {
        let pitch = keysMap.get(e.key);
        playNote(pitch);
        document.getElementById(pitch).classList.add("key-bkg-color"); // change color of key
    }

Here’s the relevant code.

let notes = document.getElementsByClassName("note");
let soften = document.getElementById("soften");
let sustain = document.getElementById("sustain");
let piano = document.getElementById("piano");
let context = new (window.AudioContext || window.webkitAudioContext)();
let keysMap = new Map([
    ['q', "C3"],
    ['2', "Db3"],
    ['w', "D3"],
    ['3', "Eb3"],
    ['e', "E3"],
    ['r', "F3"],
    ['5', "Gb3"],
    ['t', "G3"],
    ['6', "Ab3"],
    ['y', "A3"],
    ['7', "Bb3"],
    ['u', "B3"],
    ['i', "C4"],
    ['9', "Db4"],
    ['o', "D4"],
    ['0', "Eb4"],
    ['p', "E4"],
    ['[', "F4"],
    ['=', "Gb4"],
    [']', "G4"],
    ['a', "Ab4"],
    ['z', "A4"],
    ['s', "Bb4"],
    ['x', "B4"],
    ['c', "C5"],
    ['f', "Db5"],
    ['v', "D5"],
    ['g', "Eb5"],
    ['b', "E5"],
    ['n', "F5"],
    ['j', "Gb5"],
    ['m', "G5"],
    ['k', "Ab5"],
    [',', "A5"],
    ['l', "Bb5"],
    ['.', "B5"],
    ['/', "C6"],
]);

// load all audio files when page loads so that when the user presses keys the sounds start on time
// store buffers in array to access piano sounds when user presses a key
let buffers = [];
window.addEventListener("load", function() {
    for (let i = 0; i < notes.length; ++i) {
        let request = new XMLHttpRequest();
        request.open("GET", "./audio/" + notes[i].id + ".mp3");
        request.responseType = "arraybuffer";
        request.onload = function() {
            let undecodedAudio = request.response;
            context.decodeAudioData(undecodedAudio, (data) => buffers[notes[i].id] = data)
        }
    request.send();
    }
})
function isValidInput(input) {
    return keysMap.has(input) === true;
}

function playNote(pitch) {
    let playSound = context.createBufferSource();
    let gainNode = context.createGain();
    playSound.buffer = buffers[pitch];  

    if (soften.checked === true) {
        gainNode.gain.setValueAtTime(0.6, context.currentTime);
        gainNode.gain.exponentialRampToValueAtTime(1.05, context.currentTime + 0.35);
    }
    else {
        gainNode.gain.setValueAtTime(1.5, context.currentTime);
    }

    playSound.connect(gainNode);
    gainNode.connect(context.destination);
    playSound.start(context.currentTime);

    if (sustain.checked === false) {
        gainNode.gain.exponentialRampToValueAtTime(0.001, context.currentTime + 3);
    }
}

// Keyboard Input
document.addEventListener("keydown", function(e) {
    // the pressed key is used for input in the piano -> play note
    // !e.repeat makes sure that only the first keydown event when holding down on a certain key is taken into account
    if (!e.repeat && isValidInput(e.key)) {
        let pitch = keysMap.get(e.key);
        playNote(pitch);
        document.getElementById(pitch).classList.add("key-bkg-color"); // change color of key
    }
})

document.addEventListener("keyup", function(e) {
    let pitch = keysMap.get(e.key);
    document.getElementById(pitch).classList.remove("key-bkg-color"); // change color of key
})

Why dose previous solution slide show not work?

I was searching for a solution to a slide show on a website that i wanted but the solution is this yet it doesn’t work for me.

 <div class="container">
         <div id="slideshow">
             <img alt="slideshow" src="http://thumb7.shutterstock.com/photos/thumb_large/253822/156271139.jpg" id="imgClickAndChange" onclick="changeImage()" />
         </div>
     </div>
     <script>
         var imgs = ["http://thumb7.shutterstock.com/photos/thumb_large/253822/156271139.jpg", "http://thumb9.shutterstock.com/photos/thumb_large/554278/132632972.jpg", "http://thumb7.shutterstock.com/photos/thumb_large/101304/133879079.jpg", "http://thumb101.shutterstock.com/photos/thumb_large/422038/422038,1327874090,3.jpg", "http://thumb1.shutterstock.com/photos/thumb_large/975647/149914934.jpg", "http://thumb9.shutterstock.com/photos/thumb_large/195826/148988282.jpg"];
         function changeImage(dir) {
             var img = document.getElementById("imgClickAndChange");
             img.src = imgs[imgs.indexOf(img.src) + (dir || 1)] || imgs[dir ? imgs.length - 1 : 0];
         }
         document.onkeydown = function(e) {
             e = e || window.event;
             if (e.keyCode == '37') {
                 changeImage(-1) //left <- show Prev image
             } else if (e.keyCode == '39') {
                 // right -> show next image
                 changeImage()
             }
         }
     </script>
     

When i run it it ends up like this.

nothing is seen

Trouble with aligning container in BootStrap 4

I am new to web development and was having an issue with aligning a container on my webpage. For some reason any text on the page is updating, but when I try to align the container in the center of the page using (line 30) the page updates but there’s no change. Any ideas as to where I’m going wrong, also my code is provided below.

<!DOCTYPE html>
<html lang="en">

<head>
      <!-- Required meta tags always come first -->
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      <meta http-equiv="x-ua-compatible" content="ie=edge">
  
      <!-- Bootstrap CSS -->
      <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
    <title>Ristorante Con Fusion</title>
</head>

<body>

    <header>
        <div>
            <div>
                <div>
                    <h1>Ristorante con Fusion</h1>
                    <p>We take inspiration from the World's best cuisines, and create a unique fusion experience. Our lipsmacking creations will tickle your culinary senses!</p>
                </div>
                <div>
                </div>
            </div>
        </div>
    </header>

    <div class="container">
        <div>
            <div>
                <h3>Our Lipsmacking Culinary Creations</h3>
            </div>
            <div>
                <h2>Uthappizza</h2>
                <p>A unique combination of Indian Uthappam (pancake) and Italian pizza, topped with Cerignola olives, ripe vine cherry tomatoes, Vidalia onion, Guntur chillies and Buffalo Paneer.</p>
            </div>
        </div>


        <div>
            <div>
                <h3>This Month's Promotions</h3>
            </div>
            <div>
                <h2>Weekend Grand Buffet</h2>
                <p>Featuring mouthwatering combinations with a choice of five different salads, six enticing appetizers, six main entrees and five choicest desserts. Free flowing bubbly and soft drinks. All for just $19.99 per person </p>
            </div>
        </div>

        <div>
            <div>
                <h3>Meet our Culinary Specialists</h3>
            </div>
            <div>
                <h2>Alberto Somayya</h2>
                <h4>Executive Chef</h4>
                <p>Award winning three-star Michelin chef with wide International experience having worked closely with whos-who in the culinary world, he specializes in creating mouthwatering Indo-Italian fusion experiences. </p>
            </div>
        </div>
    </div>

    <footer>
        <div>
            <div>             
                <div>
                    <h5>Links</h5>
                    <ul>
                        <li><a href="#">Home</a></li>
                        <li><a href="#">About</a></li>
                        <li><a href="#">Menu</a></li>
                        <li><a href="#">Contact</a></li>
                    </ul>
                </div>
                <div>
                    <h5>Our Address</h5>
                    <address>
                      121, Clear Water Bay Road<br>
                      Clear Water Bay, Kowloon<br>
                      HONG KONG<br>
                      Tel.: +852 1234 5678<br>
                      Fax: +852 8765 4321<br>
                      Email: <a href="mailto:[email protected]">[email protected]</a>
                   </address>
                </div>
                <div>
                    <div>
                        <a href="http://google.com/+">Google+</a>
                        <a href="http://www.facebook.com/profile.php?id=">Facebook</a>
                        <a href="http://www.linkedin.com/in/">LinkedIn</a>
                        <a href="http://twitter.com/">Twitter</a>
                        <a href="http://youtube.com/">YouTube</a>
                        <a href="mailto:">Mail</a>
                    </div>
                </div>
           </div>
           <div>             
                <div>
                    <p>© Copyright 2018 Ristorante Con Fusion</p>
                </div>
           </div>
        </div>
    </footer>
  <!-- jQuery first, then Popper.js, then Bootstrap JS. -->
  <script src="node_modules/jquery/dist/jquery.slim.min.js"></script>
  <script src="node_modules/popper.js/dist/umd/popper.min.js"></script>
  <script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
</body>

</html>

How to intercept ALL HTTP requests on html page

I would like to intercept all of the HTTP requests an html page makes, I am using it to add a reverse-proxy URL to all the requests on a page, ( ex. https://proxy.url/{original_request_url} ) Say I had a link element for a css stylesheet:

<link rel="stylesheet" href="/style.css">

The link element would stay the same but when the browser requests the /style.css file, it would actually request https://proxy.url/style.css

Or say the website makes a fetch request

fetch("file.txt")

It should request https://proxy.url/file.txt

Oh, and I cant use Service Workers as this needs to run before anything loads and needs to stop the page from loading until it is done adding the reverse-proxy

TinyMCE editor image margin left right

Hi guys I am folowing tinymce documenttation to add margin left/right to image in tinyMCE using style_formats: [{ ... }] but it doesn’t work. my version is 5.1

It does floating image to left right style="float: left;" but doesn’t add margin, here is my setup:

function initTinyMCE(selector, minHeight) {
  var menuBar = 'file insert format table help';
  if (selector == '.tinyMCEComment') {
      menuBar = false;
  }
  tinymce.init({
    selector: selector,
    min_height: minHeight,
    valid_elements: '*[*]',
    relative_urls: false,
    remove_script_host: false,
    directionality: directionality,
    language: '<?= $Lang->editor_lang; ?>',
    menubar: menuBar,
    style_formats: [{
      title: 'Image Left',
      selector: 'img',
      styles: {
          'float': 'left', 
          'margin-right': '10px'
      }
     },
     {
       title: 'Image Right',
       selector: 'img', 
       styles: {
           'float': 'right', 
           'margin-left': '10px'
       }
     }],
    plugins: [
        'advlist','autolink','lists','link','image','charmap','print','preview','anchor',
        'searchreplace','visualblocks','code','codesample','fullscreen',
        'insertdatetime','media','table','imagetools'
    ],
    toolbar: 'fullscreen code preview | undo redo | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | numlist bullist | forecolor backcolor removeformat | image media link | outdent indent',
    content_css: ['<?= base_url('assets/plugins/tinymce/editor_content.css'); ?>'],
  });
  tinymce.DOM.loadCSS('<?= base_url('assets/plugins/tinymce/editor_ui.css'); ?>');
}

How to join strings conditionally without using let in javascript

I have a situation where I’m trying to join the array of strings only if it has a value. I did using let variable, but I wonder can I do this using map. I’m very mindful on the position, so I used in this way.

const [hours, minutes, seconds] =["", "10", ""]

  let time = "";

 if (hours) {
    time += `${hours}h `;
  }
  if (minutes) {
    time += `${minutes}m `;
  }
  if (seconds) {
    time += `${seconds}s`;
  }
  
  console.log(time)

Will I be able to do this using map, filter and join?

Two dimensinal arrays

Combine these 4 weeks into a four element array to represent a
month.
o Modify your previous code to take a week number and print
out all that week’s activities to the page.
o Modify one of your week arrays to consist not of single
elements, but of arrays of hours from 8am to 5pm. This then
represents a three dimensional array. We can extend arrays to
be n-dimensional, where n is more or less arbitrary.
o Finally, alter your code to prompt the user for three values – a
week, a day and an hour. Store these values in three separate
variables, and use those variables to display the requested task,
or else to display an error message if a task cannot be found

How open link from iframe in new tab?

I have some link, and when I click on button I redirect it with help of event to another page

<div id="link"><a href="javascript:void(0);">Redirect</a></div>

 function redirectFromIframe() {
     window.top.location.href = "some_link"
  }

 let link = document.getElementById("link");
 link.addEventListener("click", redirectFromIframe, false);

All works fine, but if we want open it in new tab, we need to use next code, since we cannot use target_blank because link is voided

 window.open('some_link', '_blank');

So how we can use link from iframe and at the same time open in new tab

pinia. vue3 | accessing to the array

I’ve posted a question before and this is also another related question. Hope someone can help me out.

in Pinia (base.js)

export const useBaseStore = defineStore('base', {
state: () => {
    return {
        areaLocal: [
            { id: 0, name: 'LAX' },
            { id: 1, name: 'SFO' },
            { id: 2, name: 'SAN' },
        ],
        areaLocal2: {
            area: [
                { id: 0, name: 'AAA'},
                { id: 1, name: 'BBB'},
                { id: 2, name: 'CCC'},
        ]},
    }
},
getters: {
    getAreaById: (state) => {
        return (areaId) =>
            state.areaLocal.find((areaLocal) => areaLocal.id === areaId)
    },..

in Vue (area.vue)

<script setup>
import { computed, ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useBaseStore } from '../stores/base'

const areaStore = useBaseStore()
const { getAreaById } = storeToRefs(areaStore)
const areaIndex = ref(0)
</script>
<template>
    <div class="container">
        <h2>AREA: {{ getAreaById(areaIndex).name }}</h2>
....

This, areaLocal, I get “AREA: LAX”, no problem!
but HOW I can write “getter” in the pinia for access to “areaLocal2”, the object “area” then the array?

state.areaLocal2.area.find((areaLocal2.area) => areaLocal.id.area === areaId

it doesn’t work….
Thank you so much!

jquery show only certain element class of an external html object data

How to show only element span class="bar of this external html object data?

See in a html example page

<!doctype html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
  <div id="y"></div>

  <script>
    $(document).ready(function(){
      $("#y").html('<object data="https://www.osculati.com/it/advancedSearchResults.aspx?searchbar=49.548.04" />');
    });
  </script>
</body>
</html>

Or see the same in a jsfiddle