Vanilla javaScript detect ‘click’ and ‘touch’ events in one boilerplate function.

        /**
         * Run a callback after a click or tap, without running duplicate callbacks for the same event
         * Hem dokunma hemde click eventlerinin aynı anda tetiklenmemesi için bir Callback ile geri besleme
         * Works in all modern browsers, and at least back to IE9.
         * @public
         * @polyfill    @required               None
         * @components  @required   @TODO       'util.queryElement()', 'util.on()'
         * @param       {Node}      elem        The element to listen for clicks and taps on
         * @param       {Function}  callback    The callback function to run on a click or tap
         */
        onClickOrTap: function (elem, callback) {

            elem = util.queryElement(elem);

            // Make sure a callback is provided
            if ( !callback || typeof(callback) !== 'function' ) return;

            // Variables
            var isTouch, startX, startY, distX, distY;

            /**
             * touchstart handler
             * @param  {event} event The touchstart event
             */
            var onTouchStartEvent = function (event) {
                // Disable click event
                isTouch = true;

                // Get the starting location and time when finger first touches surface
                startX = event.changedTouches[0].pageX;
                startY = event.changedTouches[0].pageY;
            };

            /**
             * touchend handler
             * @param  {event} event The touchend event
             */
            var onTouchEndEvent = function (event) {

                // Get the distance travelled and how long it took
                distX = event.changedTouches[0].pageX - startX;
                distY = event.changedTouches[0].pageY - startY;

                // If a swipe happened, do nothing
                if ( Math.abs(distX) >= 7 || Math.abs(distY) >= 10 ) return;

                // Run callback
                callback(event);

            };

            /**
             * click handler
             * @param  {event} event The click event
             */
            var onClickEvent = function (event) {
                // If touch is active, reset and bail
                if ( isTouch ) {
                    isTouch = false;
                    return;
                }

                // Run our callback
                callback(event);
            };

            // Event listeners
            util.on('touchstart', elem, onTouchStartEvent);
            util.on('touchend', elem, onTouchEndEvent);
            util.on('click', elem, onClickEvent);

        }

Function Components

on()

        /**
         * Add events or an event
         * Works in all modern browsers, and at least back to IE9.
         * @public
         * @polyfill    @required                   None
         * @components  @required       @TODO       'eventListenerHandler()'
         * @param       {String|Node}   types       The event type or types (space separated)
         * @param       {String}        selector    The selector to run the event on (, seperated)
         * @param       {Function}      callback    The function to run when the event fires
         */
        on: function (types, selector, callback) {

            // Make sure there's a selector and callback
            if (!selector || !callback) return;

            // Loop through each event type
            types.split(',').forEach((function (type) {

                // Remove whitespace
                type = type.trim();

                // If no event of this type yet, setup
                if (!activeEvents[type]) {
                    activeEvents[type] = [];
                    WIN.addEventListener(type, eventListenerHandler, true);
                }

                // Push to active events
                activeEvents[type].push({
                    selector: selector,
                    callback: callback
                });

            }));

        }

off()

        /**
         * Remove events or an event
         * Works in all modern browsers, and at least back to IE9.
         * @public
         * @polyfill    @required                   None
         * @components  @required       @TODO       'getListenerIndex()', 'eventListenerHandler()'
         * @param       {String|Node}   types       The event type or types (space separated)
         * @param       {String}        selector    The selector to remove the event from (, seperated)
         * @param       {Function}      callback    The function to remove
         */
        off: function (types, selector, callback) {

            // Loop through each event type
            types.split(',').forEach((function (type) {

                // Remove whitespace
                type = type.trim();

                // if event type doesn't exist, bail
                if (!activeEvents[type]) return;

                // If it's the last event of it's type, remove entirely
                if (activeEvents[type].length < 2 || !selector) {
                    delete activeEvents[type];
                    WIN.removeEventListener(type, eventListenerHandler, true);
                    return;
                }

                // Otherwise, remove event
                var index = getListenerIndex(activeEvents[type], selector, callback);
                if (index < 0) return;
                activeEvents[type].splice(index, 1);

            }));

        }

