10 ترفند برای استفاده از جاوا اسکریپت بدون jQuery

10 ترفند برای استفاده از جاوا اسکریپت بدون jQuery
تقریبا میشه گفت که بهترین کتابخونه جاوا اسکریپت , jQuery هست و می تونید به راحتی با توابع jQuery کار کنید و یا توابع جدیدی بسازید. اما با پیشرفتی که در دنیای وب شاهدب هستیم میتونید برای خیلی از کارای ساده , از jQuery استفاده نکنید و با چند خط کد جاوا اسکریپت نتیجه مطلوبتون رو بگیرید.
دارالترجمه رسمی
دارالترجمه رسمی پارسیس شامل خدمات ترجمه رسمی و تخصصی در بیش از 60 زبان زنده دنیا
جای بروشور دیواری
خرید جای بروشور دیواری و رومیزی
افزونه های سئو وردپرس
بهترین افزونه های سئو وردپرس به صورت کاملا فارسی
تعمیر لوازم خانگی
تعمیر جاروبرقی، مایکروفر، بخارشوی، ظرفشویی، لباسشویی، سولاردام، کولرگازی
خودتان را اینجا معرفی کنید

در این مقاله قرار نیست قدرت jQuery رو زیر سوال ببریم! خیلی از کمپانی های بزرگ از jQuery استفاده می کنند. از همکاران jQuery می توان به Wordpress , IBM , MAXCDN , Adobe و دیگر کمپانی های بزرگ اشاره کرد. خیلی از وب سایت های برگزیده در طراحی خودشون از jQuery استفاده کردن اما در این مقاله 10 ترفند رو به نمایش میزاریم تا برای کارهای پیش پا افتاده از jQuery استفاده نکنید.

1 - لود شدن کامل سایت

در ابتدای کدهای jQuery همیشه 
$(document).ready()
رو مینویسیم تا کدهای ما زمانی اجرا شود که بدنه HTML سایت به طور کامل بارگذاری شده باشد. می توان از قطعه کد زیر برای جایگزینی استفاده کرد.
// Add an event listener of DOMContentLoaded to the whole document and call an anonymous function.
// You can then wrap your code in that function's brackets
// and it will execute once loading is complete.

document.addEventListener('DOMContentLoaded', function () {

    // Our hawaiian greeting is displayed as soon as the page loads,

    console.log('Aloha');

});

 2 - انتخاب المان ها

در روزگاران قدیم ( laugh ) فقط می تونستیم با tag , class , id یک المان رو برای جاوا اسکریپت انتخاب کنیم. در عین حال jQuery با آزادی عملی که در انتخاب المان ها بهمون میداد داشت زندگی ما رو نجات میداد. اما دیگه این مشکل حل شده و می تونید با 
querySelector
خیلی راحت انتخاب کنید.
// We can use document.querySelector to get the first element that matches a certain criteria.
// It's only argument is a string containing one or more CSS selectors.

var lochNess = document.querySelector(".monsters");

console.log("It's from Scotland - " + lochNess.textContent);

// We can also get all elements of a certain type or class by using document.querySelectorAll.
// This returns a NodeList of all the elements that fit our criteria.

var scary = document.querySelectorAll(".monsters");

console.log("Hide and seek champions: ");

for (var i = 0; i < scary.length; i++) {

    console.log(scary[i].innerHTML);

}

3 - اضافه کردن و برداشتن Listener های رویدادها

گوش دادن ( Listening ) به رویداد های مختلف بخش مهمی از برنامه های تحت وب است، در قدیم دو روش برای این کار وجود داشت به اسم IE و rest ولی امروزه تنها از طریق addEventListener میشه این کار رو کرد.
var btn = document.querySelectorAll("button"),
    list = document.querySelector("ul");

// We call the addEventListener method on our desired event target(in this case a button).
// This will start a listener that will wait until a click is generated on the element.

btn[0].addEventListener("click", function () {

    // When this button is clicked we want to enable zooming of our list.

    // To do this we add an event listener to our list itself,
    // so when the cursor hovers it, the enlarge function gets called.

    list.addEventListener("mouseover", enlarge);
});

