DOM Events API: event delegation and stopPropagation - javascript

This is a code with jQuery 1.7:
<div class="test">
<div class="bu">
<a>
bu here
</a>
</div>
</div>
<script src="http://code.jquery.com/jquery-1.7.js"></script>
<script>
$(document).on('click', '.test', function () { alert(0); return false; });
$(document).on('click', '.bu', function () { alert(1); return false; });
$(document).on('click', '.bu', function () { alert(2); return false; });
</script>
Xlicking on .test > .bu will alert "1" and alert "2", but not alerts "0"
My question is: how to do the same WITHOUT jQuery (on native DOM API)? Seems, I can't do it with Native DOM API without implementing my own library...

Here you go:
document.addEventListener( 'click', function ( e ) {
if ( hasClass( e.target, 'bu' ) ) {
// .bu clicked
// do your thing
} else if ( hasClass( e.target, 'test' ) ) {
// .test clicked
// do your other thing
}
}, false );
where hasClass is
function hasClass( elem, className ) {
return elem.className.split( ' ' ).indexOf( className ) > -1;
}
Live demo: http://jsfiddle.net/Nrxp5/30/

<div class="a">
<div class="b">
<div class="c" style="border: 1px solid silver; width: 80px; text-align: center;line-height: 80px;">
click me!
</div>
</div>
</div>
<script>
// Element.prototype.matchesSelector
(function (x) {
var i;
if (!x.matchesSelector) {
for (i in x) {
if (/^\S+MatchesSelector$/.test(i)) {
x.matchesSelector = x[i];
break;
}
}
}
}(Element.prototype));
Document.prototype.on =
Element.prototype.on = function (eventType, selector, handler) {
this.addEventListener(eventType, function listener(event) {
var t = event.target,
type = event.type,
x = [];
if (event.detail && event.detail.selector === selector && event.detail.handler === handler) {
return this.removeEventListener(type, listener, true);
}
while (t) {
if (t.matchesSelector && t.matchesSelector(selector)) {
t.addEventListener(type, handler, false);
x.push(t);
}
t = t.parentNode;
}
setTimeout(function () {
var i = x.length - 1;
while (i >= 0) {
x[i].removeEventListener(type, handler, false);
i -= 1;
}
}, 0);
}, true);
};
Document.prototype.off =
Element.prototype.off = function (eventType, selector, handler) {
var event = document.createEvent('CustomEvent');
event.initCustomEvent(eventType, false, false, {selector: selector, handler: handler});
this.dispatchEvent(event);
};
document.on('click', '.b', function () {
alert(2);
});
document.on('click', '.a', function () {
alert(1);
});
document.on('click', '.b', function (event) {
alert(3);
event.stopPropagation();
});
</script>

Here is a prototype based version
Document.prototype.on = function(event, target = null, callBack){
this.addEventListener(event, function(event){
let len = target.length, i = 0;
while(i < len){
if(event.target === target[i]){
callBack.call(target[i], event);
}
i ++;
}
}, false);
};
Usage is like jQuery has:
let btns = document.getElementsByTagName('button');
document.on('click', btns, function(event){
console.log(this.innerText)
});
And a live example is below:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body bgcolor="#000">
<button>hello1</button>
<button>hello2</button>
<script type="text/javascript">
Document.prototype.on = function(event, target = null, callBack = function(){}){
this.addEventListener(event, function(event){
let len = target.length, i = 0;
while(i < len){
if(event.target === target[i]){
callBack.call(target[i], event);
}
i ++;
}
}, false);
};
//example of usage
let btns = document.getElementsByTagName('button');
document.on('click', btns, function(t){
alert(this.innerText);
})
//add elements after delegating an event
let newBtn = document.createElement('button');
newBtn.innerText = 'btnNew';
document.body.appendChild(newBtn);
//delay to create
setTimeout(function(){
let newBtn = document.createElement('button');
newBtn.innerText = 'another btnNew';
document.body.appendChild(newBtn);
},2000);
</script>
</body>
</html>

Related

js differ click and double click

