JavaScript link with html [closed]

How to link an external JavaScript file with an html file in VSCode when Bootstrap is linked.

I need link external JavaScript file with HTML file when Bootstrap linked but one script tag used for Bootstrap as well as I don’t don’t know how to link external JavaScript file with HTML file.

Is there a way to rotate the background image of a Canvas without rotating the whole canvas? See example

Its a rough sample but would like to move the needle image as mouse moves without rotating the doughnut chart. Or is there a better way to approach it?

html:

<canvas id="myChart" style="background:url('https://th.bing.com/th/id/R.2db409a16ede3960a7b29d352023f96b?rik=fmfST8altAgOzw&riu=http%3a%2f%2fwww.clker.com%2fcliparts%2fM%2fx%2fk%2f6%2fA%2fw%2fred-compass-needle-hi.png&ehk=lc9ZHlPQDSYqkD9apB6GLPDGgANmGVqnzx05ht2zekw%3d&risl=&pid=ImgRaw&r=0')no-repeat center; background-size:auto 30%; " height="100"></canvas>

script:

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'doughnut',
  data: {
    labels: ["Red", "Blue", "Yellow"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)'
      ],
      borderColor: [
        'rgba(255,99,132,1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)'
      ],
      borderWidth: 1
    }]
  },
  options: {
    tooltips: {
      callbacks: {
        title: function(tooltipItem, data) {
          return data['labels'][tooltipItem[0]['index']];
        },
        label: function(tooltipItem, data) {
          return data['datasets'][0]['data'][tooltipItem['index']];
        },
        afterLabel: function(tooltipItem, data) {
          var dataset = data['datasets'][0];
          var percent = Math.round((dataset['data'][tooltipItem['index']] / dataset["_meta"][0]['total']) * 100)
          return '(' + percent + '%)';
        }
      },
      backgroundColor: '#FFF',
      titleFontSize: 16,
      titleFontColor: '#0066ff',
      bodyFontColor: '#000',
      bodyFontSize: 14,
      displayColors: false
    }
  }
});
var img = $('#myChart');
if (img.length > 0) {
    var offset = img.offset();

    function mouse(evt) {
        var center_x = (offset.left) + (img.width() / 2);
        var center_y = (offset.top) + (img.height() / 2);
        var mouse_x = evt.pageX;
        var mouse_y = evt.pageY;
        var radians = Math.atan2(mouse_x - center_x, mouse_y - center_y);
        var degree = (radians * (180 / Math.PI) * -1) + 90;
        img.css('-moz-transform', 'rotate(' + degree + 'deg)');
        img.css('-webkit-transform', 'rotate(' + degree + 'deg)');
        img.css('-o-transform', 'rotate(' + degree + 'deg)');
        img.css('-ms-transform', 'rotate(' + degree + 'deg)');
    }
    $(document).mousemove(mouse);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id="myChart" style="background:url('https://th.bing.com/th/id/R.2db409a16ede3960a7b29d352023f96b?rik=fmfST8altAgOzw&riu=http%3a%2f%2fwww.clker.com%2fcliparts%2fM%2fx%2fk%2f6%2fA%2fw%2fred-compass-needle-hi.png&ehk=lc9ZHlPQDSYqkD9apB6GLPDGgANmGVqnzx05ht2zekw%3d&risl=&pid=ImgRaw&r=0')no-repeat center; background-size:auto 30%; " height="100"></canvas>
https://jsfiddle.net/wtzj4fhr/

How to put marker on top center of the google maps

I am new to google maps and following is code from google maps
The marker is in middle of the screen but how can I appear at top center (top middle) of the screen instead of center center on x and y.

function initMap() {
  const myLatLng = { lat: -25.363, lng: 131.044 };
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 4,
    center: myLatLng,
  });

  new google.maps.Marker({
    position: myLatLng,
    map,
    title: "Hello World!",
  });
}

window.initMap = initMap;

enter image description here

floating value not being shown up correctly

im building a shopping cart for an application and im trying to get the total value of the sum between all the elements with the class “.totalPrice”.

everything is working fine and the sum is being done correctly untill i try to sum values like 1.005.67 + 1.050.00, then the result is printed like this

