The infinite slide from right to left

I am using the below code for the slider from right to left infinite loop but it’s not working.

I have found so many solutions but they have been added multiple times Same HTML. I don’t want that.

.slider-container {
    width: 100%;
    overflow: hidden;
  }
  
  .slider {
    display: flex;
    animation: slideRightToLeft 03s linear infinite;
  }
  
  .slider-card {
    flex: 0 0 auto;
    width: 200px; 
    height: 150px; 
    background-color: #f0f0f0; 
    margin-right: 20px; 
  }
  
@keyframes slideRightToLeft {
  0% {
    transform: translate(0, 0);
  }
  100% {
    transform: translate(-30%, 0);
  }
}
<div class="slider-container">
  <div class="slider">
    <div class="slider-card">Card 1</div>
    <div class="slider-card">Card 2</div>
    <div class="slider-card">Card 3</div>
    <div class="slider-card">Card 4</div>
    <div class="slider-card">Card 5</div>
    <div class="slider-card">Card 6</div>
    <div class="slider-card">Card 7</div>
    <div class="slider-card">Card 8</div>
    <div class="slider-card">Card 9</div>
    <div class="slider-card">Card 10</div>
    <div class="slider-card">Card 12</div>
    <div class="slider-card">Card 13</div>
    
    <!-- Add more cards as needed -->
  </div>
</div>

How does an iframe read an event listener js function

I have two functions in my Java Script file that increments and decrements their respective counts in a modal on the homepage if a question’s answer’s button is correct or incorrect.

— in script.js —

/* calling functions to increment/decrement */
correctInc.addEventListener("click", () => {
  right();
  input1.value = getCorrect();
});

incorrectInc.addEventListener("click", () => {
  wrong();
  input2.value = getIncorrect();
});

An iFrame is on homepage.html

<p><iframe id="iframe" src="funfacts.html" height="200" width="300" title="Fun Facts"></iframe></p>

Here is the test question, which pops up in an iframe which also has the script.js file in it already. I want these button clicks to also use the previous code to see how many questions the user got wrong/right but it’s not communicating with the other HTML file’s code to disply that within my counts.

  
<!-- Review Question | Modal -->
<div id="reviewMod" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title">Review</h4>
        </div>
        
        <!-- Question answers -->
        <div class="input-group">
            <p>Creeper had a specific antivirus?</p>
                <button id="right" type="button" class="btn" data-dismiss="modal">Yes</button>
                <button id="wrong" type="button" class="btn" data-dismiss="modal">No</button>
                <button type="button" class="btn">Maybe</button>
        </div>
        
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
    </div>

  </div>
</div>

Im not currently trying to use jquery

I tried calling the JS file in the iframe html file and it doesn’t communicate with the homepage.html file which is also calling the JS file.

Forminator form – forcing users to check a certain amount of options in a specific checkbox

the problem is this: I created a form with the forminator plug-in. This form contains 12 checkboxes, for which I would like the user to be able to select a certain number of boxes (1 for checkboxes 1 to 10, 8 for 11 and 12). I found the code online to limit the checkboxes:

<?php
/**
 * Plugin Name: [Forminator Pro] - Restrict select the multiple field(s).
 * Description: [Forminator Pro] - Restrict select the multiple field(s) (select/checkbox).
 * Author: Thobk @ WPMUDEV
 * Jira: SLS-918
 * Author URI: https://premium.wpmudev.org
 * License: GPLv2 or later
 */
if ( ! defined( 'ABSPATH' ) ) {
    exit;
} elseif ( defined( 'WP_CLI' ) && WP_CLI ) {
    return;
}
/**
 * 1. Add custom class wpmudev-option-limit inside STYLING tab of a multiple field's settings: https://share.getcloudapp.com/KoulYdY9
 * 2. Enter the form id(s) in the snippet code bellow that you want to apply this custom code: form_ids: [123, 456]
 * 3. Modify the limit for each MU field:
 * limit: {
 * 'checkbox-2': 5,//[field-id]:[limit]
 * 'select-1': 2
 * }
 */
