Issue related to event propagation

I’m having an issue with event propagation in JavaScript. I have different data and single form attached to each child element. To prevent an event from propagating to each child element and it’s parent I am using stopImmediatePropagation(). The other method like following doesn’t work.

event.cancelBubble = true;
//OR
event.stopPropagation();
//OR
yourFormSubmissionElement.removeEventListener('submit', submitCreatePlistForm, false);
yourFormSubmissionElement.addEventListener('submit', submitCreatePlistForm, false)

Problem that I’m having is that the data that was linked to each individual element become same in each call, i.e. if the form submission was to send DATA01, DATA02, DATA03 etc. for element1, element2, element3… respectively, then on each submission DATA01 is sent back to backend when I use stopImmediatePropagation() in this.

//Each Button in the playlist has this event listener with their own data passed as argument
const listenFormSubmission = async (data) => {
    const taskAForm = document.querySelector('<selector>');

    const submitTaskAForm = async function(e) {
        e.preventDefault();
        // e.cancelBubble = true;
        // e.stopPropagation();
        e.stopImmediatePropagation();

        await axios.post('/target', data).then(async function(errResponse){
            console.log(errResponse)});
        }
        taskAForm.addEventListener('submit', submitTaskAForm, false);
    }

If anyone can give suggestions on how to handle this, that will be of great help.
And though I already have gone through most of the related articles and questions any other useful reference in your knowledge will be greatly appreciated.

sending data in forms html to mysql data base using Node.Js

Hello I am doing an exercise that the main goal is to create a RestAPI with Node.js and test it in small hmtl application. My teacher helped us create the RestAPI with an example, and I was able to adapt it to my own mysql database, and tested every endpoint of the API using Thunder Client extension on Visual Studio Code, and it his working properly. However i am having problems in the testing in the html app. I am trying to send some data using a form, but as i submit, i know the endpoint it is right, because it truly connects to the right function and table, and insert new data to the table, however it doesn’t save any of the data i put in the form, instead, it inserts null values to all columns.

Here is my html form

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
   
    <title>Header</title>

    <link rel="stylesheet" href="css/styles.css">
    </head>
<body>

    <h1 id="teste"> Adicionar um Videojogo</h1>
    <form action=" http://localhost:3000/api/videogames" method="post" enctype="multipart/form-data"  >

        <div class="form-item col" id="form_">
                    <input type="text" name= "nome" id="nome" placeholder="Nome" required= "required">
                    </div>
        <div class="form-item" id="form_">
                    <input type="text" name= "produtora" id="produtora" placeholder="Produtora" required= "required">               
                    </div>
        <div class="form-item" id="form_">
                   <input type="text" name= "distribuidora" id="distribuidora" placeholder="Distribuidora" required= "required">
                    </div>
        <div class="form-item" id="form_">
                   <input type="text" name= "ano" id="ano" placeholder="Ano" required= "required">
    
                   </div>

Here is my model

const sql = require("./db.js");

// construtor
const Videogame = function(videogame) {
  this.nome = videogame.nome;
  this.produtora = videogame.produtora;
  this.distribuidora = videogame.distribuidora;
  this.ano = videogame.ano;
  this.id_genero= videogame.id_genero;
  this.id_plataforma = videogame.id_plataforma;
}

Videogame.insert = (newVideogame, result) => {
  sql.query('INSERT INTO videogame SET ?', newVideogame, (err, res) => {
    if (err) {
      console.log('error: ', err);
      result(err, null);
      return;
    }

    console.log("Videojogo inserido: ", { id: res.insertId, ...newVideogame });
    result(null, { id: res.insertId, ...newVideogame});
  });
}

My Controller

const Videogame = require("../models/videogame.model.js");

// Inserir um novo videojogo
exports.insert = (req, res) => {
    // Validar a request
    if (!req.body) {
      res.status(400).send({
        message: "O conteúdo do videojogo deve estar definido."
      });
    }
  
    // Criar um "Videogame"
    const videogame = new Videogame({
      nome: req.body.nome,
      produtora: req.body.produtora,
      distribuidora: req.body.distribuidora,
      ano: req.body.ano,
      id_genero: req.body.id_genero,
      id_plataforma: req.body.id_plataforma,
    });
  
    // Guardar "Videogame" na base de dados
    Videogame.insert(videogame, (err, data) => {
      if (err)
        res.status(500).send({
          message:
            err.message || "Ocorreu um erro ao inserir o videojogo..."
        });
      else res.send(data);
           
    });
  };

