How do you serve this different HTML version depending on viewport width?

So I have a rather primitive HTML table, but it should have two versions – one for mobile, one for desktop/tablet.

In the desktop version the table is normal – information is on the left side and the corresponding points are at the right side.

Now in the mobile version there should be a new tablerow which contains the same text in a rowspan of 2.

As far as I am aware, this isn’t possible to do with purely CSS (media queries)…

I am aware you can get the viewport height and width using JavaScript, but then it should be transmitted to an API which gives corresponding content.

  • Is this prototype any good?:

The frontend sends a POST request using Fetch to the Backend with the data of the viewport width and then fetches the corresponding HTML from the Backend via AJAX.

  • Would this work?
  • This looks rather cumbersome and complicated for such basic functionality. Is there a better way to do this?

My pseudocode:
Frontend:

var width = getViewportwidth();
var xhr = new XMLHttpRequest();
xhr.open(width, url);

.fetch(API URL here, options here etc).then {
Ajax call here.addtodomhere("#domelement");
}

Backend:

[/Apiurlhere]
[GET]
if (width) < 600 {
table markup for mobile view here
} else {
table markup for desktop view here 
}

I am using .NET Core for the Backend if it matters.

Play background music node js

I’m programing a game and i would like to play a background sound on all my website.
If I change page I want that the music continue. I add a button settings to turn on or off the sound.
But I trayed many npm functions, no one works.

Have you got solutions for that?

Thanks

Loop function on hover jquery

Can you please tell me if it is possible to execute the function while the hover of the element is done without setInterval? That the function would be looped.

$("#left").hover(function() {
  left_statuses();
})

function left_statuses() {
  var scroll = $(".scroll").scrollLeft();
  var new_scroll = scroll + 100;
  $(".scroll").scrollLeft(new_scroll);
}
.left {
  z-index: 1;
}

.scroll {
  width: 100px;
  height: 50px;
  background: red;
  overflow: hidden;
  overflow-x: scroll;
}