enter image description here

this is my code:

function sum() {
  var sum = 0;
  $('.totalPrice').each(function () {
    sum += parseFloat(this.value);
  });
  $("#total").text("Total: $" + sum.toFixed(2).replace(".",","));        
}
<label>
<label> Value 1 </label>
<input type="text" class="totalPrice">
<br><br><br>
<label> Value 2 </label>
<input type="text" class="totalPrice">
<br><br><br>
<button onclick="sum()"> calculate </button>
<h1 id="total"> </h1> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>

javascript calling before ajax call request

I have a problem in my coding, I made it very very short so that I could get a fast answer, and not to waste your time, I have an input text, an input number and a button, when I click a button, a function would call named (getvalue), but the problem is the ajax call run after the javascript code, the big project that am working on, one of the ajax call, is that if the other php file returns invalid, then I don’t want to apply .val() in the input text with id (num), cause if it’s invalid, and the calculation is wrong, why should the javascript code work?!, I don’t want to be run if the ajax returns invalid, that’s all I have some ajax call requests inside this function in my project and need to run and call before any other javascript codes, how could I do that?!

here is the index file php code:

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <input type="text" name="" id="inp">
    <button onclick="getValue()">Click Me</button>

    <br>
    <input type="text" name="" id="num">

    <script src="jquery-3.6.1.min.js"></script>
    <script>
        function getValue() {

            var inpText = $("#inp").val();
            var inpNum = $("#num");
            alert("hey ")
            alert("hello world ")
            //   javascript coding..... aproximately 100 lines

            inpNum.val("random num...")


            $.ajax({
                type: 'POST',
                url: 'validate.php',
                data: {
                    myInput: inpText,
                },
                complete: function(r) {
                    if (r.responseText == "validNum") {
                        alert("valid")
                    } else {
                        alert("invalid number, please enter another number  ")
                    }

                }
            });       
        }
    </script>
</body>

</html>
<?php

again, I made it very simple, just so you understand, I don’t want to delete validate.php file and put the whole code inside index.php, with all other ajax call requests.

Escape quotes in string laravel

I am working with laravel and yajra datatable,
In my database there is a entry like What 'are' "you" doing
I am fetching that data using Laravel query builder,
and then i showed that data in my datatabe.

But in this case datatable gives a error.

How can i fix it

i have tried htmlspecialchars function but not working,
then i edited the entry in database and added backslash in front of quotes here the error is gone but the backslash is visible in the datatable

Javascript – points calculation doesn’t work

I created a simple survey, where every answer to a question gives you different amount of the points. I don’t want the points to be in the value itself so I put it into the javascript.

I cannot find the error why in the console the querySelector throws null:
Uncaught TypeError: document.querySelector(…) is null

HTML code:

<fieldset id="question1">
    <p style="font-weight:600;">What's your favorite color?</p>
    <label><input type="radio" name="q1" id="q1a1" required>Red</label><br>
    <label><input type="radio" name="q1" id="q1a2" required>Blue</label><br>
</fieldset>
<fieldset id="question2">
    <p style="font-weight:600;">How old are you?</p>
    <label><input type="radio" name="q2" id="q2a1">over 18</label><br>
    <label><input type="radio" name="q2" id="q2a2">under 18</label><br>
</fieldset>

Name represent question number and id represent question number together with answer number.

Javascript

var points = {
    "q1": {"q1a1": 0, "q1a2": 1},
    "q2": {"q2a1": 0, "q2a2": 3}
};
var totalPoints = 0;

function calculatePoints() {
    for (var i = 1; i <= numQuestions; i++) {
        var selectedAnswer = document.querySelector('input[name="q' + i + '"]:checked').id;
    totalPoints += points[selectedAnswer];
    }
}

I tried to add the calculation of the points into the listener itself but it also throws the same error. Just want the number of points being taken from variable based on the selectedAnswer and calculated and send to the next page with results.

Cannot read property of undefined in comparator function

I have a quicksort algoritm (Hoare Partition Scheme) for objects of my class and three comparators.