My routes

module.exports = app => {
    const videogames = require("../controllers/videogame.controller.js");
  
    var router = require("express").Router();
  
    // Consultar todos os videojogos
    router.get("/", videogames.selectAll);
  
    // Consultar um videojogos pelo id
    router.get("/:id", videogames.findById);
  
    // Inserir um novo videojogo
    router.post("/", videogames.insert);
  
    // Atualizar um videojogo pelo id
    router.put("/:id", videogames.update);
  
    // Apagar um videojogo pelo id
    router.delete("/:id", videogames.delete);
  
    // Apagar todos os videojogos
    router.delete("/", videogames.deleteAll);
  
    app.use('/api/videogames', router);
  };

Here is the result that appear on the terminal, after i submit my form

Videojogo inserido:  {
  id: 14,
  nome: undefined,
  produtora: undefined,
  distribuidora: undefined,
  ano: undefined,
  id_genero: undefined,
  id_plataforma: undefined
}

It should save the data i use in forms instead of undefined ( i also have 2 radio buttons for id_genero and id_plataforma on my forms, but i only put the others here, because i don’t think the problem is not with the radio buttons, as if it were, it would at assign the other values in forms.

Thanks in advance

Is there a way to get the element that is visually underneath or above or left or right a certain element?

I am working on simple game (classic number game) with JavaScript
in which a container div with display Flex contains 9 divs
8 divs are blue with numbers inside from 1 to 8 and 1 div is white without any content
each time the page loaded the divs are ordered randomly
image of the game

and the empty div is placed randomly too.

the mission is to rearrange the numbers from 1 to 8 that when you click on any div that is visually neighbor (above, beneath, left or right)

to the empty div
they are switch their positions
in this image the divs that are allowed to move are 4,7,5
How I can make it with javaScript or jquery ?

here is my code:

$(document).ready(function(){
  var arr = [];
  
  for(i=1;i<9;i++)
  {
    arr.push(i);
  }
  
  arr.push("");

  function shuffleArray(array) 
  {
    for (let i = array.length - 1; i > 0; i--) 
    {
      const j = Math.floor(Math.random() * (i + 1));
      [array[i], array[j]] = [array[j], array[i]];
    }
  }
  
  shuffleArray(arr);

  for(i=0;i<9;i++)
  {
    divContent.innerHTML += "<div class='tile'>"+arr[i]+"</div>"
  }

  var tile = document.getElementsByClassName("tile");

  var n = 0;

  while (n < tile.length) 
  {
    if (tile[n].textContent != (n+1))
      break;
    
    tile[n].style.color = "yellow";
    n++;
  }

  for(i=0;i<tile.length;i++)
  {
    if(!tile[i].textContent)
    {
      tile[i].style.backgroundColor  = "#fff";
      tile[i].classList.add("whitt");
    }
    tile[i].style.color = "#fff";
  }

  $('.tile').click(function (evt) {
    var $div = $(evt.target).closest('.tile');
    $div.next('.tile').after($div).animate({opacity: 0.9, top:'100'}, 500 );

    for(i=0;i<tile.length;i++)
    {
      if(!tile[i].textContent)
      {
        tile[i].style.backgroundColor  = "#fff";
        tile[i].classList.add("whitt");
      }
      tile[i].style.color = "#fff";
    }

    n = 0;
    
    while (n < tile.length) 
    {
      tile[n].style.color = "#fff";
      if (tile[n].textContent != (n+1)) 
        break;
      tile[n].style.color = "yellow";
      n++;
    }
  });
});
.flexDiv{
  display:flex;
  flex-wrap: wrap;
  width:310px;
  border:1px solid black;
}
.tile{
  position:relative;
  background:#08088A;
  text-align:center;
  width:29%;
  margin:1px;
  font-size:75px;
  font-weight:bold;
  color:#fff;
  padding:5px;
}
.wh{
  background:#fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<div id="divContent" class="flexDiv"></div>

How to redirect page using targetURL with my datepicker

I am tweaking with Twisty’s script – Using Jquery UI Datepicker to redirect to URL: Change URL value based on the selected date

I am trying let user click on a date which will be redirect to a page according to the date selected. But I am getting this alert – Redirect to undefined, no matter how I tweaked the script.
Hence, I would appreciate your help. Thank you.

Pick a date:

<script>
$(function() {
  function getDayOfYear(n) {
    var s = new Date(n.getFullYear(), 0, 0);
    var d = (n - s) + ((s.getTimezoneOffset() - n.getTimezoneOffset()) * 60 * 1000);
    var oneDay = 1000 * 60 * 60 * 24;
    var day = "00" + Math.floor(d / oneDay);
    return day.substr(-3);
  }

  var targetUrl;

  $("#datepicker")
    .datepicker({
      dateFormat: 'dd-mm-yy',
      onSelect: function(dateText) {
      datePicked = $.datepicker.parseDate('dd-mm-yy', dateText);
       dayPicked = getDayOfYear(datePicked);
       targetUrl  =  "https://datepicker.com/" + dayPicked;
        $(this).change();
      }
    })
    .change(function() {
      alert("Redirect to " + targetUrl);
      //window.location.href = targetUrl;
    });
});
</script>

Is there a way to optimize this script to run faster? I am getting the error “Exceeded maximum execution time”

I am using Google App Scripts to import data from Spreadsheet #1 to Spreadsheet #2. But I am getting the error “Exceeded maximum execution time”. What am I doing wrong? Is there a better way to optimize the code?

Script Logic

  • Create Array #1, for column B, on Spreadsheet #1, which contains Employee ID’s
  • Create Array #2, for column A, on Spreadsheet #2, which contains Employee ID’s already imported.
  • If Array #1 contains an ID not found in Array #2, append a new row on Spreadsheet #2 with the ID, email1, and email2 columns.

Spreadsheet #1 (Source)

  • Contains duplicate data in rows.
  • There are 50,000 rows currently with 100 new rows added daily.
A B C D E F G H I J K L M N O P Q R S T U V W
200001 [email protected] [email protected]
200001 [email protected] [email protected]

Spreadsheet #2 (Destination)

  • Contains non-duplicate rows.

Working Script (for data less than 5,000 rows).

// Source sheet settings
let sourceSheetId = '1qW5UDn0O*******************';
let sourceTab = 'Source';
let sourceColumn = 2;
let sourceEmail1Column = 20;
let sourceEmail2Column = 19;

// Destination sheet settings
let destinationTab = 'Destination';
let destinationColumn = 1;
let destinationEmail1Column = 2;
let destinationEmail2Column = 4;


function newEmployeeIds() {
  let ss = SpreadsheetApp.getActiveSpreadsheet();
  let destinationSheet = ss.getSheetByName(destinationTab);

  let sourceSS = SpreadsheetApp.openById(sourceSheetId);
  let sourceSheet = sourceSS.getSheetByName(sourceTab);

  let existingIdsArray = destinationSheet.getRange(2,destinationColumn,destinationSheet.getLastRow()-1,1).getValues();
  let existingIds = existingIdsArray.flat();

  let sourceIdArray = sourceSheet.getRange(2,sourceColumn,sourceSheet.getLastRow()-1,1).getValues();
  let sourceIds = [...new Set(sourceIdArray.flat())];

  let email1Array = sourceSheet.getRange(2,sourceEmail1Column,sourceSheet.getLastRow()-1,1).getValues();
  let email2Array = sourceSheet.getRange(2,sourceEmail1Column,sourceSheet.getLastRow()-1,1).getValues();

  for (i=0;i<sourceIds.length;i++){
    if (existingIds.indexOf(sourceIds[i]) == -1){
    let newRow = destinationSheet.getLastRow()+1;
    destinationSheet.getRange(newRow,destinationColumn).setValue(sourceIds[i]);
    let index = sourceIdArray.flat().indexOf(sourceIds[i]);
    destinationSheet.getRange(newRow,destinationEmail1Column).setValue(email1Array[index][0]);
    destinationSheet.getRange(newRow,destinationEmail2Column).setValue(email2Array[index][0]);
    }
  }

}

Should i go with expressjs and mongoose or django and mongoose as the backend for my website (I’m using React for the frontend)?

I have been looking at tutorials for working in the backend of my website and our team members have also thought about using django since it comes with a lot of features(mainly giving permissions to different users is easy there) whereas i don’t really have a clue about how this works using express with mongodb. Since the database used for our project is gonna be non-relational(i.e mongodb), please suggest me if i should go with express or django along with mongodb, any documents references will be much appreciated!

Laravel JSPDF output() not working but save() is working

I have Laravel project that use JSPDF to generate PDF file from a DIV and download it

When I tried it on iPhone Safari I found that it’s not working

I searched about the reason and I found that I can use output(‘dataurl’) instead

When I replaced the save() with output(), it’s not working on all platforms now

The code:

$('#print').click(async function (e) {
    e.preventDefault();
    const pdf = new jsPDF('p', 'mm', 'a4');
    const imgWidth = 208;
    const position = 0;

    let page1 = document.querySelector('#report-one');
    let page2 = document.querySelector('#report-two');
    const [imgPage1, imgPage2] = await Promise.all([html2canvas(page1), html2canvas(page2)]);
    // Process first image
    let imgHeight = imgPage1.height * imgWidth / imgPage1.width;
    let contentDataURL = imgPage1.toDataURL('image/jpeg');
    pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight);
    pdf.addPage();
    // Process second image
    imgHeight = imgPage2.height * imgWidth / imgPage2.width;
    contentDataURL = imgPage2.toDataURL('image/jpeg');
    pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight);

    pdf.output('dataurl');
});

