/r/learnjavascript

Photograph via snooOG

This subreddit is for anyone who wants to learn JavaScript or help others do so.

Questions and posts about frontend development in general are welcome, as are all posts pertaining to JavaScript on the backend.

This subreddit is a place for people to learn JavaScript together. Everyone should feel comfortable asking any and all JavaScript questions they have here.

With a nod to practicality, questions and posts about HTML, CSS, and web developer tools are also encouraged.


Posting and Commenting Guidelines

  1. Be Welcoming. n00bs are welcome here. Negativity is not.
  2. Include Context. If you’re asking for help, include enough information for others to recreate your problem.
  3. No Self-Promotion. The following are not allowed: Requests for subscribers, asking for "test users" for your new JS course, offering paid mentorships, and/or premium courses. Even if there is a coupon discount, no. If you're in doubt, message the mods first.

  4. Good Titles - Write a descriptive title. Titles that begin with "hey guys" will be removed.


Related Subreddits


If you want to post something self-promotional, please message the mods first. Personal blog posts that are relevant to the subreddit's stated subject matter don't need prior approval (and are encouraged!).

/r/learnjavascript

265,043 Subscribers

1

How to add sound effects ?

Hey ! I coded an animation with some circles bouncing of each other in a square, and I'd like to add a sound effect on each bounce, like a bell sound or something. I tried to implement it with correct path, loading and naming of the mp3 files, but it doesn't work... any help ? 🙏🏻

0 Comments
2024/11/12
06:25 UTC

4

Understanding JavaScript Scope : A Comprehensive Guide

Hey, I’m writing a Medium blog about JavaScript scope. Feel free to share your thoughts in the comments!.

Understanding JavaScript Scope and Closures: A Comprehensive Guide

0 Comments
2024/11/12
05:40 UTC

0

Help needed

Hi, Help needed in implementing a download excel functionality to a specific location on the user machine rather than the downloads folder.Upin clicking save button user should be allowed to select a location to download the excel file and upon clicking OK file should be downloaded there.Is or possible to accomplish this in java script and html..springboot backend upon clicking save button is returning blob which is excel data..please suggest how to modify this to allow user to select download location and download the excel to that location

0 Comments
2024/11/12
04:11 UTC

0

Help needed

Hi, Looking for a download excel functionality which should allow user to select a location for the file download.Is or possible to achieve this using java script and html.speingboot backend is returning the Excel data as blob.Upon clicking save button in UI which is html;it should give user option to select a location for file download and then excel should be downloaded to that location.Please suggest

0 Comments
2024/11/12
04:09 UTC

3

A date-time question: how to interpret a time as being in a specific timezone?

Referring to a recent post of mine; I now have difficulty managing datetimes. I have a conference program, all dates and times of which are in the local time (in this case a city in Indonesia). I want to copy these times into my file, but allow other people to change them into their own, local timezones.

So for example, a datetime of November 23, 2024, 14:00 is to be interpreted as the timezone specific to its Indonesian city. What is the best way of doing this? I have been experimenting with luxon but I'm not sure, for my simple needs, whether I need it over and above JavaScript's native date handling.

I suppose I could change all the times into UTC times - subtracting the appropriate hours - which means that the times just need to be changed according to the user's timezone. But my question remains: how do I interpret a given time as being in a specific timezone?

Thanks very much.

2 Comments
2024/11/12
03:34 UTC

1

Is there an event to detect a user on a mobile device changing apps to or from their browser?

I am working on a browser application that uses websocket connections to provide simultaneous multi-user collaboration. An interesting pitfall I've discovered is when one of the users changes from their browser to a different application on their mobile device, then returns to the browser with my app still running. My websocket connection can detect the user navigating away from my site or closing the browser, but it seems to be blind to the user changing to another application. Thus, I can't update my application state or inform other users that a user has left in this situation.

I have somewhat solved the problem with timeouts based on continued user input. However, if I could detect a user either leaving or returning to my app, I could provide a better experience.

2 Comments
2024/11/12
02:34 UTC

1

RPG Maker MV followup attack

