J2J jQuery to Modern Javascript

jQuery JS

Event

  • on()

    $('#my_id_or_any_css_selector').on('click',function(){ 
        $(this).css('color','red');
    })

    addEventListener()

    document.getElementById('my-button').addEventListener("click", function(){ 
        /* do some  stuff (add new stuff to previous click event if exist) */
        /* THIS IS THE CURRENT BEST PRACTICES */
    },false);
    
    document.getEmentById('my-button').attachEvent('onclick', function(){ 
        /* do some  stuff (add new stuff to previous click event if exist) */
        /* IE <= 8 */
        /* No final boolean parameter to manage bubbuling event */
    })
    
    document.getElementById('my-button').onclick=function(){ 
        /* do some  stuff (override previous onclick event) */
    }; 
    
    // Do not use this following script if not a good reason (more info)
    <a href=”fallback_link.html” onclick=”alert(‘Bad for maintenace’); return false; ”>Alert Me!</a>
    <a href=”javascript:alert(‘bad for maintenace and no trigger click event’);”>Alert Me!</a>
  • load()

    $(window).load(function(){
       // Do stuff html after the image are loaded 
    });

    addEventListener('load', fn, false);

    window.addEventListener('load', function(){
        // Do stuff html load but before image loaded
        // Modern browser only
    }, false);
  • ready()

    $('document').ready(function(){
       // Do stuff html load but before image loaded
    });
    
    $(function(){
       // Do stuff html load but before image loaded
       // shorten version
    })
    
    jQuery(function($){
       // Do stuff html load but before image loaded
       // safest version , avoid $ conflic with other library  
       // or allow using $ when jQuery is in no conflic mode (eg: wordpress)
    })

    addEventListener('DOMContentLoaded', fn, false);

    document.addEventListener('DOMContentLoaded', function(){
        // Do stuff html load but before image loaded
        // Modern browser only
    }, false);
    
    document.attachEvent("onreadystatechange", function(){
        // Do stuff html load but before image loaded
        // old IE browser only
    });
  • on() // event delegation

    $('#container').on('click','.item',function(){ 
        // DO SOMETHING
    })

    addEventListener('click',function(){event.target})

    function delegate(elSelector, eventName, selector, fn) {
        var element = document.querySelector(elSelector);
    
        if(!element) return;
    
        element.addEventListener(eventName, function(event) {
            var possibleTargets = element.querySelectorAll(selector);
            var target = event.target;
    
            for (var i = 0, l = possibleTargets.length; i < l; i++) {
                var el = target;
                var p = possibleTargets[i];
    
                while(el && el !== element) {
                    if (el === p) {
                        return fn.call(p, event);
                    }
                    el = el.parentNode;
                }
            }
        });
    }
    
    // USAGE
    delegate('#container', 'click', '.item', function(e) {
        // DO SOMETHING
    });
            