Jquery Datetimepicker inline not showing selected date and time value in text format

The JQuery Datetimepicker has the option to display the calendar inline however when this is done it removes the input box that shows the user selected input value of the date and time chosen. How can you make the datetimepicker display the calendar inline and also display the user selected date in an input box.

JQuery datetimepicker - https://plugins.jquery.com/datetimepicker 
Documentation - https://xdsoft.net/jqplugins/datetimepicker
CDN - https://cdnjs.com/libraries/jquery-datetimepicker 
The JSFiddle with the code -  https://jsfiddle.net/x8L4o0qa/1

Click event not firing for dynamically generated button

I am getting JSON data (businesses) from the yelp API. I loop through the data to display the businesses, and upon clicking on a certain business, display more information about it. I also want to include a button that will add the business and its location information to a list to use later on. This is what I have so far:

        function display_results(businesses) {
            var options = '';
            for (var i = 0; i < businesses.length; i++) {
                options += '<div class="optbtn" data-value="' + i + '">' + businesses[i].rating.toFixed(1) + "/5u2606  " + businesses[i].name + '</div>';
            }
            $('#businesses').html(options);

            // display details on click
            $('.optbtn').click(function () {
                var index = $(this).data('value');
                console.log("index: " + index);
                var details = businesses[index];
                console.log(businesses[index].name);

                var info = '';

                info += 'Name: ' + details.name + '<br>';
                info += 'Rating: ' + details.rating + '<br>';
                info += 'Price: ' + details.price + '<br>';
                info += 'Hours: ' + details.hours + '<br>';
                info += 'Location: ' + details.location.address1 + ', '
                    + details.location.city + ', '
                    + details.location.state + ' '
                    + details.location.zip_code + '<br>';

                info += '<br>';
                info += '<button type="button" class="add btn btn-primary" data-value="' + index + '">' + 'Add to List' + '</button>';

                $('#info').html(info);
            });

            $(document).on('click', 'btn', function () {
                console.log("button clicked");
                var d = $(this).data('value');
                console.log("btn: " + d);
            });

        }

        $(function () {
            $("#search_bar").autocomplete({
                source: "/autocomplete",
                minLength: 3,
                select: function (event, ui) {
                    $.ajax({
                        url: "/business_search",
                        type: "GET",
                        data: {
                            term: ui.item.value
                        },
                        success: function (result) {
                            display_results(JSON.parse(result).businesses);
                        }
                    });
                }
            });
        });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="ui-widget">
  <label for="search_bar">Business Search:</label>
  <input id="search_bar" />
