malware – Is this javascript code malicious?

a friend visited this site:

  • h-t-t-p-s://adidastore.buzz/adidass/tb.php?_t=1614958342

I malformed the url so no one accidently clicks on it
Below is the code the site is serving.
I don’t know javascript and wanted to know from you, if the code looks malicious?

Thank you!

<html lang="en">
<head>
<meta property="og:type" content="website">
<meta property="og:url" content="https://www.adidas.com/">
<meta property="og:title" content="Adidas Women's Day gift">
<meta property="og:image" content="/img/s/adidas.jpg">
<meta property="og:description" content="Adidas gives away 1 million pairs of shoes">
<title>Adidas Women's Day gift</title>
</head>
<body>
<script type="text/javascript" charset="utf-8">
         function loadScript(url, callback){
            var script = document.createElement ("script")
            script.type = "text/javascript";
            if (script.readyState){
                script.onreadystatechange = function(){
                    if (script.readyState == "loaded" || script.readyState == "complete"){
                        script.onreadystatechange = null;
                        callback();
                    }
                };
            } else {
                script.onload = function(){
                    callback();
                };
            }
            script.src = url;
            document.getElementsByTagName("head")(0).appendChild(script);
        }
        setTimeout(function(){
            loadScript('/j/og.js?_t='+ (new Date()).getTime(),function(){});
        },200);
    </script>
</body>
</html>

javascript – React Native FlatList with Scroll-To-load data

I am creating an application that interacts with spotify. A part of my app is a FlatList screen displaying a list of songs and song controls.
enter image description here

I am under the impression that my FlatList is very poorly optimized, leading to slow load times as you scroll down.

The main issue I want to resolve is this performance issue.

First, the authentication wrapper

import {
  setAccessToken,
  setRefreshToken,
} from '_redux/features/authenticationSlice'
import authHandler from '_utils/authenticationHandler'

async function updateReduxWithValidAccessToken({
  accessToken,
  accessExpiration,
  refreshToken,
}) {
  if (accessToken === null || new Date() > new Date(accessExpiration)) {
    console.log('Access Token is Invalid, Refreshing...')
    console.log('refreshToken=', refreshToken)
    const response = await authHandler.refreshLogin(refreshToken)
    accessToken = response.accessToken
    setAccessToken({
      accessToken,
      accessExpiration: response.accessTokenExpirationDate,
    })
    setRefreshToken({
      refreshToken: response.refreshToken,
    })
  }
  return accessToken
}

Next, the song fetching code. This lives within the component

  const (songs, setSongs) = useState(())
  const (songsToFetch, setSongsToFetch) = useState(100)
  const (page, setPage) = useState(0)

  const getSongsOfPlaylist = async (aToken, aPlaylist, aPage, aLimit) => {
    const response = await authHandler.get(
      `/playlists/${aPlaylist}/tracks`,
      aToken,
      {
        offset: 100 * aPage,
        limit: aLimit,
        fields:
          'total,items(track(preview_url, id, name, duration_ms, artists, album(!available_markets)))',
      },
    )
    if (response) {
      const remainingSongs =
        response.data.total - songs.length - response.data.items.length
      setSongsToFetch(Math.min(100, remainingSongs))
      setSongs((...songs, ...response.data.items))
    }
  }

Then all the functions related to rendering the list:

  useEffect(() => {
    console.log('Loading page #', page)
    setLoading(true)
    updateReduxWithValidAccessToken(authentication)
      .then((token) => getSongsOfPlaylist(token, playlistID, page))
      .then(() => {
        setLoading(false)
      })
  }, (page))

  async function loadMore() {
    if (!loading && songsToFetch > 1) {
      setPage(page + 1)
    }
  }

  function renderFooter() {
    if (!loading) {
      return null
    }
    return <ActivityIndicator animating />
  }
  function renderSeparator() {
    return <SeparatorLine />
  }