class Participant{
login;
fine;
solved;
}

    /*This function should convert array of strings - 
      ['alla 4 100','gena 6 1000','gosha 2 90','rita 2 90','timofey 4 80']
      Into an array of Participant objects and return their names separated by 'n'
      In this format:
      gena
      timofey
      alla
      gosha
      rita
*/
function effectiveSort(membersInfo){
    var sortedMembers = [];
    for (let i = 0; i < membersInfo.length; ++i){
        sortedMembers.push(new Participant);

    
    sortedMembers[i].login = membersInfo[i].split(' ')[0];
    sortedMembers[i].fine = Number(membersInfo[i].split(' ')[2]);
    sortedMembers[i].solved = Number(membersInfo[i].split(' ')[1]);
}
    sortedMembers = (quickSort(sortedMembers, 0, sortedMembers.length - 1, loginComparator));
    sortedMembers = (quickSort(sortedMembers, 0, sortedMembers.length - 1, fineComparator));
    sortedMembers = (quickSort(sortedMembers, 0, sortedMembers.length - 1, tasksAmountComparator));
    
    return sortedMembers.map(a => a.login).join('n');
}

//Comparators for each class field. That's where the problem starts

function loginComparator(firstParticipant, secondParticipant){
    return firstParticipant.login < secondParticipant.login;
}

function tasksAmountComparator(firstParticipant, secondParticipant){
    return firstParticipant.solved >= secondParticipant.solved;
}

function fineComparator(firstParticipant, secondParticipant){

    return firstParticipant.fine >= secondParticipant.fine;
}

//Hoare Partition Scheme

function partition(arr, start, end, compar) {
    const pivotVal = arr[Math.floor((start + end) / 2)];    
    while (start <= end) {
        while (compar(arr[start], pivotVal)) {
            start++;
        }
        while (compar(pivotVal, arr[end])) {
            end--;
        }        
        if (start <= end) {
            let temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;            
            start++;
            end--;
        }
    }    return start;
}

function quickSort(arr, start = 0, end = arr.length - 1, compar) {
    if (start < end) {
        const index = partition(arr, start, end, compar);        
        quickSort(arr, start, index - 1, compar);
        quickSort(arr, index, end, compar);
    }    
    return arr;
}

//Test data
var real_mebmers = ['alla 4 100','gena 6 1000','gosha 2 90','rita 2 90','timofey 4 80'];
var zero_members = ['alla 0 0','gena 0 0','gosha 0 0','rita 0 0','timofey 0 0'];
console.log(effectiveSort(real_mebmers));

The problem starts in these comparators
return (firstParticipant.solved >= secondParticipant.solved); and return firstParticipant.fine >= secondParticipant.fine;
JS will say that

    return (firstParticipant.solved >= secondParticipant.solved);
                             ^
TypeError: Cannot read property 'solved' of undefined

.
Same goes for fineComparator. If I change these return statements to
return (firstParticipant.solved > secondParticipant.solved); and here return firstParticipant.fine > secondParticipant.fine;
Everthing seems fine. But why I can’t check two properties for equality? I checked these properties and they don’t have ‘undefined’ value, but JS somehow sees it…

Multiple Awaits necessary for async function? (Javascript/Playwright)

Im pretty new to using the await keyword, I am used to the older “Promise” like commands used in Cypress.

However one confusion I have is when a function returns a promise, but there is both an await keyword IN the function and when using the function. For example:

async goto() {
    await this.page.goto('https://playwright.dev');
  }

Above is a simple method used in Page Object Model pattern, page.goto returns a promise, so we await it…..which makes sense, but to use that you also have to await via:

await playwrightDev.goto();

So I understand the syntax, because the goto function is async. However I guess I don’t really understand “why” we have to do this. More specifically why the function has to be async. Because the inner command of the function is already waiting for a promise, why does the function itself need to be async. Since it won’t return until the innermost command is done anyways?

Hopefully what I am asking makes sense. I understand the syntax but not WHY it is like this.

back button which should go back to same div/section/position in viewport on the previous page from where I redirected to current page