add_action( 'wp_footer', function(){

    global $post;

    if( ! $post instanceof WP_Post || ! has_shortcode( $post->post_content, 'forminator_form' ) ) {
        return;
    }

    ?>
    <style>
        .forminator-ui .wpmudev-option-limit .wpmudev-disabled{
            color:#ddd!important;
        }
        .forminator-ui .wpmudev-option-limit .wpmudev-disabled span[aria-hidden]{
            border-color: #ddd!important;
        background-color: #ddd!important;
        }
    </style>
    <script type="text/javascript">
        
        ($=>{

            const _forminator_restrict_multiple_fields = {
                form_ids: [10097],
                limit: {
                    'checkbox-1': 1,
                    'checkbox-2': 1,
                    'checkbox-3': 1,
                    'checkbox-4': 1,
                    'checkbox-5': 1,
                    'checkbox-6': 1,
                    'checkbox-7': 1,
                    'checkbox-8': 1,
                    'checkbox-9': 1,
                    'checkbox-10': 1,
                    'checkbox-11': 8,
                    'checkbox-12': 8,
                },
                run : function( e, form_id ) {
                    if( _forminator_restrict_multiple_fields.form_ids.indexOf( form_id ) === -1 ){
                        return;
                    }
                    let _form = $( "#forminator-module-" + form_id );

                    _form.find('.wpmudev-option-limit').each(function(){
                        let _field = $(this),
                                checkbox_fields = _field.find( ":checkbox" );
                        if( checkbox_fields.length ){
                            checkbox_fields.on('change', function (e) {
                                let _parent = $(this).closest('.wpmudev-option-limit'),
                                        _parent_id = _parent.attr('id'),
                                        _selected = _parent.find(':checkbox:checked').length;
                                if( _parent_id in _forminator_restrict_multiple_fields.limit && _selected >= _forminator_restrict_multiple_fields.limit[ _parent_id ]){

                                    // save latest value.
                                    _field.data('latest_value', $(this).val() );
                                    // disable other options.
                                    _parent.find(':checkbox:not(:checked)').each(function(){
                                        $(this).prop('disabled', true).parent().addClass('wpmudev-disabled');
                                    });
                                }else{
                                    _parent.find(':checkbox:disabled').each(function(){
                                        $(this).prop('disabled', false).parent().removeClass('wpmudev-disabled');
                                    });

                                    _field.removeData('latest_value');
                                }
                            });
                        }

                        // auto remove previous value when riched the limit.
                        $(this).on('click', '.wpmudev-disabled', function(){
                            let _latest_value = _field.data('latest_value') ;
                            if( _latest_value ){
                                let _previous_opt = $(this).closest('.wpmudev-option-limit').find('input[value="'+ _latest_value +'"');
                                if( _previous_opt.length ){
                                    _previous_opt.trigger('click');
                                    $(this).removeClass('wpmudev-disabled').find('input:disabled').removeAttr('disabled');
                                }
                            }
                        })
                    });
                }
            }

            $(document).ready(function(){
                $.each(_forminator_restrict_multiple_fields.form_ids, function(i, _form_id){
                    _forminator_restrict_multiple_fields.run(this,_form_id);
                });
                $(document).on( 'response.success.load.forminator', _forminator_restrict_multiple_fields.run );
            });
        })(jQuery);

    </script>

    <?php
}, 999 );

However, checkboxes 11 and 12 allow me to continue even if I have selected fewer than 8 options. How can I force the user to mandatory select 8 options for the last two checkboxes? A thousand thanks!

I’m still pretty inexperienced, but I’ve tried many different solutions without being able to figure it out.

Webpack loading remote module on an incorrect endpoint

I am using webpack’s module federation plugin for a microfrontend architecture.

The container app sends a request to the following

new ModuleFederationPlugin({
      name: 'container',
      filename: 'remoteEntry.js',
      remotes: {
        huddle: 'microfrontend@{domain}/AdditionalDir/remoteEntry.js'
      },

    })

For more context both frontends are on nginx pods served through a kubernetes cluster and the requests also get handled through an nginx proxy.

RemoteEntry.js gets loaded fine however the chunks get loaded like this domain/hash.js while i want it to load like this {domain}/AdditionalDir/hash.js is there a way to specify where i load my remote modules from ?? I’ve tried playing around with the publicPath in webpack’s config with no luck.

Javascript – I want to sort an array with multiple criteria

Let’s say I have this array:

const services = [
    { id: 100, priority: 'Y', count: 300, payout: '30', id_region: 137 },
    { id: 101, priority: 'N', count: 200, payout: '40', id_region: 153 },
    { id: 102, priority: 'Y', count: 400, payout: '30', id_region: 137 },
    { id: 103, priority: 'Y', count: 500, payout: '50', id_region: 153 },
    { id: 104, priority: 'Y', count: 800, payout: '80', id_region: 222 }
];

And this global variable:

var regionsFound = ['153'];

I want to sort:

  • first the id_region if that appears in regionsFound
  • then priority ‘Y’ first
  • then highest payout
  • then the id_region if that doesn’t appear in regionsFound
  • then count

Here’s my code:

services.sort((a, b) => {
 if (regionsFound.indexOf(a.id_region.toString()) >= 0 && regionsFound.indexOf(b.id_region.toString()) >= 0){
    if (a.priority == 'Y' && b.priority == 'N'){
        return -1;
    } else if (a.priority == 'N' && b.priority == 'Y'){
        return 1;
    }
    return b.payout - a.payout;    
 } else if (regionsFound.indexOf(a.id_region.toString()) >= 0 && regionsFound.indexOf(b.id_region.toString()) < 0){
    return -1;
 } else {
    return b.count - a.count; 
 }
});

So the result should be:

const services = [
    { id: 103, priority: 'Y', count: 500, payout: '50', id_region: 153 },
    { id: 101, priority: 'N', count: 200, payout: '40', id_region: 153 },
    { id: 104, priority: 'Y', count: 800, payout: '80', id_region: 222 },
    { id: 102, priority: 'Y', count: 400, payout: '30', id_region: 137 },
    { id: 100, priority: 'Y', count: 300, payout: '30', id_region: 137 }
];

I don’t know where’s the error.

How to individualize a reused component in React JS

I have an iteration of cards with which each cards needs its own MoreoptionPopup component. Right now with the code I have implemented, once I click the more options icon all the More option Popups open up. And I get why they behave that way. But, I cannot figure out how to make each instance of MoreoptionPopup component a unique item that will only be opened from its own parent element.

I tried adding the key attribute to the MoreoptionPopup but still didn’t work correctly.

See image attached for a visual representation of the behavior I would like to happen.

return (
    <div className="bucketlist_boards">
      <div className=" boards newBoard">
        <button className="board_openpopup" data-bs-toggle="modal" data-bs-target="#staticBackdrop1" >+ Add New Board </button>
      </div>
      {getBoards.length > 0 ? (
        getBoards.map((item, id) => (
          <div key={id} className={`boards ${id}`}>
            <span className="more-options" onClick={(e) => handleMoreOptionsClick(e, item)} >
              <img src={Moreoption} alt="More options" />
            </span>
            <span className="board-name">{item.name}</span>

            { showPopup && (
              <MoreoptionPopup
                onClose={handleClosePopup}
                onEdit={() => {
                  setShowEditPopup(true); // Open the EditPopup
                  setCurrentImage(currentBoard?.image_url); // Set the current image URL
                }}
                onMakePublic={() => {
                  /* Implementation */
                }}
                onDelete={() => {
                  /* Implementation */
                }}
              />
            )}
            {showEditPopup && (
              <EditPopup onClose={handleClosePopup} imageSrc={currentImage} />
            )}
          </div>
        ))
      ) : (
        <div className="bordercard">
          <div className="welcome-message">
            Welcome.
          </div>
        </div>
      )}
    </div>
  );
};

enter image description here

How can I track quiz answers width GTM?

I have a simple javascript quiz. The html is pretty simple :

 <div class="quiz-container">
      <div id="question-container">
        <h3 id="question">Question</h3>
        <div id="answer-buttons"></div>
      </div>
      <button id="next-btn" class="btn hide">Next</button>
      <div id="result" class="hide"></div>
      <button id="restart-btn" class="btn hide">restart</button>
    </div>

When clicking on the Next button, there is no page reload, the content is simply replaced via JavaScript;

So we pass the different screens, and the different answers are injected into the div#asnwer-button. The IDs of the radio buttons are incremented, and are always the same regardless of the screen. So for each question, I have #answer1, #answer2 etc..

So I always have the same IDs for each screen (question) and the same ids for each radio button.

I’m asked if I can track the user journey, i.e., up to what question it was, what were the answers ticked off… I have the impression that this is impossible in the first place, because there is no differentiating element.

Maybe I’m wrong. Anyone know if this is possible?

I followed this tutorial. But as he says, when you switch from one screen to another, there’s no data persistence, and he’s not talking about whether or not you can track radio buttons as part of a JavaScript quiz.

refresh AWS Cognito access token workflow in browser with javascript v2

I’ve got a simple web app (I’m not really a dev) which I’ve based off of this tutorial. Everything I’ve done is written in plain javascript (no React, etc) and gets deployed to a git repo with .js files run on the user’s browser.

Everything is configured and works perfectly, but now I’m trying to extend functionality. The issue I’m facing is that users can spend more than 60 minutes on a single page (some websocket and API interactions which are validated using their access token), and the access token will expire. I believe it isn’t refreshing through the normal SDK operations because they are staying on the same page the whole time.