Hello! I have a character in my game that inflicts a state onto enemies, and i want this to happen: when an actor hits an enemy with that state he launches a followup attack onto the enemy. I tried using scripts to achieve this but my js knowledge is very limited, if someone could help me id appreciate it so much!! if you need more context or if my question doesnt make sense lmk

3 Comments
2024/11/11
23:03 UTC

1

I have a lua-js encryptor-decrypter system for discord, just checking if this code is correct, this is run on render btw

const express = require('express');

const crypto = require('crypto');

const axios = require('axios');

const app = express();

app.use(express.json());

const encryptionKey = process.env.ENCRYPTION_KEY;

function decrypt(encryptedData) {

const decipher = crypto.createDecipheriv('aes-256-cbc', encryptionKey, Buffer.alloc(16, 0));

let decrypted = decipher.update(encryptedData, 'base64', 'utf8');

decrypted += decipher.final('utf8');

return JSON.parse(decrypted);

}

app.post('/', async (req, res) => {

try {

console.log("Request body:", req.body);

const encryptedPayload = req.body.data;

if (!encryptedPayload) {

throw new Error("Missing encrypted data in the request body");

}

const decryptedMessage = decrypt(encryptedPayload);

const { identifier, content, embeds } = decryptedMessage;

let discordWebhookUrl = "";

if (identifier === "join") {

discordWebhookUrl = process.env.JOIN_WEBHOOK_URL;

} else if (identifier === "logs") {

discordWebhookUrl = process.env.LOGS_WEBHOOK_URL;

}

await axios.post(discordWebhookUrl, {

content: content || null,

embeds: embeds || []

});

res.status(200).send("Notification sent successfully");

} catch (error) {

console.error("Error processing request:", error.message);

res.status(500).send("Failed to process notification");

}

});

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {

console.log(\Server listening on port ${PORT}`);`

});

0 Comments
2024/11/11
22:00 UTC

2

I don't Know if i am learning correctly or not

I am currently learning Js through superSimpleDiv channel on Youtube and someTimes i feel like i am not learning a lot because i can't solve the exercise without looking at the finished solution and only after looking at solution i understand the way to solve the exercise and i don't know if what i am doing is right or wrong

3 Comments
2024/11/11
19:07 UTC

1

are these still there?

Are there guys who still do everything with vanilla JavaScript instead of frameworks? is that possible? even though you are an expert? Also as a Freelancer?

12 Comments
2024/11/11
19:00 UTC

2

How to fill a screen with 2D circles that surrounds HTML content?

Hi everyone - I received a Figma design that has me a bit stumped on how to implement and would really appreciate some guidance to lead me in the right direction (not expecting a full solution)

Desktop Design: https://postimg.cc/QHy2dQLr

Mobile Design: https://postimg.cc/yJXNS1zB

As you can see, I would need be able to render some page/form content and then fill the remaining space with 2D circles. I don't think I can just use a CSS pattern since we need to be aware of the content on the page and not render a circle in the background.

Even if we simply set a solid background color for the content on top, this would result in some of the circles being cut off and instead we simply want to just not render a circle when there is a potential for content intersection.

My current thought is that I would need to do the following:

  1. Retrieve the `boundingClientRect` for each element on the page (i.e. the form elements, the logo, the header etc)
  2. Detect screen size and calculate how many circles can fit per row/column
  3. Render 2D circles and skip circles where a coordinate intersects with some HTML content
  4. As this needs to be responsive, add a throttled resize handler to detect when the screen size changes in order to redraw

Is this the right starting point?

Would it be best to draw these circles on an HTML `canvas` instead of writing each circle as a `div` on the HTML DOM?

I've also been looking in to collision detection, but just don't feel like I've been able to find any good examples to learn from so I would be really curious to learn how to best handle this kind of scenario?

Thanks a lot!

EDIT: something else to consider is how would we handle scrolling to ensure that the circles would not intersect with the content upon scroll? In my mind having them "move out of the way" would be ideal but sounds tough to implement

26 Comments
2024/11/11
18:58 UTC

1

Need help with separate chaining hash table using linked list: only last element set to the table appears