I want to make a back button on page B which redirects me to the previous page. For this I have used onClick={() => navigate(-1) react hook, but on after redirecting it is showing the page A(previous page) from the top.

I want to redirect to the same section from where I left before going to page B. (hope I am clear)

FYI: I have used <ScrollToTop /> in App.tsx because I want to see every page from the top on redirection/refresh. If I don’t use <ScrollToTop /> then I am not able to get any page from the top.

Please let me know any solution for this. Thanks in advance!

Webrotate 360 apiReadyCallback working only once

I am trying to integrate Webrotate 360 into my Magento 2 website. I have created it as a module and it is working. Now, I want to prepend the site URL before the hotspot’s relative URL. I have prepended it using the API but it only works once. When I click on any of the hotspots, the new image is loaded, but the API for appending the URL is not working in the new image.

require(['jquery', 'webrotate'], function($) {
    jQuery(document).ready(function() {
      jQuery('#wr360PlayerId').rotator({
        licenseFileURL: '<?php echo $this->getViewFileUrl('Idm_InteractiveDemoRoom::webrotate360/license.lic'); ?>',
        configFileURL: '<?php echo $this->getViewFileUrl('Idm_InteractiveDemoRoom::webrotate360/360_assets/Demo Room/Demo Room.xml'); ?>',
        graphicsPath: '<?php echo $this->getViewFileUrl('Idm_InteractiveDemoRoom::webrotate360/imagerotator/html/img/basic'); ?>',
        responsiveBaseWidth: 1000,
        responsiveMinHeight: 0,
        googleEventTracking: false,
        apiReadyCallback: (api, isFullScreen) => {
          api.hotspots.onAction(hotspotConfig => {
            console.log(JSON.stringify(hotspotConfig, null, 4));
            if (hotspotConfig.id == "productpage") {
              hotspotConfig.hotspotInfo.url = "<?php echo $block->getUrl(''); ?>/" + hotspotConfig.hotspotInfo.url
            } else {console.log(hotspotConfig.hotspotInfo.url)
              hotspotConfig.hotspotInfo.url = "<?php echo $this->getViewFileUrl('Idm_InteractiveDemoRoom::webrotate360'); ?>/" + hotspotConfig.hotspotInfo.url
            }
            return hotspotConfig; // Returning false indicates that you don't want to override a default hotspot action.
          });
        }
      });
    });

  });

Plotly show info of all elements when a toggle button is activated

enter image description here
Current: As you may know, in Plotly it is possible to show the info of a bar when hovering on it.

Question: Is there any plotly function or parameter that I can call/set to show all info elements.

Problem: I have stacked bars and all numbers of the stacked bars are expected to appear with the same size regardless of the thickness of the bars. Because some bars are to thin, the font size is becoming small and not readable. The only way to show the value of this thin bars is by hovering on it. But since we have many stack bars (spreaded in x axis) we cannot hover on all stack bars at once. So I expect to have a button that can show all the information of all bars at one click 🙂

Hope the explanation is understanable 🙂
Please ask for more detail 🙂
Super grateful for any helps 🙂

Question: Is there any plotly function or parameter that I can call/set to show all info elements.

Any possible way to convert string format to JSON in javaScript?

   {dataOrList=[{subFlowParam={name=postPrivate_On_Input_OR}, type=SUB_FLOW, tReferenceName=Data_42767_OR_43873}, {subFlowParam={name=postPrivate_On_Input_OR}, type=SUB_FLOW, tReferenceName=Data_42767_OR_43870}], dataOrListInput={Data_42767_OR_43873={DatalRouteId=43873, PrivatePayLoad={name=UpdateLink, payload={"ReadingType": "PRIVATEXplorer;OperationType=Private","TestMeta": {"CustomFields": [{"Name": "LineID","Value": "Line1"},{"Name": "PhaseID","Value": "Phase1"}]}}}}, Data_42767_OR_43870={DatalRouteId=43870, PrivatePayLoad={name=UpdateLink, payload={"ReadingType": "PRIVATEXplorer;OperationType=Private","TestMeta": {"CustomFields": [{"Name": "LineID","Value": "Line1"},{"Name": "PhaseID","Value": "Phase1"}]}}}}}}

I want to convert this string object into JSON for development purpose this response comes from server (device data). I tried JSON.parse(); but not works. also tried with Javascript Convert string in a different format to Json this also for some data it works and for some not works.