Click here to Skip to main content
15,891,423 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I was wondering how I could make something like $() in JQuery. I want to make my own JS Library, and want to do something like, maybe: elem().fadeIn(). In the parentheses of elem, you would put your querySelector, e.g. elem('.banana'). And then use that as a parameter for fadeIn. Please tell me if this is too confusing.

What I have tried:

I don't know where to start, sorry.
Posted
Updated 19-Feb-21 10:41am

Think of $() as being a wrapper object that wraps up a lot of functionality.

I will give you an example you can run to see it work.
But this sample will be a bit simpler.

JavaScript
let $ = (el) => {console.log(el)};


That actually defines a function named $ that takes one parameter named el.

To run it you can pass in an element like the following:

JavaScript
$(document.querySelectorAll("img")[0]);



You could make $ an object that contains a bunch of other functions (basically what jQuery did).

JavaScript
let $ = {};

$.double = (a) => a*2;
$.multiply = (a,b) => a*b;

Now you can use it like the following:
JavaScript
$.double(3);
$.multiple(3,4);
 
Share this answer
 
Comments
Tilier 18-Feb-21 18:10pm    
How would I do just $('.banana').fadeIn(), though? I'm a bit confused.
Not sure how this will help you but you can do the following:

JavaScript
let $ = (item) => ({element:item, fadeIn:function (){ console.log(document.querySelector(this.element)) } });


Now you can call it:

JavaScript
$(".banana").fadeIn();


In this case it will just print the element object.

You will have to do the work to define the fadeIn() function.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900