I want to create a separate chaining hash table in which, in case of collisions, the index of the table is a linked list. I wrote below a test code for just one array index. I'm not sure why only the last element added to the table appears in the linked list? How to make this work? Thank you!

class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}

class LinkedList {
  constructor() {
    this.head = null;
    this.size = 0;
  }

  prepend(value) {
    const node = new Node(value);
    if (this.head === null) {
      this.head = node;
    } else {
      node.next = this.head;
      this.head = node;
    }
    this.size++;
  }
}

class HashMap {
  constructor() {
    this.storageCapacity = 16;
    this.storage = new Array(this.storageSizeCapacity).fill(null);
  }

  setKeyValue(value) {
    this.storage[1] = new LinkedList();
    this.storage[1].prepend(value);
  }
}

const test = new HashMap();
test.setKeyValue("dog");
test.setKeyValue("cat");
test.setKeyValue("parrot");
test.setKeyValue("hamster");
test.setKeyValue("snake");
test.setKeyValue("turtle");

console.log(test.storage);
2 Comments
2024/11/11
18:57 UTC

2

Why am I getting this error....(Uncaught TypeError: playBtn is null <anonymous> http://127.0.0.1:5500/script2.js:9) for a button that i have created

(HTML)
<!-- This is the link from my start page to the actual tic tac toe game board -->
    <a href="/game.html" target="_blank" rel="noopener noreferrer" id="playBtn" type="submit">Play Game</a>

    <script src="script2.js"></script>
</body>
</html>


(Js)
const playBtn = document.getElementById('playBtn');
const player1Name = document.querySelector('player1Name');             
const player2Name = document.querySelector('player2Name');             
const displayName1 = document.getElementById('displayName1');            
const displayName2 = document.getElementById('displayName2');            



playBtn.addEventListener("click", () => {
  console.log("hello");

});


let board = ['', '', '', '', '', '', '', '', ''];
let currentPlayer = 'X';
let gameActive = true;
8 Comments
2024/11/11
16:39 UTC

2

function should run every time button is clicked

I have a form that, when submitted, the form should disappear and another button should show up. That button (multiStartBtn) disappears when click and a (1) a math problem shows up and (2) a form field and button should appear (button = multiAnsSubmitBtn)

Then, the user will put in a value in to the form field and submit. When they submit, a new math problem shows up in the question block.

This happens as expected the first time around. But after a new question shows up in the questionBlock, none of it works anymore.

I feel like I am making this more complicated than it needs to be, but I can't find the issue.

ChatGPT keeps telling me to add a flag, so I have done that, but somehow I feel like this isn't fully working properly either.

Does anybody have any ideas of what is going on and can send me in the right direction?

Thank you!

multiForm.addEventListener("submit", function (event) {
    event.preventDefault();
    // Get the min and max values from the form inputs
    multiMin = Number(document.getElementById("wsf-1-field-117").value);
    multiMax = Number(document.getElementById("wsf-1-field-113").value);
    multiTotalProblems = Number(
        document.getElementById("wsf-1-field-111").value
    );

    // Hide the form and show the answer, start and problem block
    multiFormWrapper.innerHTML = `<p>${multiTotalProblems} exercises. Lowest factor = ${multiMin}. 
            Highest factor = ${multiMax}</p>`;
    multiAnsForm.style.display = "block";
    questionBlock.style.display = "inline-block";
    multiStartBtn.style.display = "block";
});

function generateProblem() {
    multiNum1 = Math.floor(
        Math.random() * (multiMax - multiMin + 1) + multiMin
    );
    multiNum2 = Math.floor(
        Math.random() * (multiMax - multiMin + 1) + multiMin
    );
    multiQuestionBlock.textContent = `${multiNum1} X ${multiNum2} = `;
}

multiStartBtn.addEventListener("click", function () {
    answerForm.style.display = "block";
    generateProblem();
    multiStartBtn.style.display = "none";
    multiAnsSubmitBtn = document.getElementById("wsf-2-field-116");


if (!isListenerAdded && multiAnsSubmitBtn) {
    multiAnsSubmitBtn.addEventListener("click", function () {
        multiAns = document.getElementById("wsf-2-field-115").value;
        console.log("clicked");
        console.log(multiAns)
        generateProblem();
    });
    isListenerAdded = true;
    
}
    
});
12 Comments
2024/11/11
16:03 UTC

1

Need help with a code issue working fine in android but not in iphone

// Start JavaScript code for popup
$(document).ready(function () {
    $("#upload-image-to-db").click((e) => {
        $('#uploadedImages').empty();
    });

    function appendImagesFromSession() {
        // var imageUrls = getSessionDataByKey('feedback_images');
        var data = getSessionData();
        if (data != null && data['feedback_images'] != undefined) {
            var imageUrl = data['feedback_images'];
            if (imageUrl) {
                $("#uploadedImages").html('');
                $('#uploadedImages').append(
                    '<div class="image-container">' +
                    '<img src="' + imageUrl + '" alt="Selected Image">' +
                    '<button class="delete-button" onclick="deleteUploadedImage(\'' + imageUrl + '\')">&times;</button>' +
                    '</div>'
                );
                document.querySelector('#upload-image-to-db').classList.add('display-none');
                document.querySelector('.form-group2').classList.add('display-none');
            }
        }
    }

    $('#close-upload-popup').click((e) => {
        $('#popup').hide();
        $('#overlay').hide();
    });

    $('#uploadButton').click(function (e) {
        e.preventDefault();
        $('#popup').removeClass("display-none");
        $('#overlay').removeClass("display-none");
        $('#popup').show();
        $('#overlay').show();
        appendImagesFromSession();
    });

    $('#overlay').click(function () {
        $('#popup').hide();
        $('#overlay').hide();
    });

    $('#fileInput').on('change', function () {
        var files = this.files;
        var form = $(this).closest('form');
        form.submit();
        $('#selectedImages').html('');
        if (files) {
            $.each(files, function (index, file) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $('#selectedImages').append('<img src="' + e.target.result + '" alt="Selected Image">');
                };
                reader.readAsDataURL(file);
            });
        }
    });

    $('#uploadForm').on('submit', function (e) {
        document.getElementById('uploadedFileInfo').classList.add('uploaded-file__info--active');
        e.preventDefault();
        $('.loader').show();

        var formData = new FormData();
        var files = this.querySelector('input[type="file"]').files;
        const MAX_FILE_SIZE_MB = 1;
        const MAX_FILE_SIZE_BYTES = MAX_FILE_SIZE_MB * 1024 * 1024;

        // Detect if the device is an iPhone
        function isIPhone(userAgent) {
            return /iPhone/.test(userAgent);
        }

        function isAndroid(userAgent) {
            try {
                return /Android/.test(userAgent);
            } catch (error) {
                // Assume the device is not Android if an error occurs
                return false;
            }
        }

        // Detect if the browser is Chrome on iPhone
        function isIPhoneChrome(userAgent) {
            return /CriOS/.test(userAgent) && isIPhone(userAgent);
        }

        function convertToWebP(file, quality = 0.8) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = function (e) {
                    const img = new Image();
                    img.src = e.target.result;

                    img.onload = function () {
                        const canvas = document.createElement('canvas');
                        const ctx = canvas.getContext('2d');

                        canvas.width = img.width;
                        canvas.height = img.height;
                        ctx.drawImage(img, 0, 0);

                        function adjustCompression() {
                            canvas.toBlob(function (blob) {
                                if (blob) {
                                    if (blob.size <= MAX_FILE_SIZE_BYTES || quality <= 0.1) {
                                        resolve(blob);
                                    } else {
                                        quality -= 0.1;
                                        adjustCompression();
                                    }
                                } else {
                                    reject('Blob creation failed');
                                }
                            }, 'image/webp', quality);
                        }
                        adjustCompression();
                    };

                    img.onerror = function () {
                        reject('Image loading failed');
                    };
                };

                reader.onerror = function () {
                    reject('File reading failed');
                };

                reader.readAsDataURL(file);
            });
        }

        var userAgent = navigator.userAgent;

        // Process each file, handle based on the browser and device
        var processPromises = Array.from(files).map(async (file) => {
            return new Promise((resolve, reject) => {
                if (isAndroid(userAgent)) {
                    convertToWebP(file).then((webpBlob) => {
                        formData.append('images[]', webpBlob, file.name.replace(/\.[^/.]+$/, "") + ".webp");
                        resolve();
                    }).catch(reject);
                } else {
                    formData.append('images[]', file, file.name);
                    resolve();
                }
            });
        });

        Promise.all(processPromises).then(() => {
            addFeedbackImages(formData);
            $('.loader').hide();
        }).catch((error) => {
            console.error(error);
            $('.loader').hide();
            alert('An error occurred: ' + error); // Show the error to the user
        });
    });
});