I am trying to differentiate click and dblclick events by javascript. I tried stopPropagation in dblclick however did not work. hence I coded my own function using setTimeout tries to avoid calling the other when calling one.
/* dblclick differ click
takes two functions as param and one element
to bind the event listener on
*/
function cdblclick(click, dblclick, el){
el.cooled = true;
el.addEventListener('click', function(){
if(el.cooled){
setTimeout(function(){
if(!el.cdblc){el.cdblc = 0}
el.cdblc++;
if(el.cdblc === 1){
setTimeout(function(){
if(!el.doubled){
console.log('click')
// click();
el.cdblc = 0;
el.cooled = true;
el.doubled = false;
}
}, 300);
}else if(el.cdblc === 2){
console.log('double')
// dblclick();
el.doubled = true;
el.cdblc = 0;
el.cooled = true;
}else{
}
}, 250);
}
});
}
however, it does not work properly. I will be so glad if you ca give me a hand.
Thanks for the suggestions of divide to two elements, however, I must implement both events on the same element
solution
thanks to all the helps.
/* dblclick differ click
takes two functions as param and one element
to bind the event listener on
*/
function cdblclick(click, dblClick, el) {
let clickedTimes = 0;
const incrementClick = () => {
clickedTimes++;
};
const reset = () => {
clickedTimes = 0;
};
el.addEventListener('click', e => {
incrementClick();
setTimeout(() => {
if (clickedTimes === 1) {
click(e);
} else if (clickedTimes >= 2) {
dblClick(e);
}
reset();
}, 300);
});
}
Here's a solution where each 'click counter' is specific to each element, so onclick functions outside the element will not be effected...
const singleOrDouble = ({target}) => {
if (isNaN(target.cn)) {
target.cn = 1
} else {
target.cn++
}
setTimeout(() => {
if (target.cn == 1) {
console.log('once')
target.cn = 0
}
if (target.cn > 1) {
console.log('twice')
target.cn = 0
}
}, 500)
}
<p onclick="singleOrDouble(event)">Click me</p>
If you dont want to execute the single click at all in case of double, you can use a timeout like you did. You just have to reset the counter and the timeout properly. You do not reset el.cdblc on your last empty else.
Be aware, that this delays normal clicks.
/* dblclick differ click
takes two functions as param and one element
to bind the event listener on
*/
function cdblclick(click, dblclick, el){
//REM: Storing the values in an object instead of own element properties
let tObject = {
Clicks: 0,
onClick: click,
onDblClick: dblclick
};
//el.cooled = true;
el.addEventListener('click', function(object){
object.Clicks += 1;
//REM: Starting the click..
if(object.Clicks === 1){
object.Timeout = window.setTimeout(function(){
//REM: Execute click if not stopped
if(typeof object.onClick == 'function'){
object.onClick()
};
//REM: Resetting the click count
object.Clicks = 0
/*if(!el.cdblc){el.cdblc = 0}
el.cdblc++;
if(el.cdblc === 1){
setTimeout(function(){
if(!el.doubled){
console.log('click')
// click();
el.cdblc = 0;
el.cooled = true;
el.doubled = false;
}
*/
}.bind(this, object), 300)
}
//REM: Unless we have triple clicks, there is only double left
else{
//REM: Cancel the single click
window.clearTimeout(object.Timeout);
//REM: Execute double click
if(typeof object.onDblClick === 'function'){
object.onDblClick()
};
//REM: Resetting the click count
object.Clicks = 0
/*
console.log('double')
// dblclick();
el.doubled = true;
el.cdblc = 0;
el.cooled = true;
*/
}
}.bind(el, tObject))
};
document.querySelector('b').onclick = cdblclick(
function(){console.log('onclick')},
function(){console.log('ondblclick')},
document.body
);
<b>Click me</b>
Like this will work.
function cDblClick(click, dblClick, el) {
let clickedTimes = 0;
const incrementClick = () => {
clickedTimes++;
};
const reset = () => {
clickedTimes = 0;
};
el.addEventListener('click', () => {
incrementClick();
setTimeout(() => {
if (clickedTimes === 1) {
click();
} else if (clickedTimes === 2) {
dblClick();
}
reset();
}, 300);
});
}
you can try ondblclick js listner like this :
document.getElementById('click').onclick = function() { console.log("click"); }
document.getElementById('dblclick').ondblclick = function() { console.log("double click"); }
<div>
<button id="click"> click </button>
<button id="dblclick"> double click </button>
</div>
You can try this way to differ click and dbclick:
document.getElementById('click').onclick = function() {
//do something if click
}
document.getElementById('click').ondblclick = function() {
//do something if dbclick
}
<div>
<button id="click"> click or dbclick? </button>
</div>