</div>
<div class="ui-widget">
  Businesses:
  <div id="businesses" class="ui-widget-content"></div>
</div>
<div class="ui-widget">
  Info:
  <div id="info" class="ui-widget-content"></div>
</div>

I am having trouble getting the button to actually work. Additionally, what would be the best way to store the business if I wanted to hold the name, location, and other related information?

Discord.js “ReferenceError: message is not defined”

I was looking at the tutorial with making kick command (https://www.youtube.com/watch?v=IKg7tX5MeWc) and I typed the same. But it doesn’t work. It gives me “ReferenceError: message is not defined” error. How to fix it?

if(message.content.startsWith("?kick")) {
  if(message.member.hasPermission("KICK_MEMBERS")) {
    let member = message.mentions.members.first()
    if(!member) message.channel.send("Вы не указали, кого кикнуть.")
    else {
      member.kick().then(mem => {
        message.channel.send(`${mem.user.username} был успешно кикнут.`)
      })
    }
  } else {
    message.reply("Вы на данный момент не имеете права кикать людей.")
  }
}

Check if point is inside of shape drawn by a complex Path2D

I want to check if a given point is inside of the space drawn inside of a irregular path – inside of the brain (the path is below).

I don’t seem to be able to use CanvasRenderingContext2D.isPointInPath(path, x, y) because it only returns true if the point is literally inside the path (the white outline).

I also don’t think I can use the odd polygon rule, given that it is possible for a point not to be in the edge and its line still hit the shape wall an even number of times…

Shape

How to use static information in react app?

I have a card designed in react. The card needs to appear throughout the project (on different pages).

Each card will have different titles, subtitles, and amount.

How can I go about doing this? I thought about creating an object and then looping through it. Calling the card component on different pages, but this won’t allow me to change the content depending on the page.

Card.js

const cards = [
   {title: Card A, subtitle: Card A Subtitle},
   {title: Card A2, subtitle: Card A2 Subtitle},
   {title: Card A3, subtitle: Card A3 Subtitle},
]

{cards.map through cards to display it}

ExamplePageA.js. (Card:3, title: CardA, Subtitle:CardASubtitle….)

<Card />
<OtherStuff />

ExamplePageB.js (Card:2, title: cardB, Subtitle: CardBSubtitle….)

<Card />
<OtherStuffB />
<OtherStuffToo />

Save WAV file in Django backend

I am trying to record a voice message in the frontend and send it to the Django backend to test it against a ML algorithm of voice gender prediction. In the frontend I record the voice and I use AJAX to send the blob to the backend where I try to use wave to save the file as a valid .wav. The problem is that the file that gets saved on the backend is only noise without hearing the voice at all. On the frontend I can listen to the voice recording just fine, sounding exactly as it should. I am wondering how could I save on the backend the blob that I receive as a valid WAV file?

Here is the recording and blob sending logic on the frontend:

<div>
    <div id='gUMArea'>
      <button class="home-btn"  id='gUMbtn'>Request Stream</button>
    </div>
    <div id='btns'>
      <button class="home-btn" id='start'>Start</button>
      <button class="home-btn" id='stop'>Stop</button>
    </div>
    <div>
      <ul class="list-unstyled" id='ul'></ul>
    </div>
    <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script>
        'use strict'

        let log = console.log.bind(console),
          id = val => document.getElementById(val),
          ul = id('ul'),
          gUMbtn = id('gUMbtn'),
          start = id('start'),
          stop = id('stop'),
          stream,
          recorder,
          counter=1,
          chunks,
          media;
        
        gUMbtn.onclick = e => {
          let mv = id('mediaVideo'),
              mediaOptions = {
                audio: {
                  tag: 'audio',
                  type: 'audio/wav',
                  ext: '.wav',
                  gUM: {audio: true}
                }
            };

          media = mediaOptions.audio;
          navigator.mediaDevices.getUserMedia(media.gUM).then(_stream => {
            stream = _stream;
            id('gUMArea').style.display = 'none';
            id('btns').style.display = 'inherit';
            start.removeAttribute('disabled');
            recorder = new MediaRecorder(stream);
            recorder.ondataavailable = e => {
              chunks.push(e.data);
              if(recorder.state == 'inactive')  makeLink();
            };
            log('got media successfully');
          }).catch(log);
        }

        start.onclick = e => {
          start.disabled = true;
          stop.removeAttribute('disabled');
          chunks=[];
          recorder.start();
        }

        stop.onclick = e => {
          stop.disabled = true;
          recorder.stop();
          start.removeAttribute('disabled');
        }

        function makeLink(){
          let blob = new Blob(chunks, {type: media.type })
            , url = URL.createObjectURL(blob)
            , li = document.createElement('li')
            , mt = document.createElement(media.tag)
            , hf = document.createElement("button");
          ;
         
          mt.controls = true;
          mt.src = url;
          hf.download = `${counter++}${media.ext}`;
          hf.innerHTML = `Submit ${hf.download}`;
          hf.className = "home-btn";
          hf.onclick = function(){
            $.ajax({
                type: "POST",
                url: "{% url 'detector' %}",
                processData: false,
                contentType: false,
                data: blob,
                success: function(data){
                    console.log("success");
                    console.log(data);
                },
                failure: function(data){
                    console.log("failure");
                    console.log(data);
                },
            });
          }
          li.appendChild(mt);
          li.appendChild(hf);
          ul.appendChild(li);
        }
    </script>
</div>

And here is my logic on the Django backend:

def post(self, request):
        audio = wave.open('test.wav', 'wb')
        audio.setnchannels(1)
        audio.setnframes(1)
        audio.setsampwidth(1)
        audio.setframerate(8000)
        audio.writeframes(request.body)
        audio.close()

What am I doing wrong? Is there a way to create a valid WAV file having the same content as the blob that I record on the frontend?

JavaScript – How do I access a value in an array, containing an object that contains and array of objects?? I need a property of one of the objects [duplicate]

screengrab of console output of actual array

I’m new to JS and am trying to get a value from inside of this array.

assetList = 

[ 
    {data: 
        [{track: 1, status: 'ready', id: 1111111}, {track: 2, status: 'idle', id: 2222222}]
    }
];

In the console I enter:

assetList[0].data[0].id 

and I get back the value 1111111 as I expect to, however when I try to pass the value into a variable in my actual JS script as per below:

var assetListData = assetList[0].data[0].id;

I get an error back, Uncaught TypeError: Cannot read properties of undefined (reading ‘data’)

What am I doing wrong here? Thanks for your help!

Scale width to height (100% of parent)

I’m attempting to create a webpage template with Bootstrap 5.0 fluid containers (a header and a container that adjust so that vertical scroll is never required. Inside of this container, I want to render a D3 map within a svg that will dynamically scale to 100% of its parent container’s height (whatever its parent container’s height is currently), and adjust its width accordingly to preserve aspect ratio.

I found some styling to get my container to always scale to remaining viewport height without necessitating vertical scroll, included below, but I can’t figure out how to instantiate my svg to take up only this vertical space, scale horizontally and resize.

HTML

<body>
    <div class="container-fluid" id="wrapper-div">
        <div class="container-fluid" id="header-div">
            HEADER TEXT
        </div>
        <div class="container-fluid" id="map-div">
            <svg id="map-svg"></svg>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
            integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
            crossorigin="anonymous"></script>
    <script src="https://d3js.org/d3.v5.min.js"></script>
    <script src="https://unpkg.com/topojson@3"></script>
    <script src="./index.js"></script>
</body>

JS

let path = d3.geoPath()

let svg = d3.select("#map-svg").  <--presumably something here to establish height/width?
    .attr("preserveAspectRatio", "xMidYMid meet")
    .attr("viewBox", "0 0 960 600")

d3.json("https://cdn.jsdelivr.net/npm/us-atlas@3/counties-albers-10m.json").then(
    function(us) {

        svg.selectAll("path.county")
            .data(topojson.feature(us, us.objects.counties).features)
            .join("path")
            .attr("id", function (d) {
                return d["id"]
            })
            .attr("class", "county")
            .attr("fill", "#E7E7E8")
            .attr("stroke", "#FFFFFF")
            .attr("stroke-linejoin", "round")
            .attr("stroke-width", "0.3")
            .attr("d", path)
    }
)

CSS

* {
    margin: 0;
    padding: 0;
    border: 0;
}

html, body {
    height: 100%;
}

#wrapper-div {
    height: 100%;
    display: -webkit-flex;
    display: flex;
    -webkit-flex-direction: column;
    flex-direction: column;
    outline: 1px solid red;
}

#header-div {
    background-color: lightblue;
    -webkit-flex: 0 0 auto;
    flex: 0 0 auto;
}

#map-div {
    background-color: lightgreen;
    -webkit-flex: 1 1 auto;
    flex: 1 1 auto;
    display: -webkit-flex;
    display: flex;
    -webkit-flex-direction: row;
    flex-direction: row;
}

#map-svg {
    background-color: lightpink;
}