.scroll div {
  width: 1000px;
  height: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="left">
  LEFT
</div>

<div class="scroll">
  <div></div>
</div>

Nestjs @ResolveField() of type Int throws an Error

I want to resolve docsCount field for ModuleStats but I get an error Error: Undefined resolver type error. Make sure you are providing an explicit object type for the “ModuleStatsResolver”

@ObjectType()
export class ModuleStats {
  @Field(() => ID)
  _id: string;
  @Field()
  name: string;
  @Field(() => Int)
  docsCount: number;
}

@Resolver(() => ModuleStats)
export class ModuleStatsResolver {
  @Query(() => ModuleStats)
  async getModuleStats(@Args() args: ModuleArgs) {
    return await this.moduleService.getStats(args);
  }

  @ResolveField("docsCount", () => Int)
  async getDocsCount(@Parent() moduleStats: ModuleStats) {
    return await this.docsService.getCount(moduleStats._id);
  }
}

I can’t store response comes from payment api

ı have been devoloing an e-commerce system but ı have problem with iyzipay payment api. I make successful request and get response from server but I can’t store data comes from server. anyone help?

 let returnedData = {}

  iyzipay.payment.create(paymentRequest, function (err, result) {
    if (err) {
      return next(new CustomError("Ödeme başarısız.", 500))
    } 
     return returnedData = result
  })

  //ı can't see data here and return empty {}
  console.log(returnedData)

  // but ı can see here when ı wait 1 second
  setTimeout(() => {
    console.log(returnedData)
  }, 1000);

How to filter array inside of vue-virtual-scroll-list in Vuejs?

<div id="app">
  <div class="wrapper">
    <virtual-list class="list" style="height: 360px; overflow-y: auto" data-key="key" :keeps="20" :data-sources="computedItems" :data-component="Item" />
    <hr />
    <!-- Create a binding between the searchString model and the text field -->

    <input type="text" v-model="searchString" placeholder="lSources" />
    <p>sortKey = {{ sortKey }}</p>
    <li v-for="item in sortedItems" :key="item">
      <input class="checkbox-align" type="checkbox" :value="item.name" id="productname" v-model="item.checked" /> {{ item.price }} - {{ item.name }}
    </li>
  </div>
  <hr />
  <div class="bbb">
    <button @click="sortKey = 'name'" />name<br />
    <button @click="sortKey = 'price'" />price
  </div>
</div>

I have functionality like, filtering array and according to name, price filter array. Where logic is working fine. But I am not sure, how to place it inside of the vue-virtual-scroll-list and preform the same action inside.

Below is my code https://codesandbox.io/s/live-demo-virtual-list-forked-hwq38?file=/src/App.vue

How to add string beside iterated value of for loop which are divisible by 3,5 & both?

I want to run a loop from 1 to 10 & ​want to print “divisible by 3” beside all the numbers which are divisible by 3 same for 5, print “divisible by both” beside the numbers which are divisible by 3 & 5 both as explained below.

Expected Output:-

  1
  2
  3 'divisible by 3'
  4
  5 'divisible by 5'
  6 'divisible by 3'
  7
  8
  9 'divisible by 3'
 10 'divisible by 5'
 11
 12 'divisible by 3'
 13
 14
 15 'divisible by both'

How to properly use Google Tag script in Next.js?

I read How to load Google Tag Manager with next/script component (Next.js 11)? and I also read this doc page.

But none of them solved my problem.

I want to include Google Tag on many of my sites that are developed using nextjs. Thus I have creatd a simple reusable component:

import Script from 'next/script'

const GoogleTag = ({ identifier }) => {
    if (!identifier || !identifier.startsWith('G-')) {
        throw new Error('Google tag id is not correct;');
    }
    return <>
        <Script
            src={`https://www.googletagmanager.com/gtag/js?id=${identifier}`}
            strategy="afterInteractive"
        />
        <Script id="google-analytics" strategy="afterInteractive">
            {`
          window.dataLayer = window.dataLayer || [];
          function gtag(){window.dataLayer.push(arguments);}
          gtag('js', new Date());

          gtag('config', '${identifier}');
        `}
        </Script>
    </>
}

export default GoogleTag;

And I use it in each of my sites, in the _app.js file, this way:

import Head from 'next/head';
import GoogleTag from '../Base/GoogleTag';

export default function MyApp({ Component, pageProps }) {

return (
        <>
            <Head>
                <GoogleTag identifier='G-9XLT855ZE0' />
            </Head>
            <div>
                application code comes here
            </div>
        </>
    )
}

But I don’t see Google Tag script being loaded in the Chrom’s Dev Tools, int Networks tab.

How to translate webpage from google translate dropdown using custom button?

I want to translate my webpage only for Hindi Language by clicking a custom button.
When I clicked this button. Select Option value change only not translating the webpage.
Can some one help me to fix this issue?

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title> Google Translater for Website </title> 
</head> 
<body>
  <h2>Your Web Page</h2>
  <p>Click on the dropdown button to translate.</p>
  <p>Translate this page:</p>

  <div id="google_translate_element"></div>

// page should be translate after click on this button
  <button type="button" id="hindi">T into Hindi</button>

  <script type="text/javascript">
    function googleTranslateElementInit() {
      new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element');
    }
  </script>

  <script type="text/javascript" src="https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
  <script src="https://code.jquery.com/jquery-3.6.0.slim.min.js"></script>
  <p class="notranslate"> This Paragraph will remain same because it is using notranslate class.</p>

  <p class="translate"> This Paragraph will change because it is using translate class. </p> 

  <script>
    $('#hindi').on('click', function(){

      $('select.goog-te-combo')
      .val('hi')
      .trigger('change');
    })

  </script>
</body>
</html>

Coin toss simulator with user input in prompt, how can i change from prompt to html input and do the exact same thing?

I am currently in the beginning of learning javascript in school and I have a small project to make a coin toss simulator as a way of learning so I am allowed to use others code wich I have done. I am supposed to “create” a simulator where I can flip a coin and it tells me heads or tails and keeps track of the results and it also needs a function where the user can input how many times to toss the coin and the only way I could find is doing it with prompt but I need it to be input in html. Any help is MUCH appreciated. If someone would like to help me with a MAX toss limit of 10 times aswell it would really help!

Thank you in advance
/Andreas

<html lang="en">
<head>
  <!-- Design by foolishdeveloper.com -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flip A Coin</title>
    <!--Google Fonts-->
    <link href="https://fonts.googleapis.com/css2?family=Rubik:wght@400;500&display=swap" rel="stylesheet">
    <!--Stylesheet-->
  <style media="screen">
    *{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    font-family: "Rubik",sans-serif;
}
body{
    height: 100%;
    background-image: url("wp7101128-casino-3d-wallpapers.jpg");
}
.container{
    background-color: rgb(255, 255, 255);
    width: 400px;
    padding: 35px;
    position: absolute;
    transform: translate(-50%,-50%);
    top: 50%;
    left: 50%;
    box-shadow: 15px 30px 35px rgba(0,0,0,0.1);
    border-radius: 10px;
    -webkit-perspective: 300px;
    perspective: 300px;
}
.stats{
    display: flex;
    color: #101020;
    font-weight: 500;
    padding: 20px;
    margin-bottom: 40px;
    margin-top: 55px;
    box-shadow: 0 0 20px rgba(238, 190, 34, 0.788);
    
}


.stats p:nth-last-child(1){
  margin-left: 50%;
}
.coin{
    height: 150px;
    width: 150px;
    position: relative;
    margin: 32px auto;
    -webkit-transform-style: preserve-3d;
            transform-style: preserve-3d;
}
.coin img{
    width: 145px;
}
.krone,.mynt{
    position: absolute;
    width: 100%;
    height: 100%;
    -webkit-backface-visibility: hidden;
            backface-visibility: hidden;
        
        }
.mynt{
    transform: rotateX(180deg);
}
@keyframes spin-mynt{
    0%{
        transform: rotateX(0);
    }
    100%{
        transform: rotateX(1980deg);
    }
}
@keyframes spin-krone{
    0%{
        transform: rotateX(0);
    }
    100%{
        transform: rotateX(2160deg);
    }
}
.buttons{
    display: flex;
    justify-content: space-between;
}
button{
    width: 150px;
    padding: 15px 0;
    border: none;
    font-size: 16px;
    border-radius: 5px;
    cursor: pointer;
}
#flip-button{
    background-color: #15b80f;
    color: #ffffff;
}
#flip-button:disabled{
    background-color: #e1e0ee;
    border-color: #e1e0ee;
    color: #101020;
}
#reset-button{
    background-color: #d11609;
    color: white;
}
  </style>