Jquery tab is not working

I have one problem with click function. I have created this demo from jsfiddle.net.
In this demo you can see there are smile buttons. When you click those buttons then a tab will be opening on that time. If you click the red button from tab area then the tab is not working there are something went wrong.
Anyone can help me here what is the problem and what is the solution?
The tab is normalize like this working demo
var response = '<div class="icon_b">
<div class="clickficon"></div>
<div class="emicon-menu MaterialTabs">
<ul>
<li class="tab active"> TAB1</li>
<li class="tab"> TAB2</li>
<li class="tab"> TAB3<span></span></li>
</ul>
<div class="panels">
<div id="starks-panel1" class="panel pactive"> a </div>
<div id="lannisters-panel1" class="panel"> b </div>
<div id="targaryens-panel1" class="panel"> c </div>
</div>
</div>
</div>';
$(document).ready(function () {
function showProfileTooltip(e, id) {
//send id & get info from get_profile.php
$.ajax({
url: '/echo/html/',
data: {
html: response,
delay: 0
},
method: 'post',
success: function (returnHtml) {
e.find('.user-container').html(returnHtml).promise().done(function () {
$('.emoticon').addClass('eactive');
});
}
});
}
$('body').on('click', '.emoticon', function(e) {
var id = $(this).find('.emoticon_click').attr('data-id');
showProfileTooltip($(this), id);
});
$(this).on( "click", function() {
$(this).find('.user-container').html("");
});
var componentHandler = function() {
'use strict';
var registeredComponents_ = [];
var createdComponents_ = [];
function findRegisteredClass_(name, opt_replace) {
for (var i = 0; i < registeredComponents_.length; i++) {
if (registeredComponents_[i].className === name) {
if (opt_replace !== undefined) {
registeredComponents_[i] = opt_replace;
}
return registeredComponents_[i];
}
}
return false;
}
function upgradeDomInternal(jsClass, cssClass) {
if (cssClass === undefined) {
var registeredClass = findRegisteredClass_(jsClass);
if (registeredClass) {
cssClass = registeredClass.cssClass;
}
}
var elements = document.querySelectorAll('.' + cssClass);
for (var n = 0; n < elements.length; n++) {
upgradeElementInternal(elements[n], jsClass);
}
}
function upgradeElementInternal(element, jsClass) {
if (element.getAttribute('data-upgraded') === null) {
element.setAttribute('data-upgraded', '');
var registeredClass = findRegisteredClass_(jsClass);
if (registeredClass) {
createdComponents_.push(new registeredClass.classConstructor(element));
} else {
createdComponents_.push(new window[jsClass](element));
}
}
}
function registerInternal(config) {
var newConfig = {
'classConstructor': config.constructor,
'className': config.classAsString,
'cssClass': config.cssClass
};
var found = findRegisteredClass_(config.classAsString, newConfig);
if (!found) {
registeredComponents_.push(newConfig);
}
upgradeDomInternal(config.classAsString);
}
return {
upgradeDom: upgradeDomInternal,
upgradeElement: upgradeElementInternal,
register: registerInternal
};
}();
function MaterialTabs(element) {
'use strict';
this.element_ = element;
this.init();
}
MaterialTabs.prototype.Constant_ = {
MEANING_OF_LIFE: '42',
SPECIAL_WORD: 'HTML5',
ACTIVE_CLASS: 'pactive'
};
MaterialTabs.prototype.CssClasses_ = {
SHOW: 'materialShow',
HIDE: 'materialHidden'
};
MaterialTabs.prototype.initTabs_ = function(e) {
'use strict';
this.tabs_ = this.element_.querySelectorAll('.tab');
this.panels_ = this.element_.querySelectorAll('.panel');
for (var i=0; i < this.tabs_.length; i++) {
new MaterialTab(this.tabs_[i], this);
}
};
MaterialTabs.prototype.resetTabState_ = function() {
for (var k=0; k < this.tabs_.length; k++) {
this.tabs_[k].classList.remove('pactive');
}
};
MaterialTabs.prototype.resetPanelState_ = function() {
for (var j=0; j < this.panels_.length; j++) {
this.panels_[j].classList.remove('pactive');
}
};
function MaterialTab (tab, ctx) {
if (tab) {
var link = tab.querySelector('a');
link.addEventListener('click', function(e){
e.preventDefault();
var href = link.href.split('#')[1];
var panel = document.querySelector('#' + href);
ctx.resetTabState_();
ctx.resetPanelState_();
tab.classList.add('pactive');
panel.classList.add('pactive');
});
}
};
MaterialTabs.prototype.init = function() {
if (this.element_) {
this.initTabs_();
}
}
window.addEventListener('load', function() {
componentHandler.register({
constructor: MaterialTabs,
classAsString: 'MaterialTabs',
cssClass: 'MaterialTabs'
});
});
});
There is updated and working version.
What we have to do, is to move the target on the same level as the icon is (almost like tab and content). Instead of this:
<div class="emoticon">
<div class="emoticon_click" data-id="1">
<img src="http://megaicons.net/static/img/icons_sizes/8/178/512/emoticons-wink-icon.png" width="30px" height="30px">
<div class="user-container" data-upgraded></div>
</div>
</div>
We need this
<div class="emoticon">
<div class="emoticon_click" data-id="1">
<img src="http://megaicons.net/static/img/icons_sizes/8/178/512/emoticons-wink-icon.png" width="30px" height="30px">
// not a child
<!--<div class="user-container" data-upgraded></div>-->
</div>
// but sibling
<div class="user-container" data-upgraded></div>
</div>
And if this is new HTML configuration, we can change the handlers
to target click on div "emoticon_click"
change the content of the sibling (not child) div "user-container"
The old code to be replaced
$('body').on('click', '.emoticon', function(e) {
var id = $(this).find('.emoticon_click').attr('data-id');
showProfileTooltip($(this), id);
});
$(this).on( "click", function() {
$(this).find('.user-container').html("");
});
will now be replaced with this:
//$('body').on('click', '.emoticon', function(e) {
$('body').on('click', '.emoticon_click', function(e) {
// clear all user container at the begining of this click event
$('body').find('.user-container').html("");
// find id
var id = $(this).attr('data-id');
// find the parent, which also contains sibling
// user-container
var parent = $(this).parent()
// let the target be initiated
showProfileTooltip($(parent), id);
});
$(this).on( "click", function() {
//$(this).find('.user-container').html("");
});
Check it in action here
NOTE: the really interesting note was in this Answer by pinturic
If we want to extend the first and complete answer with a feature:
close all tabs if clicked outside of the area of tabs or icons
we just have to
add some event e.g. to body
and do check if the click was not on ".emoticon" class elements
There is a working example, containing this hook:
$('body').on( "click", function(e) {
// if clicked in the EMOTICON world...
var isParentEmotion = $(e.toElement).parents(".emoticon").length > 0 ;
if(isParentEmotion){
return; // get out
}
// else hide them
$('body').find('.user-container').html("");
});
I have been debugging your code and this is the result:
you are adding the "tab" under ; any time you click within that div this code is intercepting it:
$('body').on('click', '.emoticon', function(e) {
var id = $(this).find('.emoticon_click').attr('data-id');
showProfileTooltip($(this), id);
});
and thus the "tab" are built again from scratch.

