Native addEventListener with selector like .on() in jQuery

To perform event delegation natively: parent.addEventListener(‘click’, function(e) { if(e.target.classList.contains(‘myclass’)) { // this code will be executed only when elements with class // ‘myclass’ are clicked on } }); The efficiency you are referring to has to do with how many event handlers you add. Imagine a table with 100 rows. It is much more efficient … Read more

What’s the difference between event handlers & listener?

A handler and a listener are one in the same – just synonyms for the function that will handle an event. “Handler” is probably the more accepted term, and is certainly more semantically correct to me. The term “listener” is derived from the code used to add an event to an element: element.addEventListener(‘click’, function() { … Read more

Force re-firing of all (scripts / functions) on ajaxed content

The solution you choose here will have to depend on how the scripts are initialized. There are a couple common possibilities: The script’s actions are evoked immediately upon loading of the script. In this case, the script might look something like this: (function() { console.log(‘Running script…’); })(); The script’s actions are evoked in response to … Read more

Way to know if user clicked Cancel on a Javascript onbeforeunload Dialog?

You can do it like this: $(function() { $(window).bind(‘beforeunload’, function() { setTimeout(function() { setTimeout(function() { $(document.body).css(‘background-color’, ‘red’); }, 1000); },1); return ‘are you sure’; }); }); The code within the first setTimeout method has a delay of 1ms. This is just to add the function into the UI queue. Since setTimeout runs asynchronously the Javascript … Read more

Implementing jQuery’s “live” binder with native Javascript

Here’s a simple example: function live(eventType, elementId, cb) { document.addEventListener(eventType, function (event) { if (event.target.id === elementId) { cb.call(event.target, event); } }); } live(“click”, “test”, function (event) { alert(this.id); }); The basic idea is that you want to attach an event handler to the document and let the event bubble up the DOM. Then, check … Read more

event.keyCode constants

You can define the KeyEvent object if it doesn’t exist: if (typeof KeyEvent == “undefined”) { var KeyEvent = { DOM_VK_CANCEL: 3, DOM_VK_HELP: 6, DOM_VK_BACK_SPACE: 8, DOM_VK_TAB: 9, DOM_VK_CLEAR: 12, DOM_VK_RETURN: 13, DOM_VK_ENTER: 14, DOM_VK_SHIFT: 16, DOM_VK_CONTROL: 17, DOM_VK_ALT: 18, DOM_VK_PAUSE: 19, DOM_VK_CAPS_LOCK: 20, DOM_VK_ESCAPE: 27, DOM_VK_SPACE: 32, DOM_VK_PAGE_UP: 33, DOM_VK_PAGE_DOWN: 34, DOM_VK_END: 35, DOM_VK_HOME: … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)