// To disable the zooming we can simply use removeEventListener.

btn[1].addEventListener("click", function () {

    // Removing event listeners doesn't work on anonymous functions, so always use a named one.

    list.removeEventListener("mouseover", enlarge);
});

// Let's create our enlarge function.

var enlarge = function () {

    // Add class zoomed to the unordered list.

    list.classList.add("zoomed");

    // When the cursor leaves the list return to normal size by removing the class.

    list.addEventListener("mouseout", function () {

        list.classList.remove("zoomed")

    });

};

// Now we want to be able to color the names by clicking them.

// When a 'click' is registered on one of the list entries it should change its color to green.
// Thanks to event delegation we can actually add an event listener to the whole parent object.
// This way we don't have to add separate event listeners to each <li>.

list.addEventListener("click", function (e) {

    // Make the coloring happen only to the clicked element by taking the target of the event.

    e.target.classList.add('green');

});
addEventListener میتواند آرگومان سومی به اسم useCapture داشته باشد اما استفاده از این آرگومان اختیاری است.

4 - دست کاری کلاس ها و صفت ها

دست بردن و تغییر دادن کلاس ها و صفت ها از طریق jQuery بسیار کاربردی میباشد، با استفاده از خاصیت classList این کار به سادگی انجام میشود، همچنین اگر میخواهید صفات را تغییر دهید میتوانید از setAttribute استفاده کنید.
var btn = document.querySelectorAll("button"),
    div = document.querySelector("#myDiv");

btn[0].addEventListener("click", function () {

    // Get any attribute easily.
    console.log(div.id);
});


// Element.classList stores all classes of the element in the form of a DOMTokenList.

var classes = div.classList;


btn[1].addEventListener("click", function () {

    console.log(classes);

});

btn[2].addEventListener("click", function () {

    // It supports adding and removing classes.
    classes.add("red");

});

btn[3].addEventListener("click", function () {

    // You can also toggle a class on and off
    classes.toggle("hidden");

});

5 - Get و Set کردن محتویات المنت ها

jQuery دو متد ()text و ()html برای این کار دارد، همچنین میتوانید از دو خاصیت textContent و innerHTML استفاده کنید، کاری که مدتی طولانی برای تغییرات انجام میدادیم.
var myText = document.querySelector("#myParagraph"),
    btn = document.querySelectorAll("button");

// We can easily get the text content of a node and all its descendants.

var myContent = myText.textContent;

console.log("textContent:  " + myContent);

// When using textContent to alter the text of an element
// it deletes the old content and replaces it with new.

btn[0].addEventListener('click', function () {
    
    myText.textContent = " Koalas are the best animals ";
    
});

// If we want to grab all the HTML in a node (including the tags) we can use innerHTML.

var myHtml = myText.innerHTML;

console.log("innerHTML:  " + myHtml);

// To change the html simply supply new content.
// Of course we aren't limited to text only this time.

btn[1].addEventListener('click', function () {
    
    myText.innerHTML = "<button> Penguins are the best animals </button>";
    
});

6 - Insert و Remove کردن المنت ها

jQuery نسبت به زمانی که این کار را میخواستید با جاوا اسکریپت انجام دهید عملیات را ساده تر کرده است، اما Insert و Remove کردن المنت ها در جاوا اسکریپت به صورت زیر میباشد.
var lunch = document.querySelector("#lunch");

// In the HTML tab we have our lunch for today.

// Let's say we want to add fries to it.

var addFries = function () {

    // First we have to create our new element and set its content

    var fries = document.createElement("div");
    fries.innerHTML = '<li><h4> Fries </h4></li>';

    // After that's done, we can use appendChild to insert it.
    // This will make our fries appear at the end of the lunch list.

    lunch.appendChild(fries);

};

// Now we want to add cheese both before and after the beef in our burger.