Given this, I’m trying to find a solution to check if a token needs refreshing, and refresh it if near the expiration time. I’ve tried to implement Use Case 32 from here, but can’t seem to get it to work. That code snippet references AWS.config.credentials.needsRefresh(), but the AWS-sdk .js file wasn’t included in the original repo I started from. I’ve tried downloading the latest v2 AWS-sdk .js file, and also identifying a similar needsRefresh function in the AWS-cognito-sdk .js to no avail.

The weird thing is when I try and check for needsRefresh, it throws the following error

console.log('config' in AWS) --> True
console.log('credentials' in AWS.config) --> True
console.log('needsRefresh' in AWS.config.credentials) --> Uncaught TypeError: Cannot use 'in' operator to search for 'needsRefresh' in null

Is there another way to either: 1) check if the token needs refreshing using something similar to the use case mentioned above, or 2) manually inspect the JwtToken to see if I need refresh the token?

Is there a way to integrate React with C?

I need a way to create a application where my frontend is React and my backend is in C.

I’m working on a university project to create a simple game, and we need to make it in pure C. But i want to create a frontend in React, is there a way to integrate them?

Deploying a different index page using Vercel with json-server

I am trying to deploy a pet project application of mine to Vercel. This application uses vanilla JavaScript along with json-server to fake a REST API endpoint for videos. The endpoint is solely for consumption purposes, and indeed, the application includes an index file located at ./public/index.html. To configure json-server, I initiated the process by executing the commands npm init -y followed by npm install json-server. In the root directory of my project, I created the server.js file containing the following code:

const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('./backend/videos.json');
const middlewares = jsonServer.defaults();

server.use(middlewares);
server.use(router);
server.listen(3000, () => {
  console.log('JSON Server is running')
});

I also added the “start” script into my package.json like the following:

{
  "name": "vidflow",
  "version": "1.0.0",
  "description": "",
  "main": "script.js",
  "scripts": {
    "start": "node server.js",
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "json-server": "^0.17.4"
  }
}

And finally, I added the vercel.json with the following code:

{
  "version": 2,
  "builds": [
    {
      "src": "server.js",
      "use": "@vercel/node",
      "config": {
        "includeFiles": ["./backend/videos.json"]
      }
    }
  ],
  "routes": [
    {
      "src": "/(.*)",
      "dest": "server.js"
    }
  ]

}

After deploying it to Vercel the endpoint is working as expected but the index page is set json-server index page telling me that the json-server is successfully running, and that’s not what I want. I want to display my index page from ./public/index.html. How can I do that?

Download big file in chunks from s3 and save it to disk in browser with aws sdk v3

I would like to download big file in chunks from s3 and save it to disk in browser and I am trying to do this with something like https://github.com/awsdocs/aws-doc-sdk-examples/blob/c682a07a1e6abce793e3c32ef3b9661fa723d0ff/javascriptv3/example_code/s3/scenarios/multipart-download.js#L38

How can I create a writable stream or temporary file in browser, so I can save it later on disk with somehing like

let blob = new Blob([data.Body], {type: data.ContentType});
let link = document.createElement('a');
let filename = key.replace(selectedFolder, "");
link.href = window.URL.createObjectURL(blob);
link.download = filename;
link.click();

How to provide service at the module level?

I am trying to create a provider for a library module, that when added triggers my factory provider. However, when I do so, the provider never executes the console.log so I know it isn’t running…

Here is the example service that I am trying to instantiate:

@Injectable()
export class ExampleService {
  addOptions(...options: any[]) {
    // Set options
  }
}

When the module is created, I would like to create the service and add some default options to it, so I made a factory provider like this, as I don’t want to add it at the component level, or for every instance of ExampleService. Just a one time thing for this module.

@NgModule({
  declarations: [ExampleComponent],
  exports: [ExampleComponent],
  providers: [
    {
      provide: ExampleService,
      multi: false,
      useFactory: () => {
        console.log('Creating Example Service...');
        const service = new ExampleService();
        service.addOptions('one', 'two', 'three');
        return service;
      }
    }
  ],
})
export class LibraryModule {}

I also have a component that I want to also inject the service into, but not share the same instance as the one in the module, so I did this:

@Component({
  providers: [ExampleService]
})
export class ExampleComponent {
  constructor(private example: ExampleService) {}
}

When a team in my company uses our library, they would import it like this, and the options would automatically be set from the LibraryModule.

@NgModule({
  imports: [LibraryModule]
})
export class App {}

Currently the one in the component gets created as intended, but the one in the module is not running the factory as I don’t see output from the console.log. What Do I need to do to fix this? Or, is this not the correct way to do this?


Note: I am testing this using storybook, not sure if that makes a difference.

Which looks like this:

@Component({
  standalone: true,
  imports: [LibraryModule]
})
export class StorybookExample {
  constructor(private example: ExampleService) {}
}

export default {
  title: 'Test',
  component: StorybookExample,
} as Meta<StorybookExample>;

GeoJSON MultiPolygon Inversion Works for All Federal Districts of Russia Except Siberia in D3.js Map

I’m working on a map visualization using D3.js and GeoJSON data for Russian federal districts. The goal is to display each district as a filled polygon fill to highlight certain areas.

I followed the advice from this Stack Overflow answer to invert the polygons, applying this transformation globally to each district:

[
  [0, 90], [180, 90], [180, -90], [0, -90], [-180, -90], [-180, 0], [-180, 90], [0, 90]
]

This approach worked well for all districts except showing a weird line for the Siberian Federal District on the top left

I tried to play with the transformation array (flipping, changing order, scaling) but haven’t succeed to fix it.

Would appreciate any help!

Component code:

function Map({
  statistics,
  style = {},
  colorsForScale = ["#F4F3EE", "#969AFF", "#000"]
}) {
  useEffect(() => {}, [statistics]);

  // Map
  const [regionDescription, setRegionDescription] = useState("");
  const [regionValue, setRegionValue] = useState("");

  const { language } = useLanguage();
  const [translations, setTranslations] = useState([]);

  useEffect(() => {
    getTranslations()
      .then((data) => {
        setTranslations(data);
      })
      .catch((err) => {})
      .finally(() => {});
  }, []);

  const projection = d3geo
    .geoConicConformal()
    .scale(300)
    .center([54, 44])
    .rotate([-110, 0]);

  console.log('projection',projection)  
  const path = d3geo.geoPath().projection(projection);
  console.log('path',path)
  const values = statistics.map((item) => item.value);
  const min = Math.min(0);
  const max = Math.max(100);

  const getScale = () => {
    return [min, (min + max) / 2, max];
  };

  var colorScale = d3.scaleLinear(getScale(), colorsForScale);

  const mapElements = useMemo(() => {
    if (statistics.length > 0) {
      console.log('geoData.features',geoData.features)
      return geoData.features.map((d, index) => {

        const pathD = path(d);
        if (!pathD) return null; // Skip if path is not defined

        const relevantStatistics = statistics.filter(
          (item) => item.name === d.properties.name
        )[0];
        const color = relevantStatistics
          ? colorScale(relevantStatistics?.value)
          : "lightgrey";
        return (
          <path
            key={"map-element-" + d.properties.name}
            name={d.properties.name}
            d={path(d)}
            fill= {color}
            stroke="#0e1724"
            strokeWidth="0.5"
            strokeOpacity="0.5"
            opacity="0.9"
            onMouseEnter={(e) => {
              d3.select(e.target).attr("opacity", 1);
            
              if (language === "ru") {
                setRegionDescription(relevantStatistics.name);
              } else {
                const translation = translations.find(
                  (t) => t.name_ru === relevantStatistics.name
                );
                setRegionDescription(
                  translation ? translation.name_en : relevantStatistics.name
                );
              }
              setRegionValue(Math.round(relevantStatistics.value));
            }}
            onMouseOut={(e) => {
              d3.select(e.target).attr("opacity", 0.9);
              setRegionDescription("");
              setRegionValue("");
            }}
          />
        );
      });
    } else {
      return (
        <>
          <p>No map data.</p>
        </>
      );
    }
  }, [geoData, statistics]);

  // Legend
  const mapTooltip = useRef(null);

  useEffect(() => {
    if (!mapTooltip.current) return;
  }, [mapTooltip]);

  const setTooltipPosition = (x, y) => {
    if (!mapTooltip.current) return;
    let newX = x - mapTooltip.current.offsetWidth / 2;
    newX = Math.max(newX, 0);
    mapTooltip.current.style.transform = `translate(${newX}px, ${y + 12}px)`;
  };

  if (statistics) {
    return (
      <div
        onPointerMove={(ev) => {
          setTooltipPosition(ev.clientX, ev.clientY);
        }}
        style={{ position: "relative", display: "inline-block", ...style }}
      >
        <svg className="map">
          <g className="map">{mapElements}</g>
        </svg>

        <div
          className={`map-tooltip ${!regionDescription && "hidden"}`}
          ref={mapTooltip}
        >
          {/* <div className="tip"></div> */}
          {regionDescription && (
            <>
              <h3>{regionDescription}</h3>
              <h1>{regionValue}%</h1>
            </>
          )}
        </div>
      </div>
    );
  }
  return <></>;
}

export default Map;