Why this code is working for android perfectly but not for iphone

1 Comment
2024/11/11
14:02 UTC

2

How do I convert an ArrayBuffer to base64url and vice versa?

I want to convert

[146, 158, 30, 105, 37, 64, 188, 176, 151, 69, 135, 48, 116, 103, 158, 180, 180, 93, 233, 205, 246, 73, 21, 84, 115, 104, 123, 243, 69, 20, 98, 208]

into

kp4eaSVAvLCXRYcwdGeetLRd6c32SRVUc2h780UUYtA
and vice versa.

I know I can convert the ArrayBuffer into a base64url string because this is a value from a toJSON() function from Web Authentication: An API for accessing Public Key Credentials - Level 3. But I don't know how to convert it back.

2 Comments
2024/11/11
13:33 UTC

2

How can I see the implementation of a web api?

I want to see the implementation of PublicKeyCredential: toJSON() method - Web APIs | MDN

3 Comments
2024/11/11
13:03 UTC

1

Tech recruiter training to become a Tech speaker

Hello everyone

I hope you're pulling well.

To give you a bit of background, I'm a tech recruiter at a company and little by little, as I hung out with the devs, the same thing kept coming up: ‘fed up with shitty recruiters who chase us but understand nothing and don't make the effort to understand what we do’.