Attribut

  • append()

    $("#my_id").append('<p>hello</p>');

    insertAdjacentHTML('beforeend', htmlString)

    var my_id = document.getElementById('#my_id');
    my_id.insertAdjacentHTML('beforeend', '<p>hello</p>');
  • prepend()

    $("#my_id").prepend('<p>hello</p>');

    insertAdjacentHTML('afterbegin', htmlString);

    var my_id = document.getElementById('#my_id');
    my_id.insertAdjacentHTML('afterbegin', '<p>hello</p>');
  • before()

    $("#my_id").before('<p>hello</p>');

    insertAdjacentHTML('beforebegin', 'htmlString')

    var my_id = document.getElementById('#my_id');
    my_id.insertAdjacentHTML('beforebegin', '<p>hello</p>');
  • after()

    $("#my_id").after('<p>hello</p>');

    insertAdjacentHTML('afterend', htmlString);

    var my_id = document.getElementById('#my_id');
    my_id.insertAdjacentHTML('afterend', '<p>hello</p>');
  • empty()

    $('#my_id').empty();

    innerHTML = null;

    var my_id = document.getElementById('#my_id');
    my_id.innerHTML = null;
  • parent()

    $(‘#my_id’).parent();

    parentNode

    document.getElementById("my_id").parentNode
  • children()

    $(‘#my_id’).children();

    childNodes

    document.getElementById("my_id").parentNode.childNodes[]
  • next()

    $(‘#my_id’).next();

    nextElementSibling

    var my_id = document.getElementById('#my_id');
    my_id.nextElementSibling;
  • prev()

    $(‘#my_id’).prev();

    previousElementSibling

    var my_id = document.getElementById('#my_id');
    my_id.previousElementSibling;
  • html()

    $('my_id').html()

    innerHTML

    document.getElementById('myid').innerHTML
  • text()

    $('#my_id').text();

    textContent

    document.getElementById('my_id').textContent
  • replaceWith()

    $('my_id').replaceWith('my string');

    outerHTML

    var my_id = document.getElementById('#my_id');
    myid.outerHTML = 'my string';
  • find()

    $('#my_id').find('span').hide();

    querySelectorAll()

    var my_id = document.getElementById('#my_id');
    var spans = my_id.querySelectorAll('span');
    
    for(i = 0 ; i< spans.length ; i++ ){
        spans[i].style.display = 'none';
    }
  • addClass()

    $('#my_id').addClass('my_class');

    classList.add()

    var my_id = document.getElementById('#my_id');
    my_id.classList.add('my_class');
  • removeClass()

    $('#my_id').removeClass('my_class');

    classList.remove()

    var my_id = document.getElementById('#my_id');
    my_id.classList.remove('my_class');
  • toggleClass()

    $('#my_id').toggleClass('my_class');

    classList.toggle()

    // IE 10 not support
    var my_id = document.getElementById('#my_id');
    my_id.classList.toggle('my_class');
  • hasClass()

    if($('#my_id').hasClass('my_class')){
         // DO SOMETHING
    }

    classList.contains()

    if(document.getElementById('my_id').classList.contains('my_class')){
         // DO SOMETHING 
    }

CSS

  • css() // Set

    $('#my_id').css('color','red');

    style

    var my_id = document.getElementById('#my_id');
    my_id.style.color = 'red';
  • css() // Get

    $('#my_id').css('color');

    getPropertyValue()

    var my_id = document.getElementById('#my_id');
    window.getComputedStyle( my_id.getPropertyValue('color')

Effects

  • show()

    $('#my_id').show();

    style.display

    var my_id = document.getElementById('#my_id');
    my_id.style.display = 'block';
  • hide()

    $('#my_id').hide();

    style.display

    var my_id = document.getElementById('#my_id');
    my_id.style.display = 'none';
  • fadeOut()

    $('#my_button').click(function(){
        $('#my_content').fadeOut();
    })

    requestAnimationFrame()

    function fadeOut(el){
                            
        el.style.opacity = 1;
    
        (function fade() {
            if ((el.style.opacity -= .1) < 0) {
                el.style.display = "none";
            } else {
                requestAnimationFrame(fade);
            }
        })();
        
    }
    
    document.getElementById('my_button').onclick = function(){
    
        fadeOut(document.getElementById('my_content'));
        return false;
        
    };

Ajax

  • $.ajax

    $.ajax({
    	url: "webservice",
    	type: "POST",
    	data: "a=1&b=2&c=3",
    	success: function(d) {
    		console.log(d);
    	}
    });

    XMLHttpRequest()

    var r = new XMLHttpRequest(); 
    r.open("POST", "webservice", true);
    r.onreadystatechange = function () {
    	if (r.readyState != 4 || r.status != 200) return; 
    	console.log(r.responseText);
    };
    r.send("a=1&b=2&c=3");
  • $.getJSON()

    $.getJSON('http://superapi.org/json', function(data){
        console.log(data);
    });

    xmlhttp.overrideMimeType('application/json');

    function getJSON(path, callback) {
                            
        var xmlhttp = new XMLHttpRequest();                 
        xmlhttp.overrideMimeType('application/json');  
    
        xmlhttp.onreadystatechange = function() {
            ready = (xmlhttp.readyState == 4 && xmlhttp.status == 200);
            callback(ready ? xmlhttp.responseText : false);
        };
        xmlhttp.open('GET', path, true);
        xmlhttp.send();
        
    };
    
    getJSON('http://superapi.org/json',function(data){
    
        var data = JSON.parse(data);
        console.log(data);
        
    });
    

Utilities

  • $.each()

    $('div').each(function(){
        $('this').css({backroundColor : "red"});
    });

    each();

    var nodeList = document.getElementsByTagName('div');
    var nodes = Array.prototype.slice.call(nodeList,0); // nodes is an array now. 
    nodes.forEach(function(node){ 
        node.style.backgroundColor = "red";
    });