#How to learn javascript
Explore tagged Tumblr posts
Text
JavaScript Tutorial for Students and Freshers

In today’s digital era, web development is one of the most sought-after skills, and at the heart of every interactive website lies JavaScript. Whether you're a student pursuing computer science or a fresher looking to enter the tech industry, understanding JavaScript is a key step in becoming a competent web developer. This JavaScript tutorial for students and freshers will guide you through the basics, making it easy to get started and build your first interactive web page.
What is JavaScript?
JavaScript is a powerful, high-level scripting language used primarily to create dynamic and interactive features on websites. It runs in the browser and allows developers to manipulate content, respond to user inputs, and communicate with servers — all without needing to reload the page.
JavaScript is one of the core technologies of the web, alongside HTML and CSS. While HTML structures the content and CSS styles it, JavaScript brings it to life.
Why Students and Freshers Should Learn JavaScript
If you are just starting your journey into programming or web development, JavaScript is one of the best languages to learn. Here’s why:
Easy to learn: JavaScript has a beginner-friendly syntax.
Used everywhere: It works in all modern web browsers.
In-demand skill: Almost every company building web apps uses JavaScript.
Foundation for frameworks: React, Angular, and Vue are based on JavaScript.
Great for projects: Helps in creating interactive portfolios, calculators, games, and web apps.
Getting Started with JavaScript
To start writing JavaScript, you don’t need any fancy tools. All you need is a web browser (like Chrome or Firefox) and a text editor (like VS Code, Notepad++, or Sublime Text).
Add JavaScript to an HTML Page
<!DOCTYPE html> <html> <head> <title>My First JavaScript Page</title> </head> <body> <h1>Hello JavaScript!</h1> <script> alert("Welcome, Student!"); console.log("This is your first JavaScript script!"); </script> </body> </html>
This example shows how easy it is to insert JavaScript into a webpage using the <script> tag.
Basic JavaScript Concepts Every Beginner Should Know
1. Variables
Variables store data. You can use let, const, or var (though let and const are preferred in modern JS).let name = "Amit"; const age = 21;
2. Data Types
Common types:
String: "hello"
Number: 100
Boolean: true or false
Array: [1, 2, 3]
Object: {name: "Amit", age: 21}
3. Functions
Functions are reusable blocks of code.function greet() { alert("Hello, student!"); } greet();
4. Conditionals
let score = 85; if (score > 80) { console.log("Excellent!"); } else { console.log("Keep trying!"); }
5. Loops
for (let i = 1; i <= 5; i++) { console.log("Number: " + i); }
DOM Manipulation (Document Object Model)
JavaScript allows you to interact with HTML elements using the DOM.<button onclick="changeText()">Click Me</button> <p id="demo">Original text</p> <script> function changeText() { document.getElementById("demo").innerHTML = "Text changed!"; } </script>
This example changes the paragraph text when the button is clicked — a simple but powerful interaction.
Simple Project Ideas for Students
Practicing with real-world mini-projects helps reinforce your learning. Try building these:
To-Do List App – Add, delete, and mark tasks as complete.
Calculator – A basic calculator for addition, subtraction, etc.
Quiz App – Multiple-choice questions with score calculation.
Digital Clock – Displays current time updating every second.
Form Validation – Check user input like email and password fields.
These projects not only improve your JavaScript skills but also make great additions to your resume or portfolio.
Tools and Resources for Learning
Online Editors: JSFiddle, CodePen, Replit
Documentation: MDN Web Docs
YouTube Channels: Programming with Mosh, FreeCodeCamp, Traversy Media
Courses: Codecademy, Coursera, Udemy (look for beginner JavaScript courses)
Books: Eloquent JavaScript, JavaScript & JQuery by Jon Duckett
JavaScript in the Real World
JavaScript is not limited to client-side browser code. With technologies like Node.js, it’s also used for backend development. Other popular uses include:
Web Development (Frontend & Backend)
Mobile App Development (React Native)
Game Development
Automation and Scripting
APIs and Server Communication
As a fresher or student, learning JavaScript opens doors to multiple career paths in tech.
What’s Next After Learning JavaScript?
Once you’re confident with the basics of JavaScript, you can explore:
ES6 and Modern JavaScript
JavaScript Frameworks (React.js, Angular, Vue.js)
AJAX and APIs – For dynamic data fetching
Node.js – To build server-side applications
Full-Stack Development – Combine JavaScript with HTML/CSS, MongoDB, Express, and Node.js (MERN Stack)
Final Thoughts
This JavaScript tutorial for students and freshers is just the beginning of your journey into web development. JavaScript is not only essential for making websites interactive but also a gateway to understanding advanced programming concepts and full-stack development.
If you dedicate time each day to learning and practicing JavaScript, you'll build a strong foundation that can lead to internships, freelance gigs, and full-time developer roles. Remember: consistency beats complexity. Start small, build projects, and keep coding!
0 notes
Text
The problem with learning things backwards is that it's very hard to tell whether something is difficult because it is actually difficult or because I don't know what I'm doing.
#elumish blogs#elumish complains about learning javascript#book tagging database project#i would like it to tell me how many books are showing on screen at any given time#this requires figuring out exactly how the filtering is working#this requires getting the console log to return literally anything#well no i got it to return errors#i got it to return errors in sections i wasn't even touching
24 notes
·
View notes
Text
I love you indie web I love you Neocities I love you hobby sites held together with duct tape I love you passion I love you whimsy I love you joy
And I am killing SEO with hammers. It’s for the greater good >:3
#woe be upon the employers who try to get me to code things#the adhd brain is inefficient by nature and the dyscalculia brain hates javascript with a passion#and i know jack shit about algorithms. and that’s how i like it#i have my neocities for fun which means the hours spent coding it are never wasted#but at work#inefficiency might as well be a crime#and if i cannot waffle about and be confused for hours the end product will suffer as a result#my neocities is for me bc i thought learning HTML and CSS sounded fun#and it is!#it would not be fun if my creativity was stifled by the SEO popularity contest#my site looks like ass and I’m having a great time#many thanks to whoever’s post abt neocities crossed my dash on that fateful day#i remember you fondly#though i do not know your name#neocities ily#neocities#indie web#static sites#static website#static websites#hobby websites#personal websites#hobbies#if sad check this tag
15 notes
·
View notes
Text
From crude mock-ups in photoshop to a finished-enough something, the sculpting process in skinning kind of looks a little like this for me. Its responsive-ish, which is pretty cool for someone who doesn't really have an interest in responsive design.
See how the mark-up for it is done on my codepen here. Design inspired by this little thing I saw on pinterest.
#wip: a midsummer nights dream#jcink skin#jcink codes#Been spending some spare time learning how to genuinely understand vanilla javascript & basic jquery for this project -#and its actually a little rewarding throwing what i've figured out into execution! more on that later.
43 notes
·
View notes
Text
Finally got my website sorted with a more functional music library. It even has a jukebox! For those who want to listen to my music or get scores for it the link is at https://chroniclesofautumn.com/library.
I still have some stuff on my soundcloud up and occasionally youtube, although those are more auxiliary as far as I am concerned for now. I will bring those into parity with the website either as stuff comes in or I find the time.
#Autumn's Art#spent way too long learning javascript to get it all working nicely#very pleased with how it all came out though
6 notes
·
View notes
Text
jeeez. no wonder baby Aspect bounced off of this so hard. it isn't *super* complicated? but its a lot of things i barely understand *now* all in one place, let alone 5 or 7 years ago. i think i can figure it out, but man. no wonder i hated this lmao
#.txt#coding liveblog#we learned about OOP in high school And college so like. we knew what classes are in Theory#but we didn't do a lot of coding. so stuff like getters and setters aren't Complicated?#but until we took another crack at java a few months ago. they were New and Scary#(they're still Pretty new and Pretty scary but at least I'm Aware of them now)#honestly it's ridiculous to say considering our. Literal Degree. but we only Really got our head around parameters like. earlier this year?#we understood them in theory!!!!! i promise we did#but theory and practice are WHOLLY separate concepts to us. so knowing what they are#versus how to Use them? completely different beasts.#shout out to the interactive javascript tutorial that made me figure it out#no one tell my college lecturers any of this btw they'd be mortified#or my uni lecturers for that matter#sorry guys but y'all sucked ass at teaching Me In Particular
2 notes
·
View notes
Text
Had a moment of listening to music I liked back when I was a teenager (& still like) and having a whole. Realization . That I like myself as I am now sooooo much better than I like teenage me. And I started thinking about Why.
There's a lot to it I'm pretty sure, & most of it centers around the fact that I just... didn't really know who I was as a person. I didn't really have hobbies outside of what I did in school (aka orchestra) and like. Video games + anime. I did creative writing in middle school, but dropped off in high school for... some reason? I still made original characters and played around with them a lot, but it was mostly just in drawing and thinking about them. I never actually *wrote*, and I in fact didn't get back into creative writing at all until I was 23 years old. I was someone who had spent so long hiding behind others and just doing what I was told that I just... didn't have any real direction. I didn't know what I even *wanted*. I thought I knew, but in hindsight, I can confidently say that I didn't. I was just an insecure teen drifting through life and not thinking about things beyond what was immediately in front of me. Which is pretty standard for teenagers I guess, but not all of them. Not at all.
Compared to now, where I have Many hobbies, most notably being writing. As I am now, I am just Intrinsically a writer. And it's weird to remember that I wasn't even really *writing* before 5 years ago (besides text rps, which did a lot for developing my writing skill! But still aren't a replacement for writing individually). As a teen, I wasnt into dnd, I was incredibly out of shape, & I was a lot less aggressive and focused. I was the type to avoid sports!!! I hated them!!!! But as I am now, I Love biking and can easily bike for an hour+ no problem (I remember being a teen and trying to go on just 10 minute bike rides in the summer and just *dying* from it), & I love working out. I wanna be strong!!! I LOVE being strong!!! And I was an absolute mess with things like public speaking & working in groups, vs now where I can do an impromptu presentation no problem & I'm often the unofficial leader in group projects bc im typically the one who does the organizing and allotments of work. A side effect of working as a supervisor and then assistant manager for so long. I have a lot more confidence in my perceptions and judgements, & I have the self-assurance to assert these things. And this is only really the tip of the iceberg with all the differences.
I just feel like an entirely different person, almost. The cores are the same, or at least damn near similar, with the things I want out of life & the sorts of things I enjoy, but it's like. The difference between finding a random rock off the side of the road & then that rock when it's been sanded and carved and decorated to be something individual and unique. You look at them side by side and it's something dull vs something shiny and intricate. The origins can't be ignored and dismissed, & I certainly would never resent younger me for just doing the best with what I knew at the time. But it's just astounding how much difference time and experience will have for growing and developing as a person. Things I consider integral to my personhood weren't even thoughts in my mind back then. We are almost entirely different people.
#speculation nation#under readmore bc I just got contemplative. not negative really either.#ultimately it's that kind of thing of like. college & all my experiences within it have done a LOT for developing who i am as a person.#i wouldnt be nearly so comfortable with public speaking if it werent for how many speech classes ive taken over the years.#but it's also the fact that i was working to figure out who i was during college that made me fumble it so hard.#i wanted to be an engineer. can you believe it? i was so CERTAIN of it as a teenager. but it was only really bc of the family i have/had#that are/were engineers. i didnt have personal interest in it. it was just the Thing To Do.#so i got to college and i *hated* it and i had to take several years to figure out what i actually Wanted.#i realized pretty quickly that i wanted to focus on computers after my first coding class. but thats so BROAD#and computer science wasnt for me either. i fucking hated computer science. but computer information & technology??#this is my shit. and honestly it's so weird to remember that just 10 years i knew very little about computers#and now ill be sitting in my web programming class & theyre talking about javascript and loops and such within it#and im just zoning tf out bc Yeah Yeah do while loops ive heard it a million times before. arrays?? yeah whatever i got it#but back in 2016 i had to learn these things for the first time!!! it was entirely new to me!!! teenage me didnt KNOW#so me being a computer person with a specialization in business and hobbies of writing and biking and dnd. i had NONE of those things!!!#i didnt even collect knives!!!!! granted thats mostly bc i Couldnt buy many of them yet + i also didnt have much money lol#bc i never even worked a job until i got to college. that's also unimaginable to me. imagine not knowing what it's like to Work...#i remember getting $500 or so in graduation gifts after graduating high school & my mind was just Blown#had never had that much money before. it was crazy to me. meanwhile with a job paying every other week $500 was a *low* paycheck.#but i also have to pay bills and rent and buy food and all this stuff. also things i didnt have to worry about back then. ALSO weird.#idk theres a lotta bullshit i gotta deal with as an adult but i like who i am now so much better. feel so much more *myself*#than just a directionless teenager waiting for someone to tell them what to do.#it's amazing what 10 years will do for your development as a person. absolutely wild.
2 notes
·
View notes
Text
I feel like messing around in ink and only reading the documentation when I'm confused is not efficient at all, both in terms of learning and also in just code tidiness, but I feel like this is a grand, inefficient tradition in learning how to use things that I have to maintain (also I'm just fucking around, I'm not actually doing anything yet)
#idk yet if I like Ink but it's not any scarier than Javascript and I learned how to do THAT so#reminds me I gotta get back into learning Lua. I can READ Lua but my writing Lua is bad.
2 notes
·
View notes
Text

Learned how to write some vertex animating shaders today!!! I still don't know how to write c# scripts to control the shaders but :/ progress is progress !!
#pls congradulate me i did not learn anything other than pure misery in my one singular javascript course in college#i wish matt was still here so he could explain how to write up a simple script to control shaders#looping or playing it a defined number of times or setting up triggers and states#i could probably ask the new programmer tbh cause our main one is wayyy too busy#i am feeling a lot more comfortable with shadergraph and visual scripting stuff which is cool!!#i am pretty aware that a lot of places use peoprietary engines though so idk if knowledge of shadergraph is enough to get me by#if i wanted to lean into 'tech art' i think u gotta be an actual programmer for that#waugh
6 notes
·
View notes
Text
#include <iostream>
#include <swaglib>
int main()
{
int swag = getSwag();
if (swag < 0)
std::cout << "Dude wtf is wrong with you."
else if (swag > 10)
fuckingDies();
else
{
std::cout << "Me when I fucking GET you:\n";
case swag
{
10: 9: 8: 7:
std::cout << "I'm so so niceys :3";
break;
6: 5: 4:
std::cout << "Sniles so sneetly";
break;
3: 2: 1:
std::cout << "Duuude. Uncool :("
}
}
return 0;
}
#wyv after dark#maybe i should stop doing shit like this and actually learn how Android Studio works or. JavaScript......
4 notes
·
View notes
Text
not a big update, just some cool stuff i wanted to share 😎
so a month ago i started learning coding and i'm still in the beginner stages (primarily focus on HTML, CSS, javascript, a bit of python and react) and today i made my first browser point & shoot game :)
it's not fancy or polished but that's kinda the point - just me following a tutorial to see what i can do and prove to myself that i can. the background is mine, the bird sprites are taken from said tutorial, so you're welcome to take a look (and even post your highest score in the tags, who knows) -- my own record is in the 600s.
#jakethesnake rambles#coding#programming#video games#gamedev#javascript#the more i do programming the more i appreciate how much effort developers put into things#like holy crap#it doesn't seem like a lot is happening onscrin but there's a wall of code being executed behind the scenes every millisecond#it's so cool and intimidating#love the fact that it's the perfect introvert's job#and you can learn to code for free with literally zero experience and no higher education
11 notes
·
View notes
Text
My brother: when programming, if you're having trouble getting something to work, think through the logic of what you're trying to accomplish
Me: the logic isn't the problem. jQuery is the problem
#elumish blogs#book tagging database project#i am going to learn so much JavaScript by the time i am done with this#i have so many ideas#and genuinely no idea how to do many of them#honestly learning about jquery did help#but the fact that i am working off of html knowledge from 15 years ago and the internet#is making this#difficult
14 notes
·
View notes
Text
What is Async Anyway?
Explaining async/await and general concurrency concepts in programming languages.
A lot of modern languages have async/await syntax built directly into them, and the construct can be extremely useful. Examples of languages that include these concepts are JavaScript, C#, Python, and Swift, and even modern relatively low-level languages like Rust have this syntax. Even though it's usually thought of as a more advanced feature, I think it is really not that hard to use once you get the hang of it, and it is super useful and rewarding when you really understand it.
This is going to be a bit of a long and pretty technical post, but I hope it can give you some confidence to know what async/await really does when you use it, and maybe it can help you use it more effectively. Keep in mind that I will not be able to go over everything in super deep detail, and that I am going to simplify stuff, but it should give you an idea how these systems work.
I am a little curious about eventually following this up with a post looking at how these systems compare under the hood in different programming languages, so let me know if you'd be interested in that.
Big post under the cut.
Parallelism and Concurrency
Computers today can do many things at the same time. And I mean that literally: in one instant, a modern CPU can be working on multiple instructions. That's because a single CPU has multiple cores that can all execute code (mostly) independent from each other. This is called parallelism, and the way we as programmers interact with that is through threads. Most programming languages, especially "lower level" ones, have a way for programmers to create a thread that will run some part of your code. Creating a thread is telling the computer that it can, and should, run the code in your threads in parallel (although various systems such as the OS still have discretion over when and if that actually happens).
Parallelism is not quite concurrency tho. Where parallelism is about your computer literally doing multiple things at once, concurrency is about your computer doing multiple things, but not at once. With concurrency, you kind of pretend you're doing a parallelism. But in reality, stuff doesn't happen at the same time. Instead, your system (runtime) does some work on task A a bit, then on task B, then maybe again on task A, etc., but doesn't work on the two at the same time. So, in a concurrent system it might look like task A and B are progressing simultaneously from the outside, but work actually only happens in sequence.
Let's Talk About I/O
I/O stands for input/output and describes data in your program that comes from elsewhere, or that gets sent elsewhere. So for example, user input is I/O. And similarly, a web request can be I/O, whether you send it or receive it. So let's use that as an example: you send a web request to some API to fetch you the cutest bunny images and facts:
But the service is taking its sweet time to respond.
Fact: Loading bunny fact…
With how we did it here, we halt execution of the entire thread until the response comes in (at least in most languages, more on that later). In this case, we call get a blocking method because it, well, blocks the thread without actively doing useful work.
What if we could instead use the thread for other tasks instead of just sitting there, twiddling our thumbs and waiting on the server? This smells of concurrency…
Callbacks
Callbacks are a way for programmers to avoid that period of thumb twiddling. The new getWithCallback function now returns immediately, but it doesn't return a value. Instead, we have to register the code we want to run once the server responds with the function:
The function we pass to getWithCallback is called the callback, and it gets called by the client* only once the response arrives. Oh look, here it is:

Fact: A rabbit's life span is about 8 years, though sterilized rabbits (those who are spayed/neutered) can live as long as 10-12 years.
*"The client calls it" is a big simplification, there might be a lot more stuff happening here. But the important bit is that the client magically does not need to block to wait for the response.
Promises and Futures
What JavaScript calls Promises and what a lot of the other languages call Futures is essentially sugar sprinkled on callbacks - it makes our callback code a little nicer. Callbacks can commonly create a concept called "callback hell", where you have to call a function that takes a callback inside the function that takes a callback inside the function that takes a callback…
(Code modified from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises)
To avoid this, functions now can return a Promise instead of taking a callback. Promises represent the promise that, while a concrete value might not exist right now, it will in the future. Once the value exists, we say the Promise resolves. The code above with Promises would then look like this:
It still doesn't look perfect, and there are things you can do to make it look a little nicer, but it's so much less nested. The callback in the then function will be called once the value is ready, and the callback itself can also return a Promise. The then function then returns a Promise which will get resolved once the future from the callback is resolved. Many other languages have a concept similar to JavaScript's Promise, and it's often called something like Future or Task (because it would be too easy to have consistent naming across languages).
Now keep in mind neither of those solutions above are really "concurrency" in the definition we used above. This is because the thread we call, for example, getWithCallback on still completely belongs to us. We could keep using it, and we would not get interrupted to execute the callback. Depending on the language and runtime, the callback might get executed on a different thread, or the runtime might have to wait until we are completely done with what we were doing to then use our thread to call it. The same thing goes for the callbacks in the then method of promises.
Async/Await
And async/await is just some sugar and magic fairy dust on top of Promises (or Futures or whatever). It makes our code look like it should be blocking, but in reality it isn't. Here's what our bunny image code looks like with async/await:
So here, a couple things happen. First, the Promise is created and the web request is initiated. Then, the Promise is awaited. For that, (if the Promise is not resolved at this point already,) the task first yields, meaning it tells the runtime that it is not doing any useful work at the moment, and that the thread it ran on can be used for other tasks. The runtime then makes a note of where to continue execution when that Promise resolves, and looks around for other tasks that currently need executing to put them on that thread. After a while passes, the Promise resolves, and once the runtime has some resources available for us (maybe because another task just yielded), execution on our original task is continued with the API response.

Fact: A rabbit's teeth never stop growing! Many people believe they need to chew to keep their teeth short. While they do enjoy chewing, it's the normal wear from where their top and bottom teeth meet that keeps a rabbit's teeth short.
This is more in line with the concurrency we sought out above. We can interleave other computations while our task is still running, but during times where it is not doing any useful work. (Still, because you may have multiple threads your tasks can run on and move between, it might not always be 100% technically accurate to call this system concurrent.) This is also why it is important to not block for long in async contexts: if you're hogging the thread for too long, you're stopping other tasks from progressing and throwing a lot of the benefits you gained from doing it concurrently in the bin. Most async runtimes will give you some option to run expensive or blocking code elsewhere, so that you can keep the benefits you gain from async.
So that's the explanation what async/await does, and the broad strokes of how it works. If you have any more questions regarding the topic, feel free to ask! I think it'll be fun to occasionally write a longer post on interesting things I've learned, so if you have topic suggestions, don't be afraid to tell me!
Further links and sources
Don't Block The Event Loop! - Why you should avoid blocking in Node.js, and what pitfalls to look out for.
I got the bnuuy images and facts from the animality API. The licenses on the images are not super clear, but I'll assume it's okay for me to use them here with credit because it's an open API.
I lifted the definitions and some of the explanation for parallelism and concurrency from Steve Klabnik's talk on Rust's Journey to Async/Await. The talk is more technical and very focused on Rust, but it's a great talk.
I referenced the mdn web docs at various points, they're a great resource.
I created the code screenshots using the carbon app.
#codeblr#coding#programming#progblr#javascript#wow this was something to put together#uh yea thanks for reading#I really liked writing on this#just discovered codeblr recently and was instantly motivated to write a kind of “explanation from the ground up” thing#but I feel like there are some places where I can improve my explanations and such#still learning how to write this stuff and I think I kinda just want to get this out there at this point#I hope it can help someone out a bit or that someone finds this interesting#long post#God I Wish Tumblr Supported Code Blocks#the writing process didn't contain as much research as you might think#I picked up this stuff slowly over a long time and I can't possibly source where I got all of that from#doing posts that I need to more actively research for could also be fun#just challenging myself to learn more#but yea really feel free to ask questions I know this stuff is confusing and I didn't phrase everything perfectly#asks and messages are open#okay I'm going to sleep now goodnight
2 notes
·
View notes
Text
A Better API for the Resize Observer
New Post has been published on https://thedigitalinsider.com/a-better-api-for-the-resize-observer/
A Better API for the Resize Observer


Resize Observer, Mutation Observer, and Intersection Observers are all good APIs that are more performant than their older counterparts:
The API for these three observers are quite similar (but they have their differences which we will go into later). To use an observer, you have to follow the steps below:
Create a new observer with the new keyword: This observer takes in an observer function to execute.
Do something with the observed changes: This is done via the observer function that is passed into the observer.
Observe a specific element: By using the observe method.
(Optionally) unobserve the element: By using the unobserve or disconnect method. (depending on which observer you’re using).
In practice, the above steps looks like this with the ResizeObserver.
// Step 1: Create a new observer const observer = new ResizeObserver(observerFn) // Step 2: Do something with the observed changes function observerFn (entries) for (let entry of entries) // Do something with entry // Step 3: Observe an element const element = document.querySelector('#some-element') observer.observe(element); // Step 4 (optional): Disconnect the observer observer.disconnect(element)
This looks clear (and understandable) after the steps have been made clear. But it can look like a mess without the comments:
const observer = new ResizeObserver(observerFn) function observerFn (entries) for (let entry of entries) // Do something with entry const element = document.querySelector('#some-element') observer.observe(element);
The good news is: I think we can improve the observer APIs and make them easier to use.
The Resize Observer
Let’s start with the ResizeObserver since it’s the simplest of them all. We’ll begin by writing a function that encapsulates the resizeObserver that we create.
function resizeObserver () // ... Do something
The easiest way to begin refactoring the ResizeObserver code is to put everything we’ve created into our resizeObserver first.
function resizeObserver () const observer = new ResizeObserver(observerFn) function observerFn (entries) for (let entry of entries) // Do something with entry const node = document.querySelector('#some-element') observer.observe(node);
Next, we can pass the element into the function to make it simpler. When we do this, we can eliminate the document.querySelector line.
function resizeObserver (element) const observer = new ResizeObserver(observerFn) function observerFn (entries) for (let entry of entries) // Do something with entry observer.observe(node);
This makes the function more versatile since we can now pass any element into it.
// Usage of the resizeObserver function const node = document.querySelector('#some-element') const obs = resizeObserver(node)
This is already much easier than writing all of the ResizeObserver code from scratch whenever you wish to use it.
Next, it’s quite obvious that we have to pass in an observer function to the callback. So, we can potentially do this:
// Not great function resizeObserver (node, observerFn) const observer = new ResizeObserver(observerFn) observer.observe(node);
Since observerFn is always the same — it loops through the entries and acts on every entry — we could keep the observerFn and pass in a callback to perform tasks when the element is resized.
// Better function resizeObserver (node, callback) const observer = new ResizeObserver(observerFn) function observerFn (entries) for (let entry of entries) callback(entry) observer.observe(node);
To use this, we can pass callback into the resizeObserver — this makes resizeObserver operate somewhat like an event listener which we are already familiar with.
// Usage of the resizeObserver function const node = document.querySelector('#some-element') const obs = resizeObserver(node, entry => // Do something with each entry )
We can make the callback slightly better by providing both entry and entries. There’s no performance hit for passing an additional variable so there’s no harm providing more flexibility here.
function resizeObserver (element, callback) const observer = new ResizeObserver(observerFn) function observerFn (entries) for (let entry of entries) callback( entry, entries ) observer.observe(element);
Then we can grab entries in the callback if we need to.
// Usage of the resizeObserver function // ... const obs = resizeObserver(node, ( entry, entries ) => // ... )
Next, it makes sense to pass the callback as an option parameter instead of a variable. This will make resizeObserver more consistent with the mutationObserver and intersectionObserver functions that we will create in the next article.
function resizeObserver (element, options = ) const callback = options const observer = new ResizeObserver(observerFn) function observerFn (entries) for (let entry of entries) callback( entry, entries ) observer.observe(element);
Then we can use resizeObserver like this.
const obs = resizeObserver(node, callback ( entry, entries ) // Do something ... )
The observer can take in an option too
ResizeObserver‘s observe method can take in an options object that contains one property, box. This determines whether the observer will observe changes to content-box, border-box or device-pixel-content-box.
So, we need to extract these options from the options object and pass them to observe.
function resizeObserver (element, options = ) const callback, ...opts = options // ... observer.observe(element, opts);
Optional: Event listener pattern
I prefer using callback because it’s quite straightforward. But if you want to use a standard event listener pattern, we can do that, too. The trick here is to emit an event. We’ll call it resize-obs since resize is already taken.
function resizeObserver (element, options = ) // ... function observerFn (entries) for (let entry of entries) if (callback) callback( entry, entries ) else node.dispatchEvent( new CustomEvent('resize-obs', detail: entry, entries , ), ) // ...
Then we can listen to the resize-obs event, like this:
const obs = resizeObserver(node) node.addEventListener('resize-obs', event => const entry, entries = event.detail )
Again, this is optional.
Unobserving the element
One final step is to allow the user to stop observing the element(s) when observation is no longer required. To do this, we can return two of the observer methods:
unobserve: Stops observing one Element
disconnect: Stops observing all Elements
function resizeObserver (node, options = ) // ... return unobserve(node) observer.unobserve(node) , disconnect() observer.disconnet()
Both methods do the same thing for what we have built so far since we only allowed resizeObserver to observe one element. So, pick whatever method you prefer to stop observing the element.
const obs = resizeObserver(node, callback ( entry, entries ) // Do something ... ) // Stops observing all elements obs.disconect()
With this, we’ve completed the creation of a better API for the ResizeObserver — the resizeObserver function.
Code snippet
Here’s the code we’ve wrote for resizeObserver
export function resizeObserver(node, options = ) const observer = new ResizeObserver(observerFn) const callback, ...opts = options function observerFn(entries) for (const entry of entries) // Callback pattern if (callback) callback( entry, entries, observer ) // Event listener pattern else node.dispatchEvent( new CustomEvent('resize-obs', detail: entry, entries, observer , ) ) observer.observe(node) return unobserve(node) observer.unobserve(node) , disconnect() observer.disconnect()
Using this in practice via Splendid Labz
Splendid Labz has a utils library that contains an enhanced version of the resizeObserver we made above. You can use it if you wanna use a enhanced observer, or if you don’t want to copy-paste the observer code into your projects.
import resizeObserver from '@splendidlabz/utils/dom' const node = document.querySelector('.some-element') const obs = resizeObserver(node, callback ( entry, entries ) /* Do what you want here */ )
Bonus: The Splendid Labz resizeObserver is capable of observing multiple elements at once. It can also unobserve multiple elements at once.
const items = document.querySelectorAll('.elements') const obs = resizeObserver(items, callback ( entry, entries ) /* Do what you want here */ ) // Unobserves two items at once const subset = [items[0], items[1]] obs.unobserve(subset)
Found this refactoring helpful?
Refactoring is ultra useful (and important) because its a process that lets us create code that’s easy to use or maintain.
If you found this refactoring exercise useful, you might just love how I teach JavaScript to budding developers in my Learn JavaScript course.
In this course, you’ll learn to build 20 real-world components. For each component, we start off simple. Then we add features and you’ll learn to refactor along the way.
That’s it!
Hope you enjoyed this piece and see you in the next one.
#ADD#API#APIs#Article#Articles#border#box#code#Code Snippet#content#course#CSS#css-tricks#developers#digitalocean#easy#event#Exercise#Features#functions#how#it#JavaScript#Learn#loops#Method#Mutation#News#newsletter#One
0 notes
Text
man my obsidian note graph looks so fucking haphazard LMFAO
#tbf its very scattered rn#cause im mostly using it for learning notes#aka how to do stuff in unity#blender/godot/figma and so on#so theyre kinda in their own piles w/some rare overlap#like coding stuff that covers C sharp and javascript#personal.txt
1 note
·
View note
Text
Oh yeah yesterday I went to my C programming professor's office hours to ask about what's being covered in class tomorrow. Since I can't go bc of my PT appointment overlapping with it & I'm apparently the kind of student that cares about attending every single class now.
While I was there, I ended up chatting with him about a few things, including my current standing in the class. He asked what I got on the midterm exam, & I answered it was an 87, and he told me I was one of the top 5 or 6 scores in the Whole Class (this being a like. Maybe 70 or so person class). Top score was a 92 or 93 (idr lol) & the class average was a 72. Apparently there were a few of us in the upper 80s/lower 90s, but most people got 70s or lower. And once he does the curve on the exam, he said I'd probably end up with a 97 or so on the exam. So yay!!!
And then he told me how he's noticed how I come to class every day and am really active with taking notes and answering questions. Bc I also sit up front all the time lmao. Hadn't even realized how much of a damned teacher's pet I've been being, but I've been Trying to be a good student this year. But he said I was the type of student that if I got an 88% or smth in the class, he'd likely bump me up to a 90% so I'd get an A lol. But he also said so long as I keep up with how I have been, I could possibly get a 100% in the class by the end (bc I've been there for all the extra credit questions in class and whatever).
And just. I went there bc I wanted to make sure I didn't miss anything important in class on Wednesday, and I ended up having my ego stroked for Real. Felt good to have my efforts be recognized.
#speculation nation#now if only i could care that much for my web coding class. but oh well im still keeping up even if its a reluctant shamble much of the time#other stuff we talked about was how im graduating this semester & how i plan to stay in indiana to work#bc i have family here & i like the relatively low cost of living. & im not particularly ambitious.#just wanna make enough money to live comfortably. dont need anything fancy beyond that.#& he talked about how that's a good outlook in life. how he's known ppl who went to fuckin silicon valley or whatever#with high paying jobs. but the cost of living is so high that theyre effectively not making much more money than here#he said smth about like. a $70k salary has just as much strength here than a $120k salary there. smth around those#& he praised me on how i seem genuine and hard-working. so he thinks im gonna do just fine in the industry 🥺🥺🥺#i kinda wanted to keep chatting with him but i had to go to bowling class lol. ended up late to it even#bc i checked my phone for the time while chatting and went Oh Fuck bc it wss 1 min after the class started hfkshfks had to rush off then#but yeah makes me feel very nice about that class. i think it rly is my favorite class this semester.#web programming is pretty rewarding and im glad im taking it. but i was basically a complete newbie in html css and javascript#so ive spent quite a lot of time wanting to tear out my fucking HAIR over these labs. b4 it clicks and im like Haha yayy :3#i like C programming bc it's just so much more logical and regimented. it IS the language that got me to give up my engineering degree#since i was thinking about computer engineering. took my first coding class freshman year. and went 'i love this. i want to do CS now'#didnt do that obviously. but im happy where ive ended up. i wouldnt wanna be a programmer lol#and then my quality engineering in IT class. it's certainly engaging. it's the class i constantly have presentations in tho#had Another one this morning. blah! good to keep in practice but i still dont rly enjoy public speaking lmao#probably the most work intensive of my classes. interesting but Blegh#C programming i just keep up with the labs and do the exams and it's wonderful... so logical and comforting...#oh yeah web programming i also have a few presentations. also gotta fucking. code my project pages by next week 😭😭😭#i think it's just the html and css? no javascript yet. thank god. javascript is by far the hardest to learn#but css is so finicky too!!!! ive been struggling with trying to move these fucking input boxes around#i wanna have them on the right!! but they wont go there!!! gotta poke at it more. at least i managed to finish building the form.#still have to finish the lab tho. that was due 2 days ago. lol. also have another one due sunday. AND the project pages. gah!!!#they havent even graded the wireframes yet. i wanted their feedback b4 proceeding to coding >:( oh well#anyways yeah..im keeping busy lol
3 notes
·
View notes