Well, that's a pretty old observation, I'm not discovering anything, but I've seen it the other way round, if I understand better what I'm being told and what I'm looking for, I'll become better, and have more constructive discussions with the devs I meet (and any other players in tech, po, design, etc.).

So at the moment, with a dev from my company, I'm training on JS in my spare time (with the ultimate aim of trying to make a native react app just for my own personal enjoyment).

Right now I'm eating videos about it, MDN at full blast, I'm having a great time but I was wondering if I shouldn't take a step back from what I'm doing from time to time to look at the macro; try to get to grips with the broad outlines of programming, paradigms, thinking, DB, algo, basic principles, orm...

It's probably overkill, but what do you think would be useful for me to learn, beyond JS for the moment, to have a better understanding, overall, of what I'm doing, reading, coding?

If you have any leads, documentation, principles that you absolutely must have (understanding OOP...)...

Thanks reading me

1 Comment
2024/11/11
12:00 UTC

0

Red and blue boxes

Hi team!

So I'm doing a unit on JavaScript as part of a web development course and the exercise is to get coloured boxes to do stuff.

For example when button one is clicked a blue box appears inside a red box.

When button 2 is clicked the blue box appears underneath the red box.

Now all my buttons work!

The problem I'm having is that when I click button 2 after I click button 1 the blue box from button 1 doesn't disappear leaving 2 blue boxes on the screen?

Is it possible to 'reset' the page (for lack of a better description) as each new button is pressed? Links to materials would be helpful! I'm googling is sending me down rabbit holes. The learning materials provided by my course doesnt really answer my questions?!

Please and thank you!

2 Comments
2024/11/11
11:54 UTC

15

Free help with your Javascript learning / projects

Hey guys, what's up!

My name is Damir, I'm an active full stack Javascript / Python developer and mentor. And I need your help — in exchange of mine, of course

In short: I'm looking for someone who willing to help me to improve my English speaking level in exchange for coding help. Win-win

So I invite you to join one-on-one Zoom meeting(s) to improve YOUR coding skills 💪

What you will get from our meetings:

✓ Better understanding of how things work in your code ✓ Learn new concepts you can't fully embrace ✓ New ways of writing and debugging your code