one()

        /**
         * Add events or an event
         * The handler is executed at most once per element per event type.
         * İşleyici, etkinlik türü başına öğe başına en fazla bir kez yürütülür ve sonra otomatik olarak silinir.
         * Works in all modern browsers, and at least back to IE9.
         * @public
         * @polyfill    @required                   None
         * @components  @required       @TODO       'util.on()', 'util.off()'
         * @param       {String|Node}   types       The event type or types (space separated)
         * @param       {String}        selector    The selector to remove the event from (, seperated)
         * @param       {Function}      callback    The function to remove
         */
        one: function (types, selector, callback) {
            util.on(types, selector, function callbackWrapper(e){
                callback(e);
                util.off(types, selector, callbackWrapper);
            });
        }

queryElement()

        /**
         * Return Query Element
         * Works in all modern browsers, and at least back to IE9/8.
         * @public
         * @polyfill    @required                   None
         * @components  @required                   None
         * @param       {String|Node}   selector    The selector to query element
         * @param       {Node}          elem        Parent Element
         * @returns     {Node}          elem        If has class return true
         */
        queryElement: function (selector, parent) {
            var lookUp = parent ? parent : DOC;
            return typeof selector === 'object' ? selector : lookUp.querySelector(selector);
        }

Vanilya JavaScript ile bir diziden tekrar eden ögeleri çıkarmak

Bazen bir dizide (array) birden fazla olacak şekilde öge tekrarlanabilir.

var sehirler = ["Ankara", "İstanbul", "İzmir", "Ankara"];

Yukarıda görüldüğü üzere “Ankara” ögesi listemizde iki kere tekrarlanıyor. Biz bu listeyi müşterilerimize sunacağımız bir seçim menüsü haline getireceksek karmaşaya sebep verecektir. Bu nedenle tekrar eden ögeleri temizlememiz gerekir.

var sehirler = ["Ankara", "İstanbul", "İzmir", "Ankara"];
var sehirlerTekrarsiz = sehirler.filter(function(item, index){
	return sehirler.indexOf(item) >= index;
});

console.log(sehirlerTekrarsiz);
// Çıktı ["Ankara", "İstanbul", "İzmir"]

Yukarıdaki işlemleri her bir kod bloğunda tekrar tekrar kullanmak hem sizi hemde sitenizi (fazla kod satırı) yoracaktır. Bunun için bir yardımcı fonksiyon yazdık.

Getting Full Function Helper

var arrayUnique = function (arr) {
	return arr.filter(function(item, index){
		return arr.indexOf(item) >= index;
	});
};

var jobsUnique = arrayUnique(jobs);

Beğendiyseniz takip edebilirsiniz:

Diğer 2 aboneye katılın

Vanilla JS ile Animasyon Fonksiyonu Kullanımı

Hızlı bir özet

Buradaki yaklaşım, karmaşık JS kodlarına güvenmek yerine, öge’deki CSS animasyonlarını tetikleyen bir sınıf eklemeyi/çıkarmayı içerir. Ki bundan daha önce bahsetmiştik.

<h1 id="elem">Animate</h1>

<button class="show">Show</button>
<button class="hide">Hide</button>
var elem = document.querySelector('#elem');
document.addEventListener('click', function (event) {

	if (event.target.matches('.show')) {
		elem.removeAttribute('hidden');
		elem.classList.add('fadeInDown');
	}

	if (event.target.matches('.hide')) {
		elem.setAttribute('hidden', 'true');
		elem.classList.remove('fadeInDown');
	}

}, false);

Getting Full Setup

 * Apply a CSS animation to an element
 * @param  {Node}    elem      The element to animate
 * @param  {String}  animation The type of animation to apply
 * @param  {Boolean} hide      If true, apply the [hidden] attribute after the animation is done
 */
var animate = function (elem, animation, hide) {

	// If there's no element or animation, do nothing
	if (!elem || !animation) return;

	// Remove the [hidden] attribute
	elem.removeAttribute('hidden');

	// Apply the animation
	elem.classList.add(animation);

	// Detect when the animation ends
	elem.addEventListener('animationend', function endAnimation (event) {

		// Remove the animation class
		elem.classList.remove(animation);

		// If the element should be hidden, hide it
		if (hide) {
			elem.setAttribute('hidden', 'true');
		}

		// Remove this event listener
		elem.removeEventListener('animationend', endAnimation, false);

	}, false);

};