</head>
<body>
    <div class="container">

        <div class="coin" id="coin">
            <div class="krone">
                <img src="kron.png">
            </div>
            <div class="mynt">
                <img src="mynt.png">
            </div>
        </div>
         <div class="stats">
             <p id="krone-count">Krone: 0</p>
             <p id="mynt-count">Mynt: 0</p>
         </div>
            
         <div class="buttons">
            <button id="flip-button">
                Flip Coin
            </button>
            <div>
                <label for="quantity">How many times to flip?</label>
                <input type="number" id="quantity" min="1" value="1" />
              </div>
            <button id="reset-button">
                Reset
            </button>
           </div>
           
    
    <!--Script-->
  <script type="text/javascript">


main(); // Calls the main function to begin the coin flipping simulation.

let krone = 0;
let mynt = 0;
let coin = document.querySelector(".coin");
let flipBtn = document.querySelector("#flip-button");
let resetBtn = document.querySelector("#reset-button");



flipBtn.addEventListener("click", () => {
    let i = Math.floor(Math.random() * 2);
    
    coin.style.animation = "none";
    if(i){
        setTimeout(function(){
            coin.style.animation = "spin-krone 3s forwards";
        }, 100);
        krone++;
    }
    else{
        setTimeout(function(){
            coin.style.animation = "spin-mynt 3s forwards";
        }, 100);
        mynt++;
    }
    setTimeout(updateStats, 3000);
    disableButton();
});

setTimeout(updateStats, 3000);
function updateStats(){
    document.querySelector("#krone-count").textContent = `Krone: ${krone}`;
    document.querySelector("#mynt-count").textContent = `Mynt: ${mynt}`;

function disableButton(){
    flipBtn.disabled = true;
    setTimeout(function(){
        flipBtn.disabled = false;
    },3000);
}
resetBtn.addEventListener("click",() => {
    coin.style.animation = "none";
    krone = 0;
    mynt = 0;
    updateStats();
});



}
function main() {
    var n = Number(prompt("How many times do you want to flip the coin?")); // Gets the number of times to flip the coin.
    var krone = 0, mynt = 0; // Initiates the heads and tails variables.
    for(var i = 0; i < n; i++) {

        // Uses the Math.random function to generate a random number.
        // If the rand num is less than 1/2, it is classified as heads.
        // Otherwise, the num is above 1/2 and is classified as tails.
        if(Math.random() < 0.50) {
            krone++;
        } else {
            mynt++;
        }

  
       (updateStats);

    document.querySelector("#krone-count").textContent = `Krone: ${krone}`;
    document.querySelector("#mynt-count").textContent = `Mynt: ${mynt}`;
    }

}



    
  </script>