var addCheese = function () {

    var beef = document.querySelector("#Beef"),

            topSlice = document.createElement("li"),
            bottomSlice = document.createElement("li");

    bottomSlice.innerHTML = topSlice.innerHTML = 'Cheese';

    // Inserting the top slice:
    // Take the parent of the beef (that's the sandwich) and use insertBefore on it.
    // The first argument to insertBefore is the new element we're gonna add.
    // The second argument is the node before which the new element is inserted.

    beef.parentNode.insertBefore(topSlice, beef);

    // The bottom slice:
    // We have to use a little trick here!
    // Supply the next nearest element as the second argument to insertBefore,
    // that way we can actually insert after the element we want.

    beef.parentNode.insertBefore(bottomSlice, beef.nextSibling);

};

var removePickles = function () {

    // Finally, we want to get rid of those pickles. Again javascript got us covered!

    var pickles = document.querySelector("#pickles");

    if (pickles) {
        pickles.parentNode.removeChild(pickles);
    }

};

// Delicious!

var btn = document.querySelectorAll("button");

btn[0].addEventListener('click', addFries);

btn[1].addEventListener('click', addCheese);

btn[2].addEventListener('click', removePickles);

7 - پیشمایش بر روی درخت DOM

تمام نینجا های جاوا اسکریپت میدانند که قدرت نهفته ی زیادی روی پیشمایش درخت DOM در صفحه وجود دارد، شما میتوانید کارهای زیادی برای جابجایی بین المنت ها در DOM انجام دهید که در زیر نمونه های کاربردی آن را میبینیم.
var snakes = document.querySelector('#snakes'),
    birds = document.querySelector('#birds');

snakes.addEventListener('click', function (e) {

    // To access the parent of a certain element in the DOM tree, we use the parentNode method.

    var parent = e.target.parentNode;

    console.log("Parent: " + parent.id);


    // For the opposite, calling the .children method gets all child elements of the selected object.

    console.log("Children: ");
    var children = e.target.children;

    // This returns a HTMLCollection (a type of array), so we have to iterate to access every child's content.

    for (var i = 0; i < children.length; i++) {

        console.log(children[i].textContent);

    }
});


birds.addEventListener('click', function (e) {

    // Getting the nearest sibling to our element is self-explanatory.

    var previous = e.target.previousElementSibling;

    if (previous) {
        console.log("Previous sibling: " + previous.textContent);

    }

    var next = e.target.nextElementSibling;

    if (next) {
        console.log("Next sibling: " + next.textContent);

    }

    // However, to acquire all the siblings of a node is a bit more complex.
    // We have to take all of its parent's children and then exclude the original element.
    // This is done by using filter and calling a function that checks every child one by one.

    console.log("All siblings: ");

    Array.prototype.filter.call(e.target.parentNode.children, function (child) {
        if (child !== e.target) {
            console.log(child.textContent);
        }
    });

});

8 - گردش روی آرایه ها

بجای اینکه در jQuery از ()each و ()map استفاده کنیم میتوانیم جاوا اسکریپت از forEach و map استفاده کنیم و آرایه هایمان را iterate کنیم، فقط هنگامی که از کد زیر میخواهید استفاده کنید به کاربرد this و آرگومان های ورودی توجه کنید و آن را مطابق با نیاز خود تغییر دهید.
var ninjaTurtles = ["Donatello", "Leonardo", "Michelangelo", "Raphael"];

// ForEach automatically iterates through an array.

ninjaTurtles.forEach(function (entry) {
    console.log(entry);
});

// The map method calls a function on every element of an array and creates a new array with the results.

var lovesPizza = ninjaTurtles.map(function (entry) {

    return entry.concat(" loves pizza!");

});

console.log(lovesPizza);

9 - انیمیشن ها

در jQuery میتوانستید با استفاده از متد animate کارهای انیمیشنی خود را انجام دهید، اما زمانی که کارها کمی پیچیده میشد به پایان رساندن پروژه کاری طاقت فرسا میشد، با تشکر از CSS امروزه میتوانید بسیاری از کارهای خود را از طریق Animate.css انجام دهید، که از این طریق میتوانید با اضافه کردن و حذف کردن کلاس به المنت، کارهای انیمیشنی خود را انجام دهید.
var btn = document.querySelectorAll("button"),
        circle = document.querySelector("#circle");