how to check the click is single or double in javascript

I am trying to check whether a click on an element is a single click or a double click.
I am trying with this code.
var clk_ch = document.getElementById('clk');
function singleClick() {
alert("single click");
}
function doubleClick() {
alert("double click");
}
var clickCount = 0;
clk_ch.addEventListener('click', function() {
alert();
clickCount++;
if (clickCount === 1) {
singleClickTimer = setTimeout(function() {
clickCount = 0;
singleClick();
}, 400);
} else if (clickCount === 2) {
clearTimeout(singleClickTimer);
clickCount = 0;
doubleClick();
}
}, false);
I am not getting any alert. Where am I going wrong? clk is the id of the clicked element
<input type="image" src="button.gif" id="clk" >
No need of using setTimeout. You can add dblclick event listener.
document.addEventListener("DOMContentLoaded", function (event) {
var clk_ch = document.getElementById('clk');
clk_ch.addEventListener('click', singleClick, false);
clk_ch.addEventListener('dblclick', doubleClick, false);
});
DEMO
In jquery:
$('#clk').on('click', singleClick).on('dblclick', doubleClick);
DEMO

Updating interval dynamically - jQuery or Javascript

I have two "stopwatches" in my code (and I may be adding more). This is the code I currently use below - and it works fine. But I'd really like to put the bulk of that code into a function so I'm not repeating the same code over and over.
When I tried doing it though, I could get it working - I think it was because I was passing stopwatchTimerId and stopwatch2TimerId into the function and it may have been passing by reference?
How can I reduce the amount of code repetition here?
var stopwatchTimerId = 0;
var stopwatch2TimerId = 0;
$('#stopwatch').click(function () {
if ($(this).hasClass('active')) {
$(this).removeClass('active');
clearInterval(stopwatchTimerId);
}
else {
$(this).addClass('active');
stopwatchTimerId = setInterval(function () {
var currentValue = parseInt($('#stopwatch-seconds').val()) || 0;
$('#stopwatch-seconds').val(currentValue + 1).change();
}, 1000);
}
});
$('#stopwatch2').click(function () {
if ($(this).hasClass('active')) {
$(this).removeClass('active');
clearInterval(stopwatch2TimerId);
}
else {
$(this).addClass('active');
stopwatch2TimerId = setInterval(function () {
var currentValue = parseInt($('#stopwatch2-seconds').val()) || 0;
$('#stopwatch2-seconds').val(currentValue + 1).change();
}, 1000);
}
});
As you can see, it's basically the same code in each except for stopwatchTimerId and $('#stopwatch-seconds') (and the same vars with 2 on it for the other one).
This won't pollute global scope and also you don't need to do any if-else statements. Just add data-selector to your new elements :)
<input id="stopwatch" type="text" data-selector="#stopwatch-seconds"/>
<input id="stopwatch2" type"text" data-selector="#stopwatch2-seconds"/>
$('#stopwatch stopwatch2').click(function () {
var $element = $(this),
interval = $element.data('interval');
selector = $element.data('selector');;
if ($element.hasClass('active')) {
$element.removeClass('active');
if (interval) {
clearInterval(interval);
}
}
else {
$element.addClass('active');
$element.data('interval', setInterval(function () {
var currentValue = parseInt($(selector).val()) || 0;
$(selector).val(currentValue + 1).change();
}, 1000));
}
});
function stopwatch(id){
$('#' + id).click(function () {
if ($(this).hasClass('active')) {
$(this).removeClass('active');
clearInterval(window[id]);
}
else {
$(this).addClass('active');
window[id] = setInterval(function () {
var currentValue = parseInt($('#' + id + '-seconds').val()) || 0;
$('#' + id + '-seconds').val(currentValue + 1).change();
}, 1000);
}
});
}
$(function(){
stopwatch("stopwatch");
stopwatch("stopwatch2");
});
You could do something like this (code is not very nice, you can improve it):
var stopwatchTimerId;
$('#stopwatch').click(function () {
doStopWatch(1);
});
$('#stopwatch2').click(function () {
doStopWatch(2);
});
var doStopWatch = function(option){
var stopWatch = option===1?$('#stopwatch'):$('#stopwatch2');
if (stopWatch.hasClass('active')) {
stopWatch.removeClass('active');
clearInterval(stopwatchTimerId);
}
else {
stopWatch.addClass('active');
stopwatchTimerId = setInterval(function () {
var currentValue = option===1?(parseInt($('#stopwatch-seconds').val()) || 0):(parseInt($('#stopwatch2-seconds').val()) || 0);
if(option===1)
$('#stopwatch-seconds').val(currentValue + 1).change();
else
$('#stopwatch2-seconds').val(currentValue + 1).change();
}, 1000);
}
}
Try
var arr = $.map($("div[id^=stopwatch]"), function(el, index) {
el.onclick = watch;
return 0
});
function watch(e) {
var id = this.id;
var n = Number(id.split(/-/)[1]);
if ($(this).hasClass("active")) {
$(this).removeClass("active");
clearInterval(arr[n]);
} else {
$(this).addClass("active");
arr[n] = setInterval(function() {
var currentValue = parseInt($("#" + id + "-seconds").val()) || 0;
$("#" + id + "-seconds").val(currentValue + 1).change();
}, 1000);
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="stopwatch-0">stopwatch1</div>
<input type="text" id="stopwatch-0-seconds" />
<div id="stopwatch-1">stopwatch2</div>
<input type="text" id="stopwatch-1-seconds" />

How to make expand all/collapse all button in this certain script?

i would like to ask for help in a simple task i really need to do at my work (I am a javascript newbie). I made a simple collapsible list with script provided by this guy http://code.stephenmorley.org/javascript/collapsible-lists/ but what i need right now are two simple buttons as stated in the title: expand all and collapse whole list. Do you guys know if something like that can be implemented in this certain script? Please help :)
var CollapsibleLists = new function () {
this.apply = function (_1) {
var _2 = document.getElementsByTagName("ul");
for (var _3 = 0; _3 < _2.length; _3++) {
if (_2[_3].className.match(/(^| )collapsibleList( |$)/)) {
this.applyTo(_2[_3], true);
if (!_1) {
var _4 = _2[_3].getElementsByTagName("ul");
for (var _5 = 0; _5 < _4.length; _5++) {
_4[_5].className += " collapsibleList";
}
}
}
}
};
this.applyTo = function (_6, _7) {
var _8 = _6.getElementsByTagName("li");
for (var _9 = 0; _9 < _8.length; _9++) {
if (!_7 || _6 == _8[_9].parentNode) {
if (_8[_9].addEventListener) {
_8[_9].addEventListener("mousedown", function (e) {
e.preventDefault();
}, false);
} else {
_8[_9].attachEvent("onselectstart", function () {
event.returnValue = false;
});
}
if (_8[_9].addEventListener) {
_8[_9].addEventListener("click", _a(_8[_9]), false);
} else {
_8[_9].attachEvent("onclick", _a(_8[_9]));
}
_b(_8[_9]);
}
}
};
function _a(_c) {
return function (e) {
if (!e) {
e = window.event;
}
var _d = (e.target ? e.target : e.srcElement);
while (_d.nodeName != "LI") {
_d = _d.parentNode;
}
if (_d == _c) {
_b(_c);
}
};
};
function _b(_e) {
var _f = _e.className.match(/(^| )collapsibleListClosed( |$)/);
var uls = _e.getElementsByTagName("ul");
for (var _10 = 0; _10 < uls.length; _10++) {
var li = uls[_10];
while (li.nodeName != "LI") {
li = li.parentNode;
}
if (li == _e) {
uls[_10].style.display = (_f ? "block" : "none");
}
}
_e.className = _e.className.replace(/(^| )collapsibleList(Open|Closed)( |$)/, "");
if (uls.length > 0) {
_e.className += " collapsibleList" + (_f ? "Open" : "Closed");
}
};
}();
It is important to understand why a post-order traversal is used. If you were to just iterate through from the first collapsible list li, it's 'children' may (will) change when expanded/collapsed, causing them to be undefined when you go to click() them.
In your .html
<head>
...
<script>
function listExpansion() {
var element = document.getElementById('listHeader');
if (element.innerText == 'Expand All') {
element.innerHTML = 'Collapse All';
CollapsibleLists.collapse(false);
} else {
element.innerHTML = 'Expand All';
CollapsibleLists.collapse(true);
}
}
</script>
...
</head>
<body>
<div class="header" id="listHeader" onClick="listExpansion()">Expand All</div>
<div class="content">
<ul class="collapsibleList" id="hubList"></ul>
</div>
</body>
In your collapsibleLists.js
var CollapsibleLists =
new function(){
...
// Post-order traversal of the collapsible list(s)
// if collapse is true, then all list items implode, else they explode.
this.collapse = function(collapse){
// find all elements with class collapsibleList(Open|Closed) and click them
var elements = document.getElementsByClassName('collapsibleList' + (collapse ? 'Open' : 'Closed'));
for (var i = elements.length; i--;) {
elements[i].click();
}
};
...
}();

Categories