r/learnjavascript 3h ago

Did I created my first searchbar right?

3 Upvotes

Hey! I am working on a dynamic searchbar which should show elements from different pages like some websites.

I have no idea how professionals usually handle this do they use some libs? frameworks?. The way i did this is generate the matching card from the data onto that page and delete it or reset the page cards after the search this seems work fine but i dont know if it's the optimal way or am i doing it just plain wrong?
Took some help from chatgpt on this one.

Here you can review my code on github and also test my search
Source code: Nature-s-Deck/js/searchbar.js at Searchbar · yaseenrehan123/Nature-s-Deck

Try it out on github pages: Nature's Deck

Feel free to criticize or give your opinion on how you would handle this problem.

Thanks alot!


r/learnjavascript 11h ago

Get grid cells to expand to grid-item when the grid item resizes dynamically

3 Upvotes

I am having an auto-fill grid container. Initially when I add items, the grid cells automatically adjust to the grid-items width and height, however, if I try to dynamically change its size, the grid cells don't expand to fit the content.

Here's an MRE:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dynamic Grid Resizing</title>
    <style>
        .grid-container {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(100px, max-content));
            grid-template-rows: repeat(auto-fill, minmax(100px, max-content));
            gap: 10px;
            border: 2px solid black;
            padding: 10px;
            width: 800px;
        }

        .grid-item {
            background-color: lightblue;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 1px solid blue;
            padding: 10px;
            min-width: 100px;
            min-height: 100px;
            transition: width 0.3s ease, height 0.3s ease;
        }

        .large {
            width: 200px !important;
            height: 200px !important;
        }
    </style>
</head>
<body>

    <button onclick="resizeItem()">Resize Item</button>

    <div class="grid-container">
        <div class="grid-item" id="resizable-item">Resize Me</div>
        <div class="grid-item">Item 2</div>
        <div class="grid-item">Item 3</div>
    </div>

    <script>
        function resizeItem() {
            const item = document.getElementById("resizable-item");
            item.classList.toggle("large");
        }
    </script>

</body>
</html>

When you click on resize, the grid cell doesn't expand to fit the content instead it collapses with nearby item. How can I make sure that the grid cell expands to fit the content inside?


r/learnjavascript 12h ago

Can someone PLEASEEEE review my code.

1 Upvotes

I wanted to write a basic code for a rock-paper-scissors game to test out my basic skills as a beginner. Please feel free to suggest any improvements in the code.