And, I hope, a bit of joy doing things together 😊

What I expect YOU to give in exchange:

  • Language practice
  • Tips and small piece of advice for how to say things correct
  • Speaking mistakes correction

If you find this interesting, please drop me a few lines about yourself:

  • Your name
  • Time zone
  • Desire coding skills / language to improve on our meeting(s)
  • OR problems you want to solve

My time zone: Ukraine, GMT +2 Speaking level: intermediate-ish

4 Comments
2024/11/11
11:05 UTC

67

Realistically would it be possible to learn enough JS to land freelance gigs or a job in 3 months

I have about 3 months to find a job and I've covered basic html and css and am currently learning js, if I have complete free time i.e 10 hrs per day 6 days a week, and work atleast 8 of those hrs per day, can I get a remote job or gigs on fiverr or upwork assuming I'm willing to work for cheap (yk, 3rd world county and all that)

46 Comments
2024/11/11
10:44 UTC

0

Interactive tables with time/date functionality?

The chair of a conference has tossed me the program, and asked me to make it interactive, so people anywhere in the world can see the events in their own time. The conference will be in person, and online via Zoom, so people will be logging in from all over.

I did this once before, but purely in Excel. So all I want is the ability to form a nice table, with different colored backgrounds for different types of events (papers, workshops, panels etc) and some way for the users to enter their timezones (or just city) and have the table automatically update to show the program in their time.

I know there are some JavaScript based spreadsheets, but I don't need all the fuss of a spreadsheet. Also, I don't want to spend too much time, if possible - so I'm looking for a solution (if there is one) which is beginner friendly.

What is my best approach here?

1 Comment
2024/11/11
09:05 UTC

1

Import json in jsdoc typedef

Hii,

I'm trying to import pacakge.json in jsdoc typedef but it's not working. My goal is to capture keys defined in pacakge-scripts and use them and jsdoc types for other functions.

/**
 * @typedef {import('../package.json').scripts} allScripts
 */

this turns up as any, please help

Edit, I'm also okay with hardcoding it to some extent, but want to create object from array of strings (enums)

/**
 * @typedef {['build', 'prepare-commit', 'setup', 'preview', 'start-server', 'verbose-build']} packageScripts
 */


// But this doesn't work, chatgpt also doesn't solve it, neither found any SO article
/**
 * @type {{[script: keyof packageScripts]: script}} allScripts
 */
4 Comments
2024/11/11
08:57 UTC

2

Call to action for JS Juniors

Hello fellows! I wonder if there're people here interested in starting a new project from scratch. Any new or clone from other projects idea would do. I wanted to do the whole stuff. Beginning with architecture discussion, folder structure, funcionalities discussion, milestones and so on. Discussions would evolve on github issues and we could bounce ideas on a server on discord. Anyone interested? Focusing on entry level developers.

Discord server link: https://discord.gg/FF7BRHNz

0 Comments
2024/11/11
00:19 UTC

0

Need Recommendations for Affordable JavaScript Obfuscation Tools for Business Protection

Good evening, everyone!

I’ve been doing some research on JavaScript obfuscation tools for a project I’m working on, but I’m having trouble finding something suitable. Currently, I’m using JSCrambler, but it’s proving to be too expensive for my project.

The main goal is to protect the business and its intellectual property, so I need a solid obfuscation solution that provides a high level of security without breaking the bank. If anyone has any suggestions for affordable and effective alternatives, I’d really appreciate it!

Thanks in advance!

6 Comments
2024/11/11
00:08 UTC

2

How to use async/await with WebSocket?

I need to send some messages in a specific order from client to server via a WebSocket. However I was shocked realizing that there is no async/await support for the WebSocket class. So, how can I wait for sending one message via web socket to be complete before sending the next one? I am also fine with using a 3rd party library that implements such functionality.

Looking forward to any hint on this, thanks!

2 Comments
2024/11/10
22:12 UTC

1

How to Filter out text

I made this simple code to take an image as an input then displays the image in a frame and then uses OCR to display the text from the image in another frame, now I just want to filter out the text displayed to only show specific words from that text, can anyone help?