Finally, the flatlist code:

      <MySongList
        data={songs}
        renderItem={renderListItem}
        keyExtractor={(_, index) => index.toString()}
        ItemSeparatorComponent={renderSeparator}
        ListFooterComponent={renderFooter}
        onEndReached={loadMore}
        onEndReachedThreshold={0.1} />

All this code (except for the authentication wrapper) lives inside a wrapper component, PlaylistDetailScreen.

function PlaylistDetailScreen({ route, navigation, authentication, ...props }) {
  // All code above
  return loading && page === 0 ? (
    <MyText> Loading... </MyText>
  ) : (
    <ContainerView>
      <MySongList />
    <ContainerView />
  )

From my efforts, it appears that the list is rerendering multiple times. Why would this be?

javascript – Calculate SUM,AVG, for a table using Jquery

I have a list with the below report. The report shows tons by day for the last 7 days by product totaled for all products. For example, on 2/26 the product Horlicks 5173 tons 1355 so total tuns on that day is 5173+1355=6528.Similarly for the other dates.

How to get the final report like below format in Jquery calculating the sum and avg

My final out put should be like this
enter image description here

javascript – Update textField to first letter capital and rest lower case

Is there an option via JavaScript to say: if the FirstName textfield is not null then update the text so that it is 1st letter being capital and the remaining lower case?

For example somebody types in the FistName textfield: jOHN (accidently).
This is how then the data is stored in SharePoint list, and I would like so that a java script updates the written text into the correct format before it is stored wrongly in the SP list.

I am trying something like this:

    NWF$(document).ready(function () {
    NWF$("#" + txtFirstName).change(function () {
        
        // get the text value from the FirstNname textfield
        var textContent = NWF$('#' + txtFirstName).text();

        // check to see if the value is not null
        if (textContent.length > 0) {

            // format the first letter to UpperCase and the rest to LowerCase
            textContent = NWF$("#" + txtFirstName).toUpperCase() + txtFirstName.substr(1).toLowerCase();
            this.value = txtFirstName;
        }
      });
    });

javascript – SP2013 Custom List – Date & Time Column

I have created a custom list on which both date and time needs to be captured on two specific fields. To comply with existing custom formatting on the new and edit forms, I need to re-size the three date and time input boxes to be the same total width as one standard input box.

I’m not an experienced coder but have managed this on the new form (see Image 1 below). However, when I apply the same code to the edit form the date input box resizes as it should, but the two time input boxes don’t (see Image 2 below). I can’t figure out why!

I’ve also attached my code snip below. If someone more experienced could let me know if I’ve made a schoolboy error, it will be a big help. Apologies for the poor quality images by the way. Thanks.

Image 1

Image 2

<style>

.ms-dtinput .ms-input {
 width: 180px;
}

</style>

<script type="text/javascript">
    
$(document).ready(function() {
   
$(".ms-dttimeinput").find("select")(0).style.width="80px";
$(".ms-dttimeinput").find("select")(1).style.width="50px";
$(".ms-dttimeinput").find("select")(2).style.width="80px";
$(".ms-dttimeinput").find("select")(3).style.width="50px"
    
    });
    
</script>

javascript – Vanilla JS Tic Tac Toe

I would appreciate a code review – specifically of the javascript – for a tic tac toe game that I have built. I am looking for feedback on where improvements can be made in the overall structure, syntax, and style of code.

View the whole app on codepen here, with html/css included: https://codepen.io/OKiguess/pen/poNZZQa

Thanks in advance.

Javascript:

    //Module to produce the underlying game board array
const GameBoard = (() => {

    let arr = ();

    function buildArr() {
        arr = new Array(3);
        for (let i = 0; i < arr.length; i++) {
            arr(i) = new Array(3);
            for (let j = 0; j < arr(i).length; j++) {
                arr(i)(j) = `${i}${j}`;
            };
        };
        return this.arr = arr;
    };

    function resetArr() {
        this.arr = ();
        this.arr = buildArr();
        return this.arr = arr;
    };

    return {
        arr,
        buildArr,
        resetArr
    };
})();

//uses the GameBoard module to create the DOM structure for the game
const GameDOM = (() => {

    let _boardArr, _gameBoardDiv;

    const populate = () => {

        if (GameBoard.arr.length === 0) { //checks to see whether game board array already exists
            _boardArr = GameBoard.buildArr(); //makes it if it doesnt
            _gameBoardDiv = document.querySelector('.board')
            populateLoop("cell-hidden");
        }
        else { //if it does already exist
            _gameBoardDiv.innerHTML = ""; //reset the GameBoard DOM element
            _boardArr = GameBoard.resetArr(); //recreate the gameboard array
            populateLoop("cell-shown");
        }
    }

    const populateLoop = (gameState) => {
        for (let i = 0; i < _boardArr.length; i++) {
            for (let j = 0; j < _boardArr(i).length; j++) {
                let _cell = document.createElement("div");
                _cell.setAttribute('class', `${gameState}`);
                _cell.setAttribute('id', `${_boardArr(i)(j)}`);
                _gameBoardDiv.appendChild(_cell);
            }
        }
    }
    return {
        populate,
    }
})();


//Player object used for storing and retreiving player's name, piece, score, and type (for player 2 - AI)
const Player = (playerName) => {

    let score = 0;

    const getName = () => playerName;
    const getScore = () => score;

    function getPiece() {
        return this.piece;
    }

    function setPiece(piece) {
        this.piece = piece;
        return this.piece;
    }

    function setName(playerName) {
        this.name = playerName;
        return this.name;
    }

    function addPoint() {
        score++
        return score;
    }

    return {

        setName,
        setPiece,
        getName,
        getPiece,
        getScore,
        addPoint,

    };
}


//controls the state of the game, including: whose turn, total turns so far, how turns are displayed, the display of the board, checking end state (wins and draw), and the player 2 AI
const gameState = (() => {

    //game state variables
    let turn;
    let turnTally = 0
    let p1name, p2name, p1piece, p2piece, p2type
    let winner = "";

    //DOM identifierd
    const p1nameDisplay = document.querySelector(".player1-name");
    const p2nameDisplay = document.querySelector(".player2-name");
    const board = document.querySelector(".board");
    const startDiv = document.querySelector(".new-game-form-shown");
    const startButton = document.querySelector(".start");
    const scoreBoard = document.querySelectorAll(".player-hidden")


    //starts the game and takes player name values & type
    startButton.onclick = function () {
        let p1text = document.querySelector(`(name="player1-name")`).value;
        let p2text = document.querySelector(`(name="player2-name")`).value;
        p2type = document.querySelector('input(name="type2"):checked').value;
        if (p1text != "") {
            player1 = Player(p1text)
        } else if (p1text == "") {
            player1 = Player("Player 1")
        };
        if (p2text != "") {
            player2 = Player(p2text)
        } else if (p2text == "") {
            player2 = Player("Player 2")
        };
        p1name = player1.getName();
        p2name = player2.getName();
        player1.num = "player1";
        player2.num = "player2";
        p1nameDisplay.innerHTML = `<h2>${player1.getName()}</h2>`
        p2nameDisplay.innerHTML = `<h2>${player2.getName()}</h2>`
        hideStartScreen();
        showScoreBoard();
        randomPiece();
        setTimeout(whoStarts, 500);
        activeTurn();
        return;
    }

    //displays scoreboard
    function showScoreBoard() {
        for (let i = 0; i < scoreBoard.length; i++) {
            scoreBoard(i).classList.add("player-shown")
            scoreBoard(i).classList.remove("player-hidden")
        }
    }

    //reveals game grid
    function showBoard() {
        let grid = board.querySelectorAll(".cell-hidden");
        for (i = 0; i < grid.length; i++) {
            grid(i).classList.add("cell-shown");
            grid(i).classList.remove("cell-hidden");
        }
    }

    //hides the initial start screen
    function hideStartScreen() {
        startDiv.classList.add("new-game-form-hidden")
        startDiv.classList.remove("new-game-form-shown")
        const startDivHidden = document.querySelector(".new-game-form-hidden");
        removeStart(startDivHidden);
    }

    //conrols animation transitions and removin start DIV from DOM
    const promiseTransition = (div, property, value) =>
        new Promise(resolve => {
            div.style(property) = value;
            const transitionEnded = e => {
                if (e.propertyName !== property) return;
                div.removeEventListener('transitionend', transitionEnded);
                resolve();
            }
            div.addEventListener('transitionend', transitionEnded);
        });


    async function removeStart(startDivHidden) {
        await promiseTransition(startDivHidden, "opacity", "0");
        startDivHidden.remove();
        GameDOM.populate();
        setTimeout(showBoard, 1);
    }

    //controls display of each players piece
    const displayPlayerPiece = (p1, p2) => {
        const p1pieceDiv = document.querySelector(".player1-piece")
        const p2pieceDiv = document.querySelector(".player2-piece")
        p1pieceDiv.innerHTML = `<button class="${p1}" role="radio" type="button">${p1}</button>`
        p2pieceDiv.innerHTML = `<button class="${p2}" role="radio" type="button">${p2}</button>`
    }


    //randomises players pieces
    const randomPiece = () => {
        let coinFlip = Math.round(Math.random());
        if (coinFlip === 0) {
            p1piece = player1.setPiece("X");
            p2piece = player2.setPiece("O");
            displayPlayerPiece(p1piece, p2piece);
            return;
        } else {
            p1piece = player1.setPiece("O");
            p2piece = player2.setPiece("X");
            displayPlayerPiece(p1piece, p2piece);
            return;
        }
    }

    //randomise who starts each round
    const whoStarts = () => {
        let coinFlip = Math.round(Math.random());
        if (coinFlip === 0) {
            turn = p1name;
            activeTurn();
            return turn;
        } else if (p2type == "AI") {
            turn = p2name
            activeTurn();
            AImove();
        } else return turn = p2name;
    };

    //function for switching turns between players
    const nextTurn = () => {
        if (turn == p1name) {
            turn = p2name
            if (p2type == "AI") AImove();
        }
        else if (turn == p2name) {
            turn = p1name
        }
        activeTurn();
        return turn;
    }

    //click listener for placing pieces
    board.onclick = function (e) {
        if ((winner == "") && ((e.target.className == "cell-shown cell-hover-X") || (e.target.className == "cell-shown cell-hover-O"))) {
            if (!e.target.innerHTML) {
                if (turn == p1name) {
                    placePiece(e, p1piece);
                }
                else placePiece(e, p2piece)
            }
        }
        else return;
    }

    //place piece functionality
    function placePiece(e, piece) {
        gameArrayIndex = e.target.attributes.id.value;
        splitIndexValue = gameArrayIndex.split("");
        splitValueX = gameArrayIndex(0);
        splitValueY = gameArrayIndex(1);
        GameBoard.arr(splitValueX)(splitValueY) = piece;
        e.target.innerHTML = piece;
        turnTally++
        if (turnTally > 4) {
            if (winCondition()) {
                whoStarts();
                return;
            };
        };
        nextTurn();
    }

    //highlights whose turn is active
    const activeTurn = () => {
        const p1board = document.querySelector(".player1-info")
        const p2board = document.querySelector(".player2-info")
        if (turn == p1name) {
            p1board.classList.remove("inactive")
            p2board.classList.add("inactive")
        } else {
            p2board.classList.remove("inactive")
            p1board.classList.add("inactive")
        }
    }

    //randomise AI starting move to best squares
    function AIstartingMove() {
        startingMove = ("00", "02", "11", "20", "22")
        let randomStartIndex = Math.floor(Math.random() * startingMove.length);
        return startingMove(randomStartIndex)
    }


    //overall AI move control function
    const AImove = () => {

        if (turnTally > 8) return;

        if (turnTally == 0) {
            let startingMove = AIstartingMove()
            AIplaceDOM(startingMove)
        }
        if (turnTally > 0) {
            let bestMove = minimax(GameBoard.arr, p2piece);
            AIplaceDOM(bestMove.index)
        }
        turnTally++

        if (turnTally > 4) {
            if (winCondition()) {
                whoStarts();
                return;
            };
        };

        nextTurn();
    }


    //responsible for showin the move in the DOM
    function AIplaceDOM(move) {
        AImoveCoOrds = move.toString().split("");
        let xMove = AImoveCoOrds(0)
        let yMove = AImoveCoOrds(1)
        GameBoard.arr(xMove)(yMove) = p2piece
        let placeDOM = document.getElementById(`${xMove}${yMove}`)
        placeDOM.innerHTML = p2piece
        return;
    }

    //announces winner in centre square
    function announceWinner(player) {
        let announceCell = document.getElementById("11")
        announceCell.innerHTML = `${player} wins!`
        winner = player
        announceCell.onclick = function () {
            winner = "";
            GameDOM.populate();
            turnTally = 0;
            whoStarts()
        }

    }

    //announces draw in centre square
    function announceDraw() {
        let announceCell = document.getElementById("11")
        announceCell.innerHTML = `Tie! Nobody wins.`
        winner = "none"
        announceCell.onclick = function () {
            winner = "";
            GameDOM.populate();
            turnTally = 0;
            whoStarts();
        }

    }

    //Point control function
    function winnerFound(player) {
        player.addPoint()
        updateScore(player.num, player.getScore());
        announceWinner(turn);
    }

    //updates scoreboard display
    const updateScore = (player, score) => {
        const scoreDiv = document.querySelector(`.${player}-score`)
        scoreDiv.innerText = score;
        return;
    }

    //Game end state control function
    function winCondition() {
        if (checkWinner(GameBoard.arr, p1piece)) {
            winnerFound(player1)
            return;
        }
        else if (checkWinner(GameBoard.arr, p2piece)) {
            winnerFound(player2)
            return;
        };
        if (turnTally > 8) { //evaluates draw
            announceDraw();
            return;
        }
    };

    //evaluates whether win has occurred, also used by AI for working out their best move.
    function checkWinner(board, player, theory) {

        const diagDownEqual = (board, player) => {
            if ((board(0)(0) === player) && (board(0)(0) === board(1)(1)) && (board(0)(0) === board(2)(2))) {
                if (theory !== "yes") { //if theory = "yes", AI is calculating best move and therefore winning highlight should not be applied.
                    for (let i = 0; i < 3; i++) {
                        let cell = document.getElementById(`${i}${i}`)
                        cell.classList.add(`cell-win-${player}`)
                    }
                    return true;
                }
                return true;
            }
        }

        const diagUpEqual = (board, player) => {
            if ((board(0)(2) === player) && (board(0)(2) === board(1)(1)) && (board(0)(2) === board(2)(0))) {
                if (theory !== "yes") { //if theory = "yes", AI is calculating best move and therefore winning highlight should not be applied.
                    let cells = ();
                    cells.push(document.getElementById(`02`))
                    cells.push(document.getElementById(`11`))
                    cells.push(document.getElementById(`20`))
                    for (let i = 0; i < 3; i++) {
                        cells(i).classList.add(`cell-win-${player}`)
                    }
                    return true;
                }
                return true;
            }
        }

        const rowEqual = function (board, player) {
            const xCheck = (board, player) => board.every(val => val === player);
            for (i = 0; i < board.length; i++) {
                if (xCheck(board(i), player)) {
                    if (theory !== "yes") { //if theory = "yes", AI is calculating best move and therefore winning highlight should not be applied.
                        for (j = 0; j < board(i).length; j++) {
                            let cell = document.getElementById(`${i}${j}`)
                            cell.classList.add(`cell-win-${player}`)
                        }
                        return true;
                    }
                    return true;
                }
            }
            return false;
        }

        const columnEqual = function (board, player) {
            for (let i = 0; i < board(0).length; i++) {
                if ((board(0)(i) === player) && (board(0)(i) === board(1)(i)) && (board(0)(i) === board(2)(i))) {
                    if (theory !== "yes") { //if theory = "yes", AI is calculating best move and therefore winning highlight should not be applied.
                        for (let j = 0; j < board(0).length; j++) {
                            let cell = document.getElementById(`${j}${i}`)
                            cell.classList.add(`cell-win-${player}`)
                        }
                        return true;
                    }
                    return true;
                }
            }
            return false;
        }

        if ((diagUpEqual(board, player)) || (diagDownEqual(board, player)) || (rowEqual(board, player)) || (columnEqual(board, player))) {
            return true
        }
        else return false;
    }

    //creates 2D array of available spaces to play
    function emptySpace(arr) {
        const freeSpaceArray = ();
        for (i = 0; i < arr.length; i++) {
            for (j = 0; j < arr(i).length; j++) {
                if ((arr(i)(j) != "X") && (arr(i)(j) != "O")) {
                    freeSpaceArray.push(arr(i)(j));
                }
            }
        }
        return freeSpaceArray;
    }

    //minimax AI function
    function minimax(newBoard, player, depth = 0) {

        let availSpots = emptySpace(GameBoard.arr);

        if (checkWinner(newBoard, p1piece, "yes")) {
            return { score: depth - 100 };
        } else if (checkWinner(newBoard, p2piece, "yes")) {
            return { score: 100 - depth };
        } else if (availSpots.length == 0) {
            return { score: 0 };
        }
        let moves = ();
        for (let i = 0; i < availSpots.length; i++) {
            let move = {};
            splitCoOrds = availSpots(i).toString().split("");
            let xCoOrd = splitCoOrds(0)
            let yCoOrd = splitCoOrds(1)
            move.index = newBoard(xCoOrd)(yCoOrd)
            newBoard(xCoOrd)(yCoOrd) = player

            //recursive function call
            if (player == p2piece) {
                result = minimax(newBoard, p1piece, depth + 1);
                move.score = result.score;
            } else {
                result = minimax(newBoard, p2piece, depth + 1);
                move.score = result.score;
            };

            //test to reset the board position to empty depending on coordinates            
            let splitCoOrds2 = availSpots(i).toString().split("");
            let xCoOrd2 = splitCoOrds2(0);
            let yCoOrd2 = splitCoOrds2(1);
            newBoard(xCoOrd2)(yCoOrd2) = move.index
            moves.push(move);
        }

        let bestMove;

        if (player === p2piece) {
            let bestScore = -10000;
            for (let i = 0; i < moves.length; i++) {
                if (moves(i).score > bestScore) {
                    bestScore = moves(i).score;
                    bestMove = i;
                }
            }
        } else {
            let bestScore = 10000;
            for (let i = 0; i < moves.length; i++) {
                if (moves(i).score < bestScore) {
                    bestScore = moves(i).score;
                    bestMove = i;
                }
            }
        }
        return moves(bestMove);
    }

    //highlight cell function
    board.onmouseover = function (e) {
        if (e.target.className == "cell-shown") {
            if (turn == p1name) {
                if (player1.getPiece() == "X") {
                    e.target.classList.add('cell-hover-X')
                } else e.target.classList.add('cell-hover-O')
            }
            else if ((turn == p2name) && (p2type == "human")) {
                if (player2.getPiece() == "X") {
                    e.target.classList.add('cell-hover-X')
                } else e.target.classList.add('cell-hover-O')
            }
        }
        else return;
    }
    
    //unhighlight cell function
    board.onmouseout = function (e) {
        e.target.classList.remove('cell-hover-X');
        e.target.classList.remove('cell-hover-O')
        return;
    };

})();

html – Criar Loop em Json Nestes com JavaScript

var myObj = {
  "rgInventory": {
    "teste": {
      "id": "2912579",
      "classid": "778383679",
      "instanceid": "0",
      "amount": "1",
      "pos": 73
    },
    "20978381654": {
      "id": "20978381654",
      "classid": "310778443",
      "instanceid": "302028390",
      "amount": "1",
      "hide_in_china": 0,
      "pos": 1
    },
    "20978149654": {
      "id": "20978149654",
      "classid": "1989272282",
      "instanceid": "302028390",
      "amount": "1",
      "pos": 2
    },
    "20967745237": {
      "id": "20967745237",
      "classid": "3761545285",
      "instanceid": "0",
      "amount": "1",
      "pos": 3
    }
  }

};


document.getElementById("demo").innerHTML += myObj.rgInventory("teste")("id");

var ids = myObj("rgInventory");

for (var i = 0; i < ids.length; i++) {
  document.getElementById("teste").innerHTML += ids(i).name("id")
}
<!DOCTYPE html>
<html>

<body>

  <p>Testando Java.</p>

  <p id="demo"></p>
  <p id="teste"></p>


</body>

</html>

javascript – Not Getting the mat-select value with angular virtual scroll

I have shared my code below, please help me out.
app.component.html****************

<mat-select multiple (openedChange)=”openChange($event)” formControlName=”itemSelect”>

{{ itemTrigger }}

<mat-option *cdkVirtualFor=”let list of skillSet” (value)=”list.data” (onSelectionChange)=”onSelectionChange($event)”>
{{list.data}}

<mat-error *ngIf=”!addCompany.controls(‘itemSelect’).valid && addCompany.controls(‘itemSelect’).touched”>
{{ titleAlert }}

app.component.ts***********
itemSelect = new FormControl();
constructor(
public _cdr: ChangeDetectorRef,
private formBuilder: FormBuilder
) {
this.itemSelect.valueChanges.forEach(v => {
console.log(“value changes”, v);
this.selectedItem = v;
this.itemTrigger = v;
console.log(“triggering value: “, this.itemTrigger);
});
}

ngOnInit(): void {
this._bc.setBreadcrumb(BC_COMPANY_ADD);
this.createForm();
}
selectedItem: any;
_itemTrigger: any;
get itemTrigger(): string {
return this._itemTrigger;
}
set itemTrigger(v: string) {
this._itemTrigger = v;
}
openChange($event: boolean) {
console.log(“open change”, $event);
if ($event) {
this.cdkVirtualScrollViewPort.scrollToIndex(0);
this.cdkVirtualScrollViewPort.checkViewportSize();
} else {
}
}
onSelectionChange(change: MatOptionSelectionChange) {
if (change.isUserInput) {
console.log(“onSelectionChange”, change.source.value);
this.selectedItem = change.source.value;
console.log(“triggered item “, this.selectedItem);

}

}

Trapping focus inside container using pure JavaScript

var trapElems = ();
var trapActive = false; // Set to true after the initial tabbing
var trapIndex; // Current index

// Function for handling tabbing forward
function trapTab() {
    if (trapElems.length === 0) {
        return;
    }
    if (!trapActive) {
        trapActive = true;
        trapIndex = 0;
        trapElems(trapIndex).focus();
        return;
    }
    trapIndex = trapIndex + 1;
    if (trapIndex === trapElems.length) {
        trapIndex = 0;
    }
    trapElems(trapIndex).focus();
}

// Function for handling tabbing backward
function trapShiftTab() {
    if (trapElems.length === 0) {
        return;
    }
    if (!trapActive) {
        trapActive = true;
        trapIndex = trapElems.length - 1;
        trapElems(trapIndex).focus();
        return;
    }
    trapIndex = trapIndex - 1;
    if (trapIndex < 0) {
        trapIndex = trapElems.length - 1;
    }
    trapElems(trapIndex).focus();
}

document.addEventListener("DOMContentLoaded", function() {
    // Get the focus trap elements inside the box
    trapElems = document.getElementById("box").querySelectorAll('button, (href), input, select, textarea, (tabindex):not((tabindex="-1"))');
    console.log(trapElems);

    // Handle the (tab) and (shift) key down events
    document.addEventListener(
        "keydown",
        function(e) {
            // (shift) + (tab)
            if (event.shiftKey && e.which === 9) {
                e.preventDefault();
                trapShiftTab();
            }
            // (tab) only
            else if (e.which === 9) {
                e.preventDefault();
                trapTab();
            }
        },
        false
    );
}, false);
* {
    box-sizing: border-box;
}
body {
    margin: 20px;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
}
#box {
    border: 1px solid blue;
    padding: 20px 10px;
    margin: 20px 0;
}
a {
    padding: 5px;
    border: 1px dotted gray;
}
<div>
    <a href="#">Link 1</a>
    <a href="#">Link 2</a>
    <a href="#">Link 3</a>

    <div id="box">
        <a href="#" id="box-link-1">Box link 1</a>
        <a href="#" id="box-link-2">Box link 2</a>
        <a href="#" id="box-link-3">Box link 3</a>
        <a href="#" id="box-link-4">Box link 4</a>
    </div>

    <a href="#">Link 4</a>
    <a href="#">Link 5</a>
    <a href="#">Link 6</a>