// First, we have to add a class of animated to our object, so the library can recognize it.

circle.classList.add('animated');


// We iterate over all of our buttons and add event listeners to each one.

for (var i = 0; i < btn.length; i++) {

    // Define an anonymous function here, to make it possible to use the i variable.

    (function (i) {

        btn[i].addEventListener('click', function () {

            // To start an animation you just have to add a specific class to the object.
            // In our case we stored the classes' names in the data-animation attribute of each button.

            var animation = btn[i].getAttribute('data-animation');

            circle.classList.add(animation);

            // To make it work more then once we have to remove the class after the animation is complete.

            window.setTimeout(function () {

                circle.classList.remove(animation);

            }, 1000);

        });

    }(i));

}

10 - AJAX

AJAX یکی از تکنولوژی هایی بود که برای عملیات تحت سرور در مرورگر به وجود آمد، خبر خوب این است که میتوانید از این کد در همه جا استفاده کنید و خبر بد اینکه فرستادن درخواست AJAX از طریق XMLHttpRequest مشکلاتی را ایجاد میکند، بهترین کار استفاده از یک کتابخانه ی آماده است، برای مثال میتوانید از کتابخانه های سبکی برای این کار استفاده کنید، در اینجا یک مثال را با استفاده از کتابخانه ی reqwest پیاده سازی کردیم.
// This simple example logs the body of our url (a html file) in the console.

// It's possible to do a manual GET request but it is somewhat a tedious task.

var request = new XMLHttpRequest();
request.open('GET', 'http://tutorialzine.com/misc/files/my_url.html', true);

request.onload = function (e) {
    if (request.readyState === 4) {

        // Check if the get was successful.

        if (request.status === 200) {
            console.log(request.responseText);
        } else {
            console.error(request.statusText);
        }
    }
};

// Catch errors:

request.onerror = function (e) {
    console.error(request.statusText);
};

request.send(null);

// Using a small library, such as Reqwest, can make your job much easier.

reqwest({
    url: 'http://tutorialzine.com/misc/files/my_url.html',
    method: 'get',
    error: function (err) {
    },
    success: function (resp) {
        console.log(resp);
    }
});

نتیجه گیری
پیاده سازی صفحه ی وب با جاوا اسکریپت خالص باعث میشود صفحه ی شما سریع تر شود و سرعت بارگذاری آن بهتر شود، همچنین به این نکته دقت کنید که کاری که از قبل انجام شده است را دوباره انجام ندهید، برای مثال لزومی ندارد چرخ را دوباره اختراع کنید، سعی کنید شیوه ی توسعه ی خود را بهبود ببخشید.
 

رضا از سال 87 برنامه نویسی را با زبان های خانواده C شروع کرد و بعد از 4 سال به سمت طراحی و برنامه نویسی تحت وب رفت. وی همزمان با تحصیل در مقطع کارشناسی رشته مهندسی کامپیوتر به امر ترجمه کتاب در حوزه برنامه نویسی مشغول بود که کتاب او در مرحله ویراستاری قرار دارد. به روز بودن و افزایش مستمر اطلاعات شخصی در زمینه وب دغدغه ی اصلی و همیشگی رضاست.

نظرات و سوالات کاربران

ارسال پاسخ یاسین
یاسین
دوشنبه ۰۹ اردیبهشت ۱۳۹۸ ۱۹:۲۳
سلام وقت بخیر
من در روزگاران قدیم جاوااسکریپت رو فرانگرفته بودم
الان که اومدم این queryselector وجود داشت
فقط من متوجه نمیشم که میگین

در روزگاران قدیم ( laugh ) فقط می تونستیم با tag , class , id یک المان رو برای جاوا اسکریپت انتخاب کنیم. در عین حال jQuery با آزادی عملی که در انتخاب المان ها بهمون میداد داشت زندگی ما رو نجات میداد. اما دیگه این مشکل حل شده و می تونید با queryselector خیلی راحت انتخاب کنید.

مثلا شما قبلا به چی نمیتونستین دسترسی داشته باشین ؟
ی مثال میزنین