here’s the code:

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>AI Image Text Detection</title><script src="https://cdn.jsdelivr.net/npm/tesseract.js@2.1.1/dist/tesseract.min.js"></script><style> body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f0f4f8; display: flex; flex-direction: column; align-items: center; margin: 0; padding: 20px; } h1 { color: #333; margin-bottom: 20px; } input\[type="file"\] { margin-bottom: 20px; padding: 10px; border-radius: 8px; border: 1px solid #ccc; background-color: #fff; cursor: pointer; transition: border-color 0.3s; } input\[type="file"\]:hover { border-color: #888; } .container { display: flex; gap: 20px; } .frame { width: 400px; height: 400px; border-radius: 20px; border: 4px solid #0078D4; background-color: #ffffff; display: flex; justify-content: center; align-items: center; box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1); overflow: hidden; transition: transform 0.3s; } .frame:hover { transform: scale(1.02); } img { max-width: 100%; max-height: 100%; border-radius: 16px; } .text-frame { width: 400px; padding: 20px; border-radius: 20px; border: 4px solid #4CAF50; background-color: #ffffff; box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1); display: flex; justify-content: center; align-items: center; font-size: 16px; white-space: pre-wrap; color: #333; } </style></head><body><h1>Upload Your Image and Extract Text</h1><input type="file" id="imageInput" accept="image/\*"><div class="container"><div class="frame" id="imageFrame"><p>Image will appear here...</p></div><div class="text-frame" id="textFrame"><p>Detected text will appear here...</p></div></div><script> const imageInput = document.getElementById('imageInput'); const imageFrame = document.getElementById('imageFrame'); const textFrame = document.getElementById('textFrame'); imageInput.addEventListener('change', function() { const file = this.files\[0\]; if (file) { const reader = new FileReader(); reader.onload = function(e) { imageFrame.innerHTML = \`<img src="${e.target.result}" alt="Uploaded Image">\`; // Run OCR on the image Tesseract.recognize( e.target.result, 'eng', { logger: (m) => console.log(m) } ).then(({ data: { text } }) => { textFrame.textContent = text.trim() || 'No text detected.'; }).catch(err => { textFrame.textContent = 'Error in text detection.'; console.error(err); }); } reader.readAsDataURL(file); } }); </script></body></html>
4 Comments
2024/11/10
15:14 UTC

6

Is Doing projects while watching tutorials Okay?

I am doing JS. I want to do some projects. So, I watch tutorials on youtube the try recreate each section but sometimes when I forget what to do I again watch the video and then do. Its kind of copy paste but I do improvise a bit where I feel this should be this. Will i be able to improve like this. I am completely newbie I dont know much that is why I watch Tutorials For projects.....

Your Opinions Would be appreciated.......

14 Comments
2024/11/10
14:22 UTC

3

Surprising Precision with Logs

> let {log} = Math;
undefined
> let factor = 1 / log(2);
undefined
> factor
1.4426950408889634
> factor * log(65536)
16
> 16 === factor * log(65536)
true

I was expecting an approximation, like 16.000000000132 or 15.99999999998 .

4 Comments
2024/11/10
14:17 UTC

4

What exactly makes data "unreachable" for garbage collector?

Hello!

I think I understand the basic concept of it like:

const person = "Bob"
person = null; // If there was nothing like person1 = person2, then there is nothing points to "Bob" anymore and it's removed from the memory

But let's say I want to clear a linked list (with no outside connection like const someVariable = head.next)
// head -> node1 -> node2 -> node3
head.next = null

There is still a link to node2 in node1.
I would guess that since there is no link anywhere that points to node1, it would be considered "unreachable" and cleared, which would make node2 "linkless" and then it's something like domino effect.
But I don't think that my guess is correct.

And then what if it's a double linked list? Then there is no "linkless" nodes to begin. So it's a memory leak then?

I tried to look for the answer and some say that head.next=nullis enough, but some say that correct way is to remove links from each node beforehand.

So what exactly makes data "unreachable" for it to be cleared by garbage collector?

8 Comments
2024/11/10
14:12 UTC

Back To Top