</div>

html – Cargar nombres en una tabla con Javascript

const agregarJugadores = document.getElementById('agregar-jugador');
const agregarNombres = document.getElementById('agregar-nombre');
const agregarEnTabla = document.getElementById('tabla-jugadores');
let tabla = (

);

nuevoJugador = "";
agregarJugadores.addEventListener('click', ()=> {
    var nuevoNombre = `${agregarNombres.value}`
        var tablaLlena ="";
        for (i=0; i<tabla.length; i++) {
            tablaLlena = `${nuevoNombre}`;
        }
        agregarEnTabla.innerHTML = tablaLlena;
});
.botones {
    margin: auto;
    width: 20%;
    padding: 20px;
}

.table-stirped {
    
    text-align: center;
    width: 50%;
    height: 200px;
}
<!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>
     <!-- Bootstrap CSS -->
     <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">

     <link href="style.css" rel="stylesheet">
</head>
<body>
    
        <h1>AGREGAR JUGADORES</h1>
    
        <div class="container">
    
              <div class="actions-menu">
                  
              
             <!-- Button trigger modal -->
    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
        Agregar Jugadores
      </button>
      </div>
      <!-- Modal -->
      <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="exampleModalLabel">Nuevos Jugadores</h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <input class="form-control" type="text" placeholder="Agregar nombre" id="agregar-nombre">
                <table class="table table-stirped table-hover">
                    <thead>
                      <tr>
                        <th scope="col">Jugadores</th>
                        <th scope="col"></th>
                      </tr>
                    </thead>
                    <tbody id="tabla-jugadores">
                    
                    </tbody>
                  </table>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" id="agregar-jugador">Añadir</button>
              
            </div>
          </div>
        </div>
      </div>
     
    </div>
        
    
        <!-- Optional JavaScript; choose one of the two! -->
    
        <!-- Option 1: Bootstrap Bundle with Popper -->
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script>
    
        <!--Mis Scripts-->
    <script src="app.js"></script>
    
        <!-- Option 2: Separate Popper and Bootstrap JS -->
        <!--
        <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.6.0/dist/umd/popper.min.js" integrity="sha384-KsvD1yqQ1/1+IA7gi3P0tyJcT3vR+NdBTt13hSJ2lnve8agRGXTTyNaBYmCR/Nwi" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.min.js" integrity="sha384-nsg8ua9HAw1y0W1btsyWgBklPnCUAFLuTMS2G72MMONqmOymq585AcH49TLBQObG" crossorigin="anonymous"></script>
        -->
</body>
</html>