</body>
</html>```

Combine d3.brush with events

In an angular method I do things on the graph at mouse down which then end at mouse up, together with these things I would like to draw a square and I discovered that with d3 there is brush, so I would like to combine things.

  this.svgGraph.on('mousedown', (event: any) => {
     //I do things...
     event.stopPropagation();
  })

 this.svgGraph.call(d3.brush()
  .filter(event => event.button === 2)
  .extent([[0, 0], [400, 400]])
 )

 this.svgGraph.on('mouseup', (event: any) => {
   //I do other things...
 })

How can I make the mouse down do my things and draw the square at the same time, and at the mouse up I finish my things and remove the square?

Changing text depending on date using javascript

I’m trying to switch text depending on dates.

 document.getElementById('test').innerHTML = today.toISOString().substring(0, 10) == '2021-12-05' ? 'A' : 'B';

But I don’t want to update the text after this day, for example, if today is ‘2021-12-05’, the text will show ‘A’ until forever, test B will be displayed before ‘2021-12-05’ . Thanks for your help, much appreciated.

Retuning a single array object value from the map function on a ternary condition. Problem is it returning both the conditions

Here is a code snippet i want to return the supplier id on a condition if at date is less than or equal to rounddate then it should return the supplier ID

const currentRound = 0
const roundDate = new Date('2021-12-02T10:41:57.133Z')
const offers = [ { by: 'supplier',
user_Id: '46a065f05229450e805a0a38d94b0956',
supplier_id: '7a444fea780d90ddc7c35e09104c73b0',
total: 14700,
round: 0,
at: '2021-12-01T10:46:52.278Z' },
{ by: 'supplier',
user_Id: '6fb6562bd52fd70b3f43aea1da76de16',
supplier_id: 'abc7c8e6b5acc1888ebf5d2398c44d0b',
total: 14800,
round: 0,
at: '2021-12-03T04:59:45.137Z', } ]

const suppliersWhoSubmitBid = offers.map(
                (e) => e.round === currentRound && new Date(e.at) <= roundDate && e.supplier_id,
            );

expected result = [ '7a444fea780d90ddc7c35e09104c73b0' ]
actual result = [ '7a444fea780d90ddc7c35e09104c73b0', false]

how to use the variable in snowfalke procedure

  var step0=`select INGESTION_SUCCESSFUL,ingestion_uuid   from FILE_INGESTION_HISTORY where  ingestion_uuid=(
   select ingestion_uuid from registration where registry_subject_uuid=:1
   qualify row_number() over( order by dnb_latest_received_dt desc)=1)`;
   var statement0=snowflake.createStatement( {sqlText: step0,binds: [PARAM_REG_SUB_UUID]} );
   variable1= statement0.execute();
   variable1.next();
   ingsindc=variable1.getColumnValue(1);

ingsuuid=variable1.getColumnValue(2);

when i try to use above ingsuuid in sql where clause it is throwing error

var step1= create or replace temporary table FN_IGSN_REG_LBV1 as select * from registration where ingestion_uuid=**ingsuuid** and (DELETE_INDC=0) qualify row_number() over (partition by REGISTRATION_HASH_KEY order by dnb_latest_received_dt desc, row_created_tmst desc, registration_uuid desc) = 1;

  var statement1=snowflake.createStatement( {sqlText: step1} );
 statement1.execute();
  

React toggle active class between button group array

I made a photo gallery with a filter for categories, but I want to make the active category button to have the active class

I display the buttons by mapping through the galleryData array

    {galleryData.map((item, index) => (
       <button
           key={index}
           onClick={() => filterGalley(item.category)}
           className="filter-button"
       >
           {item.category}
       </button>
    ))}

And onClick I filter the gallery items by category. The value is a string of category type

    const filterGalley = (value) => {
        if (value === 'all') {
            setGalleryItems(galleryData);
            return;
        }

        const filteredData = galleryData.filter(
            (item) => item.category === value
        );

        console.log(value);
        setGalleryItems(filteredData);
    };

How can I pass the active class to the currently viewed category? onMount should be all and after that the one that’s clicked.