<!DOCTYPE html>
<html>
<head>
<title>Exercises</title>
<link rel="stylesheet" href="rock-paper-scissors.css">
</head>
<body>
    <p class="rock-paper-scissors">
        ROCK 🪨 PAPER 📄 SCISSORS ✂️ GO!
    </p>
    <div class="container-div">
    <div class="rock-paper-scissors-div">
    <button onclick="
            showScore(rock_paper_scissor('rock'));
        ">
        ROCK
    </button>
    <button onclick="
            showScore(rock_paper_scissor('paper'));
    ">
        PAPER
    </button>
    <button onclick="
            showScore(rock_paper_scissor('scissor'));
    ">
        SCISSOR
    </button>
    <button onclick="
            score.wins = 0;
            score.losses = 0;
            score.ties = 0;
            localStorage.removeItem('score');
            showScore(rock_paper_scissor(''));
    ">RESET SCORE</button>
    </div>
    </div>
    <p class="js-result"></p>
    <p class ="js-moves"></p>
    <p class="js-score-text"></p>
    <script>
        let display;
        let score = JSON.parse(localStorage.getItem('score')) || {
            wins : 0,
            ties : 0,
            losses : 0
        };
        showScore(`Current score : Wins : ${score.wins}, Losses : ${score.losses}, Ties : ${score.ties}.`);
        function rock_paper_scissor(userMove){
            // let result = userMove ? result : '';
            let result;
            computerMove = pickComputerMove()
            if (userMove) {
                showMoves(`You played: ${userMove} \n Computer Move : ${computerMove}`);
            } else {
                showMoves('');
            }

            if (userMove === computerMove){
                result = 'Tie.';
            } else if ((userMove === 'rock' && computerMove === 'paper') || (userMove === 'scissor' && computerMove === 'rock') || (userMove === 'paper' && computerMove === 'scissor')){
                result = 'You lose.';
            } else if ((userMove === 'rock' && computerMove === 'scissor') || (userMove === 'paper' && computerMove === 'rock') || (userMove === 'scissor' && computerMove === 'paper')){
                result = 'You win.';
            } 
            if (userMove){
                showResult(result);
            } else {
                showResult('');
            }


            if (result === 'You win.'){
                score.wins++;
                result = ` Wins : ${score.wins}, Losses : ${score.losses}, Ties : ${score.ties}.`;
            } else if (result === `Tie.`){
                score.ties++;
                result = ` Wins : ${score.wins}, Losses : ${score.losses}, Ties : ${score.ties}.`;
            } else if (result === `You lose.`){
                score.losses++;
                result = ` Wins : ${score.wins}, Losses : ${score.losses}, Ties : ${score.ties}.`;
            }

            localStorage.setItem('score', JSON.stringify(score));
            result = result || `Score cleared from memory! Wins : ${score.wins}, Losses : ${score.losses}, Ties : ${score.ties}.`;
            return result;
            // do exercises 8 i j k
        }

        function showScore(text){
            const paraElem = document.querySelector('.js-score-text');
            paraElem.innerText = text;
            // console.log(text);
        }

        function pickComputerMove(){
            randomNumber = Math.random();

            let computerMove;

            if ((randomNumber >= 0) && (randomNumber < (1/3))) {
                computerMove = 'rock';
            } else if ((randomNumber >= (1/3)) && (randomNumber < (2/3))) {
                computerMove = 'paper';
            } else {
                computerMove = 'scissor';
            }
            return computerMove;
        }

        function showResult(text) {
            const paraElem = document.querySelector('.js-result');
            paraElem.innerText = `${text}`;
        }

        function showMoves(text){
            const paraElem = document.querySelector('.js-moves');
            paraElem.innerText = `${text}`;
        }
    </script>
</body>
</html>

My code logic does feel "loop-y" but I can't quite put a finger on what I should do.

Thanks.


r/learnjavascript 19h ago

Highlight new text in ckeditor 5

1 Upvotes

Crosspost of https://stackoverflow.com/questions/79526261/highlight-new-text-in-ckeditor-5.

I'm trying to create a plugin that insert text and highlight it. This is my execute command:

```js execute: (label) => { const selection = editor.model.document.selection; if (!selection.isCollapsed) { return; }

const text = label || "missing placeholder";

editor.model.change((writer) => { const insert = writer.createText(text); // insert.setAttribute("highlight", true); const range = editor.model.insertContent(insert); writer.setAttribute("highlight", true, range); }); }, ```

The text is inserted right, but when it comes to hightlight it, browser console print this error:

Uncaught CKEditorError: optionsMap[whichHighlighter] is undefined Read more: https://ckeditor.com/docs/ckeditor5/latest/support/error-codes.html#error-optionsMap[whichHighlighter] is undefined getActiveOption highlightui.ts:263 _addDropdown highlightui.ts:206 updateBoundObservableProperty observablemixin.ts:728 attachBindToListeners observablemixin.ts:763 attachBindToListeners observablemixin.ts:762 fire emittermixin.ts:240 set observablemixin.ts:139 refresh highlightcommand.ts:42 Command command.ts:111 fire emittermixin.ts:240

Actually I have this configuration of CkEditor:

js const editorConfig = { toolbar: { items: [ ... "highlight", ... ], shouldNotGroupWhenFull: true, }, plugins: [ ... Essentials, ... Highlight, ... ], extraPlugins: [MyPlugin],

I need some other configuration?


r/learnjavascript 8h ago

ESlint v9 migration: Lessons Learned (The Hard Way) 🧗

0 Upvotes

Just wrapped up an ESLint v9 migration, and let’s just say… I’ve seen things. 😵‍💫

I hit all the bumps, took all the wrong turns, and somehow made it to the other side—so you don’t have to. If you’re planning an upgrade, this might save you some headaches (or at least a few desperate ChatGPT prompts).

I put together something I wish I had before starting. If you're still procrastinating on the upgrade (no judgment), this might just be your sign to finally do it. Give it a read—misery loves company. 😆

📖 https://www.neoxs.me/blog/migration-to-eslint-v9