scrollIntoView() erratic behavior in Chrome

I have setup my html to jump from section to section each time the user clicks a button.

When I click a button on my website (not in production) scrollIntoView() does not properly execute. It registers within the DOM, but the browser does not visually show the scroll until I zoom in/out on the page, where it then ‘blinks’ the desired section into view (as if the scroll executed in the background, but not visually).

It will scroll into view once without having to zoom. After that, it stops working on Chrome only (firefox, no problem).

Here is how my different sections look in HTML (using angular)

app.component.ts

import { ChangeDetectorRef, Component, ElementRef, HostListener, ViewChild } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
    constructor(private chRef: ChangeDetectorRef){}
    
    public isMobile:boolean | null = null;

    @ViewChild("top", { static: false }) topRef!: ElementRef;
    @ViewChild("about", {static:false}) aboutRef!: ElementRef;
    @ViewChild("portfolio", {static:false}) portfolioRef!: ElementRef;

    ngOnInit(){
    }

    ngAfterViewInit(){
        this.chRef.detectChanges();
    }
}

app.component.html

<div id="top" class="content scroller">
  <section #top>
    <app-navigation
      id="top-nav"
      class="navigation width-rng"
      [elRef]="aboutRef"
    ></app-navigation>
  </section>

  <section #about>
    <app-about-me 
    id="about"
    [elRef]="portfolioRef"
    ></app-about-me>
  </section>

  <section #portfolio>
    <app-portfolio
      id="portfolio"
      [isMobile]="isMobile"
    ></app-portfolio>
  </section>
  <app-nav-button class="mobile-nav mobile-nav__portfolio" [idTag]="topRef"></app-nav-button>
</div>

app-navigation and app-about-me have the app-nav-button nested within that component. app-portfolio does not, as I use the factory pattern to create templates for each project.

My button functionality uses a button component and a service.

nav-button.component.ts: reused to jump ahead to different sections of html.

   export class NavButtonComponent {
      @Input() idTag:ElementRef | undefined;
      constructor(private scrollToService: ScrollToService) { }
    
      onNavigateTo(){
        console.log('Click event should fire ElementRef: ');
        console.log(this.idTag!.nativeElement);
        this.scrollToService.jumpTo(this.idTag);
      }
    
    }

scroll-to.service

 import { ElementRef, Injectable } from '@angular/core';

    @Injectable({
      providedIn: 'root'
    })

 export class ScrollToService {
      constructor() {}
    
      jumpTo(idTag:ElementRef | undefined):void{

      if(idTag !== undefined){
        setTimeout(()=>{
          idTag.nativeElement.scrollIntoView({behavior:'smooth', block:'start'});
        },300);
      }
    }
  }

Why does the Chart Type of Google Chart change?

I would like to update/modify an existing google chart’s options. Let’s say I want to with a click a button apply these options to an existing chart.

When the button “Modify Chart” is clicked, the chart options are updated (e.g. new colors are set).

What is strange is that the chart type is changed from a Combo Chart to a Line chart. Why is this happening? Even if I pass chartType: ‘ComboChart’ in the options, the chart type is still changed.

Help much appreciated.

function nuChart(d, t, a, h, x, y, st, is) {

    let obj = document.getElementById(d);
    if (obj == null) return;

    a = eval(a);

    if (a.length === 0) { return; }

    try {
        google.charts.load('current', { 'packages': ['corechart'] });
    } catch (error) {
        return;
    }

    google.charts.setOnLoadCallback(drawVisualization);

    if (a == '') { return; }

    function drawVisualization() {

        if (a === undefined) { return; }

        let data = google.visualization.arrayToDataTable(a);
        let wrapper = new google.visualization.ChartWrapper({

            chartType: t,
            dataTable: data,
            containerId: d,

            options: {
                title: h,
                vAxis: { title: y },
                hAxis: { title: x },
                seriesType: st,
                isStacked: is,
            }

        });

        wrapper.draw();

        window[d + '_wrapper'] = wrapper;

    }

}


