-
Dec 3rd, 2024, 05:58 PM
#1
Thread Starter
Fanatic Member
a Little Javascript Libary
Hi I made this a few years back and found it on my drive it was me trying to show how easy it was to make your own jQuery just using basic java code so here it is hope someone finds it usfull.
Code:
// MyLib Version 1.0
// Aurthor Ben J @DreamVB https://github.com/DreamVB
// Last-update : 3 March 2022 21:40pm
const $ = (selector) => {
// returns the HTML elements that match the selector
const elements = document.querySelectorAll(selector);
//Return the elements collection to the $MyLib class
return new $Mylib(elements, selector);
};
class $Mylib {
constructor (elements) {
this._elements = elements;
}
//Appends HTML to the current element
append (html){
this._elements[0].innerHTML += html;
return this;
}
//Apends HTML to the end of the current element
prepend (html){
this._elements[0].innerHTML = html + this._elements[0].innerHTML;
return this;
}
//Used to add a new class to the elements
addClass (className) {
this._elements.forEach((element) => element.classList.add(className));
return this;
}
//Removes a class from the elements
removeClass (className) {
this._elements.forEach((element) => element.classList.remove(className));
return this;
}
//Return a value eg for text fields
val(value){
if (value !== undefined) {
//Set element value
this._elements[0].value = value;
}else{
//Return element value.
return this._elements[0].value;
}
}
//Returns HTML code from a element
html(value){
if (value !== undefined) {
//Set element HTML code
this._elements[0].innerHTML = value;
}else{
//Return the HTML code
return this._elements[0].innerHTML;
}
}
text(value){
if (value !== undefined) {
this._elements[0].textContent = value;
} else {
return this._elements[0].textContent;
}
}
//Sets styles on the elements
css(value){
this._elements.forEach((element) => element.setAttribute("style",value));
return this;
}
//Return true if a element has a class that matches classname
hasClass(classname){
if (this._elements[0].classList.contains(classname)) {
return true;
}
return false;
}
hide(){
//Hide elements
this._elements.forEach((element) => element.style.display = "none");
}
show(){
//Show elements
this._elements.forEach((element) => element.style.display = "block");
}
attr(name,value){
this._elements.forEach((element) => element.setAttribute(name,value));
return this;
}
//Toogle an elements class eg show / hide
toggleClass (className) {
this._elements.forEach((element) => {
const classList = element.classList;
(classList.contains(className)) ? classList.remove(className) : classList.add(className);
});
return this;
}
//Add an event to a element such as mouse click
onEvent (event, func){
this._elements[0].addEventListener(event,func,false);
}
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|