function nuTestChart() {

    let a = [
                ['Month', 'Shane', 'Dave', 'Adam', 'Paul', 'Chris'],
                ['2019', 100, 200, 300, 400, 500],
                ['2020', 165, 238, 322, 498, 550],
                ['2021', 165, 938, 522, 998, 450],
                ['2022', 135, 1120, 599, 1268, 288]
              ];

    nuChart('google_chart', 'ComboChart', a, 'title', '', '', 'bars', false);

}

nuTestChart();

function nuModifyChart() {

  let wrapper = window["google_chart_wrapper"];

  wrapper.setOptions({
    colors: ['#e0440e', '#e6693e', '#ec8f6e', '#f3b49f', '#f6c7b6']
  });
  wrapper.draw();

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

<button onclick="nuModifyChart()">Modify Chart</button>

<div id="google_chart" data-nu-tab="8" data-nu-form="" class="nuHtml" data-nu-access="0" style="top: 38px; width: 450px; height: 192px; position: absolute; visibility: visible;"></div>

webkit.messageHandlers not working on iPad

Summarize the problem

I registered my iOS app on the App Store, but it was rejected.
Basically it works fine on iPhone.
But I’ve heard that there is a feature that doesn’t work properly on the iPad.
The app partially has a webview.
In my tests, it didn’t work on iPads (15.2, 15.1). It may not work on older versions as well.
Calling webkit.messageHandlers from webview not working

Describe what you’ve tried

At the beginning of the project we developed using modern JavaScript syntax.
However, the import/export syntax in iOS version 14.2 caused problems and fixed code compatibility issues with webpack.
I haven’t tried the solution because I can’t figure out why iPhones and iPads behave differently.

My Code

import { checkAndroid, checkIos } from "../../js/utils/index.js";

const step1El = document.querySelector("#step1");
const step2El = document.querySelector("#step2");
const btnEl = document.querySelector("button");

btnEl.onclick = function () {
  if (!step1El.checked)
    return alert("블록체인 간편인증 서비스 이용약관에 동의해주세요");
  if (!step2El.checked)
    return alert("개인정보 수집 및 이용 동의서에 동의해주세요");

  if (checkAndroid()) window.Android.agree();
  if (checkIos()) webkit.messageHandlers.agree.postMessage(""); // not working on iPad
};

document.querySelector(".tos_btn").onclick = () => {
  if (checkAndroid()) window.Android.goTermsConditions(true);
  if (checkIos()) webkit.messageHandlers.goTermsConditions.postMessage(true); // not working on iPad
};
document.querySelector(".policy_btn").onclick = () => {
  if (checkAndroid()) window.Android.goCollectionAgreement();
  if (checkIos()) webkit.messageHandlers.goCollectionAgreement.postMessage(""); // not working on iPad
};

Unit test for chart js

I am making a chart.js application in which functionality is implemented and now in the need to implement unit test for the same.

Things I have tried,

chart.tsx:

<div>
  <MyChart chartData={data} />
</div>

chart.test.tsx:

import React from "react";

jest.mock("chartjs", () => ({
  Line: () => null
}));

I have made the above code as unit test for chart.js integration. But unable to run the test for the same.

Working Example:

Edit Chart.js React Typescript (forked)

Could someone please help me in making the unit test for chart.js running efficiently?

Calculating the correct gap between custom cursor

I’m having an issue where I’m trying to create a custom cursor/crosshair within my canvas. The issue I have is the specified Length, Width, and Gap given to the four rectangles to form the cursor is producing the incorrect amount of pixels for the center gap.

Live CodeSandbox: https://codesandbox.io/s/nifty-resonance-bcl0m

Code:

import "./styles.css";
import { Stage, Layer, Rect } from "react-konva";

export default function App() {
  const length = 15;
  const width = 4;
  const gap = 3;
  const x = 400 / 2;
  const y = 400 / 2;
  return (
    <div className="App">
      <Stage width={400} height={400}>
        <Layer>
          {/* Horizontal Rectangles */}
          <Rect
            x={x + (width / 2 + gap)}
            y={y - width / 2}
            width={length}
            height={width}
            fill="green"
          />
          <Rect
            x={x - (length + width / 2 + gap)}
            y={y - width / 2}
            width={length}
            height={width}
            fill="green"
          />
          {/* Vertical Rectangles */}
          <Rect
            x={x - width / 2}
            y={y - (length + width / 2 + gap)}
            width={width}
            height={length}
            fill="blue"
          />
          <Rect
            x={x - width / 2}
            y={y + (width / 2 + gap)}
            width={width}
            height={length}
            fill="blue"
          />
        </Layer>
      </Stage>
    </div>
  );
}

In the above example, measuring the cursors Length and Width is the correct amount but, the center gap is giving 10 pixels instead of 6 pixels (Gap * 2). I know the issue must be due to how I’m calculating the X/Y positions of each rectangle but I can’t seem to find the correct formula that doesn’t throw off the whole look of the cursor.

react native: reduce all data

now i learning react native, can someone explain me? how to sum json data to text.
example i have crypto json data in SAMPLE_DATA and i want to sum the current_price.

i read in documentation, its using reduce, but i don’t understand how to apply

const reducer = (previousValue, currentValue) => previousValue + currentValue;

const HomeScreen = () => {
return(
<Text data={SAMPLE_DATA}>{current_price.reduce(reducer)</Text>
)
}

but it’s error, i don’t understand

jQuery: Cannot select val=” from generated dropdown list

I have the following JS for generating a dropdown list for provinces/states:

var populateList = function (list, element) {
    element.append("<option val=''>Select...</option>")
    list.forEach(function (val) {
        element.append("<option val=" + val[0] + ">" + val[1] + "</option>");
    })
}

var canProvinces = [
    ['ON', 'Ontario'],
    ['QC', 'Quebec'],
    ['NS', 'Nova Scotia'],
    ['NB', 'New Brunswick'],
    ['MB', 'Manitoba'],
    ['BC', 'British Columbia'],
    ['PE', 'Prince Edward Island'],
    ['SK', 'Saskatchewan'],
    ['AB', 'Alberta'],
    ['NL', 'Newfoundland and Labrador'],
    ['NT', 'Northwest Territories'],
    ['YT', 'Yukon'],
    ['NU', 'Nunavut']];

The idea I’m working towards is when the user switches countries in a form, the system can use populateList() to switch to a new list whenever the user switches countries. Then I use jQuery to put the province abbreviation in a hidden input field. Here is the code in the form:

<script src="list-of-provices/states-from-above.js"></script>

<input id="UserCountry" value="CA" type="text" /> <!-- to be converted to dropdown when issue resolves -->

<select id="province-select" name="province-select"></select>

<input id="Province" type="hidden"/>

<script>
$(document).ready(function () {

   if ($('#UserCountry').val() == 'CA') {
            populateList(canProvinces, $("#province-select"));
        } else if ($('#UserCountry').val() == 'US') {
            populateList(usaStates, $("#province-select"));
        }

    $('#province-select').bind('input propertychange', function () {

           //something wrong here? Returns full name, not 2 letter abbreviation.
           console.log($("#province-select").val())

           $('#Province').val($("#province-select").val())
        })
});
</script>

I haven’t got to the Country switching part yet because, despite everything I’ve tried, $("#province-select").val() returns the Text from the dropdown, not the value. I have not been able to find a reason for this. Here is the HTML generated by the code:

<select id="province-select" name="province-select">
   <option val="">Select...</option>
   <option val="ON">Ontario</option>
   <option val="QC">Quebec</option>
   <option val="NS">Nova Scotia</option>
   <option val="NB">New Brunswick</option>
   <option val="MB">Manitoba</option>
   <option val="BC">British Columbia</option>
   <option val="PE">Prince Edward Island</option>
   <option val="SK">Saskatchewan</option>
   <option val="AB">Alberta</option>
   <option val="NL">Newfoundland and Labrador</option>
   <option val="NT">Northwest Territories</option>
   <option val="YT">Yukon</option>
   <option val="NU">Nunavut</option>
</select>

Is there something I am missing? $("#province-select").val() should return the val=”” from the dropdown, but for me it returns the text.

Any thoughts?

PHPMailer install?

I am trying to set-up a ‘forgot-password’ function and my script do have all what i need, but i don’t know how to set-up PHPMailer for it. I already have PHPMailer script installed

Where i put this script?

<?php
use PHPMailerPHPMailersrcPHPMailer;
use PHPMailerPHPMailersrcException;

require("Exception.php");
require("PHPMailer.php");
require("SMTP.php");

$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Mailer = "smtp";
$mail->Host = "mail.mail.com";
$mail->Port = "465"; // 8025, 587 and 25 can also be used. Use Port 465 for SSL.
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Username = "[email protected]";
$mail->Password = "";

$mail->From = "[email protected]";
$mail->FromName = " Mailer";
?>

I am using IIS

HTML and ejs Tags Messed Up After Save

I am pretty new to coding and learning templating at the moment. I am having trouble with html and ejs tags auto formatting after save.

As you can see in the images below (sorry, cannot embed images on the post yet since I am new here), html and ejs tags get separated after saving the file and it looks ugly. How can I prevent them from separating?

‘Files:Associations’ setting already has ‘*.ejs – html’.
‘Emmet: Include Languages’ setting also has ‘ejs – html’.
‘Editor: Default Formatter’ is set to None.
Extensions I have are ‘EditorConfig for VS Code’ and ‘EJS language support’

BeforeSave

AfterSave

Files: Associations setting

Emmet: Include Languages

How to Set Focus Infowindow Marker Google Maps?

good morning from Indonesia. I want to display a location on google maps whose data is fetched from a database. So far, I’ve been able to do it. But, there is still a problem when displaying the infowindow as shown below.

enter image description here

When I click on one of the markers, it can bring up an infowindow with data from that marker.

enter image description here

And when I click on another marker, it also displays data from that marker. But the infowindow still focuses on the same marker.

How to fix it? the following code that I have made.

<script>
    function initMap() {
        const map = new google.maps.Map(document.getElementById("map"), {
            zoom: 10,
            center: { lat: -6.261493, lng: 106.810600 },
    });
    
    setMarkers(map);
    }
    
    const locations = @php print_r(json_encode($markers)) @endphp;
    
    function setMarkers(map) {
    
    for (let i = 0; i < locations.length; i++) {
        
        const location  = locations[i];

        let html = "";
        html += `<div id="content-${location[0]}">`;
        html += `<div id="siteNotice">`;
        html += `</div>`;
        html += `<h1 id="firstHeading" class="firstHeading">${location[1]}</h1>`;
        html += `<div id="bodyContent">`;
        html += `<p>${location[2]}</p>`;
        html += `<a href="reports/show/${location[0]}" class="btn btn-dark btn-sm">Detail</a>`;
        html += `</div>`;
        html += `</div>`;

        const infowindow = new google.maps.InfoWindow({
            content: html,
        });

        marker = new google.maps.Marker({
        position: { lat: parseFloat(location[4]), lng: parseFloat(location[5]) },
        map,
        title: location[3]
        });

        marker.addListener("click", () => {
            infowindow.open({
            anchor: marker,
            map,
            shouldFocus: true,
            });
        });

        console.log(location);
    
        }
    }
</script>

Thank you

switch statement is executing false case in javascript [duplicate]

I know switch statement must use return or break.
but I can not figure out why false condition is executing in this example.

function test(a) {
  let result = '';
  switch(true) {
      case a > 1: {
        result = 'more than one';
      }
      case a > 2: {
        result = 'more than two';
      }
      case a > 3: {
        return result = 'more than three';
      }
      default:
      result = 'not a number';
}} 
test(2)

I think 2 > 2 and 2 > 3 are false condition
but result is 'more than three'
why false case is executed?

How to save data when user move away from the web page on mobile devices?

I am creating an HTML web app and getting all data from API calls. This mostly works on mobile devices(IOS/Android). There are some pages that users can navigate these pages(every page has a previous/next button). I wanted to save page data when the user tries to move away from the webpage(tab close/minimize the browser/ swipe between apps). This app focuses on mobile devices and needs to save data when users move away from the web page. I tried onunload, onbeforeunload method but these are not fired. I used ajax calls to save data with an API. What is the best way to fix this problem?

Websocket’s onmessage data length

When i use origin websocket to send data(it’s length is very small),the serve at onmessage can receive the data ,but when the data’s length exceed about 1.2kb,the serve at onmessage cannot receive any data but blank,anyone meet this question? how to fix this question?