If I click on the first "Edit" I get a console.log('click happend') But if I add a one of these boxes via javascript (click on "Add box") and then the Edit click from this new box does not work. I know it's because the javascript run when the element was not there and that's why there is no click event listener. I also know with jQuery I could do like so:
$('body').on('click', '.edit', function(){ // do whatever };
and that would work.
But how can I do this with plain Javascript? I couldn't find any helpful resource. Created a simple example which I would like to be working. What is the best way to solve this?
So the problem is: If you add a box and then click on "Edit" nothing happens.
var XXX = {};
XXX.ClickMe = function(element){
this.element = element;
onClick = function() {
console.log('click happend');
};
this.element.addEventListener('click', onClick.bind(this));
};
[...document.querySelectorAll('.edit')].forEach(
function (element, index) {
new XXX.ClickMe(element);
}
);
XXX.PrototypeTemplate = function(element) {
this.element = element;
var tmpl = this.element.getAttribute('data-prototype');
addBox = function() {
this.element.insertAdjacentHTML('beforebegin', tmpl);
};
this.element.addEventListener('click', addBox.bind(this));
};
[...document.querySelectorAll('[data-prototype]')].forEach(
function (element, index) {
new XXX.PrototypeTemplate(element);
}
);
[data-prototype] {
cursor: pointer;
}
<div class="box"><a class="edit" href="#">Edit</a></div>
<span data-prototype="<div class="box"><a class="edit" href="#">Edit</a></div>">Add box</span>
JSFiddle here
This Q/A is useful information but it does not answer my question on how to solve the problem. Like how can I invoke the eventListener(s) like new XXX.ClickMe(element); for those elements inserted dynamically into DOM?
Here's a method that mimics $('body').on('click', '.edit', function () { ... }):
document.body.addEventListener('click', function (event) {
if (event.target.classList.contains('edit')) {
...
}
})
Working that into your example (which I'll modify a little):
var XXX = {
refs: new WeakMap(),
ClickMe: class {
static get (element) {
// if no instance created
if (!XXX.refs.has(element)) {
console.log('created instance')
// create instance
XXX.refs.set(element, new XXX.ClickMe(element))
} else {
console.log('using cached instance')
}
// return weakly referenced instance
return XXX.refs.get(element)
}
constructor (element) {
this.element = element
}
onClick (event) {
console.log('click happened')
}
},
PrototypeTemplate: class {
constructor (element) {
this.element = element
var templateSelector = this.element.getAttribute('data-template')
var templateElement = document.querySelector(templateSelector)
// use .content.clone() to access copy fragment inside of <template>
// using template API properly, but .innerHTML would be more compatible
this.template = templateElement.innerHTML
this.element.addEventListener('click', this.addBox.bind(this))
}
addBox () {
this.element.insertAdjacentHTML('beforeBegin', this.template, this.element)
}
}
}
Array.from(document.querySelectorAll('[data-template]')).forEach(function (element) {
// just insert the first one here
new XXX.PrototypeTemplate(element).addBox()
})
// event delegation instead of individual ClickMe() event listeners
document.body.addEventListener('click', function (event) {
if (event.target.classList.contains('edit')) {
console.log('delegated click')
// get ClickMe() instance for element, and create one if necessary
// then call its onClick() method using delegation
XXX.ClickMe.get(event.target).onClick(event)
}
})
[data-template] {
cursor: pointer;
}
/* compatibility */
template {
display: none;
}
<span data-template="#box-template">Add box</span>
<template id="box-template">
<div class="box">
<a class="edit" href="#">Edit</a>
</div>
</template>
This uses WeakMap() to hold weak references to each instance of ClickMe(), which allows the event delegation to efficiently delegate by only initializing one instance for each .edit element, and then referencing the already-created instance on future delegated clicks through the static method ClickMe.get(element).
The weak references allow instances of ClickMe() to be garbage collected if its element key is ever removed from the DOM and falls out-of-scope.
You can do something like this...
document.addEventListener('click',function(e){
if(e.target && e.target.className.split(" ")[0]== 'edit'){
new XXX.ClickMe(e.target);}
})
var XXX = {};
XXX.ClickMe = function(element) {
this.element = element;
this.element.addEventListener('click', onClick.bind(this));
};
XXX.PrototypeTemplate = function(element) {
this.element = element;
var tmpl = this.element.getAttribute('data-prototype');
addBox = function() {
this.element.insertAdjacentHTML('beforebegin', tmpl);
};
this.element.addEventListener('click', addBox.bind(this));
};
[...document.querySelectorAll('[data-prototype]')].forEach(
function(element, index) {
new XXX.PrototypeTemplate(element);
}
);
document.addEventListener('click', function(e) {
if (e.target && e.target.className.split(" ")[0] == 'edit') {
console.log('click happend');
}
})
[data-prototype] {
cursor: pointer;
}
<div class="box"><a class="edit" href="#">Edit</a></div>
<span data-prototype="<div class="box"><a class="edit" href="#">Edit</a></div>">Add box</span>
Do it like jQuery: have a parent element that controls the event delegation. In the following, I use document.body as the parent:
document.body.addEventListener('click', e => {
if (e.target.matches('.edit')) {
// do whatever
}
});
Working example:
var XXX = {};
XXX.PrototypeTemplate = function(element) {
this.element = element;
var tmpl = this.element.getAttribute('data-prototype');
addBox = function() {
this.element.insertAdjacentHTML('beforebegin', tmpl);
};
this.element.addEventListener('click', addBox.bind(this));
};
new XXX.PrototypeTemplate(document.querySelector('[data-prototype]'));
document.body.addEventListener('click', e => {
if (e.target.matches('.edit')) {
// do whatever
console.log('click happend');
}
});
[data-prototype] {
cursor: pointer;
}
<div class="box"><a class="edit" href="#">Edit</a></div>
<span data-prototype="<div class="box"><a class="edit" href="#">Edit</a></div>">Add box</span>
Take a look at what MDN says about Element.prototype.matches.
Thanks to all answering on the question, it is all helpfull information. What about the following:
Wrap all the functions needed inside a XXX.InitializeAllFunctions = function(wrap) {} and pass the document as the wrap on first page load. So it behaves like it did before. When inserting new DOM Elements just pass those also to this function before inserting into DOM. Works like a charm:
var XXX = {};
XXX.ClickMe = function(element){
this.element = element;
onClick = function() {
console.log('click happend');
};
this.element.addEventListener('click', onClick.bind(this));
};
XXX.PrototypeTemplate = function(element) {
this.element = element;
addBox = function() {
var tmpl = this.element.getAttribute('data-prototype');
var html = new DOMParser().parseFromString(tmpl, 'text/html');
XXX.InitializeAllFunctions(html); // Initialize here on all new HTML
// before inserting into DOM
this.element.parentNode.insertBefore(
html.body.childNodes[0],
this.element
);
};
this.element.addEventListener('click', addBox.bind(this));
};
XXX.InitializeAllFunctions = function(wrap) {
var wrap = wrap == null ? document : wrap;
[...wrap.querySelectorAll('[data-prototype]')].forEach(
function (element, index) {
new XXX.PrototypeTemplate(element);
}
);
[...wrap.querySelectorAll('.edit')].forEach(
function (element, index) {
new XXX.ClickMe(element);
}
);
};
XXX.InitializeAllFunctions(document);
[data-prototype] {
cursor: pointer;
}
<div class="box"><a class="edit" href="#">Edit</a></div>
<span data-prototype="<div class="box"><a class="edit" href="#">Edit</a></div>">Add box</span>
Related
I have button that creates a div on click. I want to return this created div when I click a button. But the following code actually returns this button.
var create = $('#create').on('click', function(e){
var content = $('<div class="foo"/>')
return content
})
var test = create.trigger('click')
console.log(test)
Result is:
init [div#create, context: document, selector: '#create']
Is this not possible to do this this way or am I missing something?
No, it is not possible. You can add a function which will be executed in your event handler to do something with the object you create in the listener:
var create = $('#create').on('click', function(e){
var content = $('<div class="foo"/>')
doSomething(content)
})
create.trigger('click')
function doSomething(test) {
console.log(test)
}
There is no other way and it is because the handler function assigned with .on() method is called when the browser triggers an event (or you use .trigger() method) and the return statement is used only to force calling event.stopPropagation() and event.preventDefault() methods (you have to return false in the handler or just assign false instead of a function as an event handler - check the documentation, section The event handler and its environment) and not to return any value when you trigger an event manually.
You can also use an external variable to store the data "generated" in your event handler:
const divs = []
var create = $('#create').on('click', function(e){
var content = $('<div class="foo"/>')
divs.push(content)
doSomething()
})
create.trigger('click')
function doSomething() {
console.dir(divs)
}
You're calling a variable ("create") which stores the event listener on the button. This is what it looks like:
var test = $('#create').on('click', function(e){
var content = $('<div class="foo"/>')
return content
}).trigger('click')
console.log(test)
This is the solution:
jQuery
var create = function() {
return $('<div class="foo"/>');
};
var createEl = $('#create');
createEl.on('click', function() {
console.log(create());
// <div class="foo"></div>
});
createEl.trigger("click");
JavaScript
var create = function() {
var el = document.createElement('div');
el.className = "foo";
// Add other attributes if you'd like
return el;
};
var createEl = document.querySelector('#create');
createEl.addEventListener("click", function() {
console.log(create());
// <div class="foo"></div>
});
createEl.click();
(jQuery) Live example
var create = function() {
return $('<div class="foo"/>');
};
var createEl = $('#create');
createEl.on('click', function() {
console.log(create());
// <div class="foo"></div>
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<button id="create">Create</button>
(JavaScript) Live example
var create = function() {
var el = document.createElement('div');
el.className = "foo";
// Add other attributes if you'd like
return el;
};
var createEl = document.querySelector('#create');
createEl.addEventListener("click", function() {
console.log(create());
// <div class="foo"></div>
});
createEl.trigger("click");
var create = function() {
var el = document.createElement('div');
el.className = "foo";
// Add other attributes if you'd like
return el;
};
var createEl = document.querySelector('#create');
createEl.addEventListener("click", function() {
console.log(create());
// <div class="foo"></div>
});
<button id="create">Create</button>
I've tried to simplify the code as much as possible. What I'm trying to do is implement a way to resize some elements. To do so, I create a <div class="resize-on"> (it's the orange colored one) and then if you click and hold your mouse down and move then some action should happen like so
var Ui = {};
Ui.Resizer = function (element) {
this.isResizing = false;
this.element = element;
this.resizer = document.createElement("div");
this.resizer.classList.add('resize-on');
var toWrap = this.element;
var parent = toWrap.parentNode;
var next = toWrap.nextSibling;
this.resizer.appendChild(toWrap);
parent.insertBefore(this.resizer, next);
this.resizer.onmousedown = function(event) {
this.isResizing = true;
console.log('onmousedown', this.isResizing);
}.bind(this);
document.querySelector("body").onmousemove = function(event) {
if(this.isResizing) {
console.log('onmousemove', this.isResizing);
}
}.bind(this);
document.querySelector("body").onmouseup = function(event) {
this.isResizing = false;
console.log('mouse up');
}.bind(this);
};
(function() {
Array.prototype.forEach.call(
document.querySelectorAll('.resizable'),
function (element) {
new Ui.Resizer(
element
);
}
);
})();
.resize-on {
background-color: orange;
}
<div class="wrap">
<div class="one">One</div>
<div class="two resizable">two</div>
<div class="three">three</div>
<div class="four">four</div>
<div class="five">five</div>
</div>
So this works fine.
Now the problem is if I have multiple resizable elements it does not work. It then only works on the "last" one (in this case <div class="four resizable">four</div>) Why is that?
The element <div class="two resizable">two</div> get's the mousedown but does not show the onmousemove anymore.
It's the exact same code as above. Just added the resizable class to another HTML element. I can't understand why this doesn't work. Can anyone shed some light on this? Also what do I have to change to get it to work?
var Ui = {};
Ui.Resizer = function (element) {
this.isResizing = false;
this.element = element;
this.resizer = document.createElement("div");
this.resizer.classList.add('resize-on');
var toWrap = this.element;
var parent = toWrap.parentNode;
var next = toWrap.nextSibling;
this.resizer.appendChild(toWrap);
parent.insertBefore(this.resizer, next);
this.resizer.onmousedown = function(event) {
this.isResizing = true;
console.log('onmousedown', this.isResizing);
}.bind(this);
document.querySelector("body").onmousemove = function(event) {
if(this.isResizing) {
console.log('onmousemove', this.isResizing);
}
}.bind(this);
document.querySelector("body").onmouseup = function(event) {
this.isResizing = false;
console.log('mouse up');
}.bind(this);
};
(function() {
Array.prototype.forEach.call(
document.querySelectorAll('.resizable'),
function (element) {
new Ui.Resizer(
element
);
}
);
})();
.resize-on {
background-color: orange;
}
<div class="wrap">
<div class="one">One</div>
<div class="two resizable">two</div>
<div class="three">three</div>
<div class="four resizable">four</div>
<div class="five">five</div>
</div>
Use addEventListener for the events. Using the property onmousemove and others on the body element is only going to allow you to add a single event listener, as the previous one is going to be overwritten, hence why only the last one done, in this case the one for "four", works.
document.querySelector("body").addEventListener("mousemove", function(event) {
this.isResizing = false;
console.log('mouse up');
}.bind(this);
Though you can make it so you only need to set a single listener with only a little modification.
Ui.Resizer = function(element){
//...other code
this.resizer.onmousedown = function(event) {
//Set a property on Ui for use to know which Resizer is active and
//access it in the body events.
Ui.active = this;
}.bind(this);
//...rest of code excluding body events (mousemove, mouseup)
};
document.body.addEventListener("mousemove",function(event){
if(Ui.active){
//if Ui.active is set, active will be the Resizer instance
//and therefore can access the element it was created for
//by using active.element
console.log("mousemove",Ui.active.element);
}
});
document.body.addEventListener("mouseup",function(event){
if(Ui.active){
console.log("mouseup",Ui.active.element);
//clear active
Ui.active = null;
}
});
Demo
var Ui = {};
Ui.Resizer = function(element) {
this.isResizing = false;
this.element = element;
this.resizer = document.createElement("div");
this.resizer.classList.add('resize-on');
var toWrap = this.element;
var parent = toWrap.parentNode;
var next = toWrap.nextSibling;
this.resizer.appendChild(toWrap);
parent.insertBefore(this.resizer, next);
this.resizer.onmousedown = function(event) {
//Set a property on Ui for use to know which Resizer is active and
//access it in the body events.
Ui.active = this;
}.bind(this);
};
document.body.addEventListener("mousemove", function(event) {
if (Ui.active) {
//if Ui.active is set, active will be the Resizer instance
//and therefore can access the element it was created for
//by using active.element
console.log("mousemove", Ui.active.element);
}
});
document.body.addEventListener("mouseup", function(event) {
if (Ui.active) {
console.log("mouseup", Ui.active.element);
//clear active
Ui.active = null;
}
});
(function() {
Array.prototype.forEach.call(
document.querySelectorAll('.resizable'),
function (element) {
new Ui.Resizer(
element
);
}
);
})();
.resize-on {
background-color: orange;
}
<div class="wrap">
<div class="one">One</div>
<div class="two resizable">two</div>
<div class="three">three</div>
<div class="four resizable">four</div>
<div class="five">five</div>
</div>
// The parent class
var Parent = function (jqueryElement) {
this.jqueryElement = jqueryElement;
};
Parent.prototype.attachClick = function () {
var that = this;
this.jqueryElement.click(function (e) {
e.preventDefault();
that.doClick($(this));
});
}
Parent.prototype.doClick = function ($element) {
console.info('click event from parent');
}
// First child class
var A = function(jqueryElement) {
var that = this;
Parent.call(this, jqueryElement);
// this is supposed to override the Parent's
this.doClick = function ($element) {
console.info('click event from A');
};
};
A.prototype = Object.create(Parent.prototype);
var test = new A($('.selector'));
test.attachClick();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="selector">Click me</button>
At this stage, I'm supposed to see the message "click event from A", but the weird thing is that I don't see any message as if the doClick method is never executed.
How do I override an inherited method (doClick) in the child class?
You forgot to execute a click. Your code is working. =)
I will only suggest to put your .doClick() method in A.prototype, so it will be shared by all A instances.
// The parent class
var Parent = function (jqueryElement) {
this.jqueryElement = jqueryElement;
};
Parent.prototype.attachClick = function () {
var that = this;
this.jqueryElement.click(function (e) {
e.preventDefault();
that.doClick($(this));
});
}
Parent.prototype.doClick = function ($element) {
console.info('click event from parent');
}
// First child class
var A = function(jqueryElement) {
var that = this;
Parent.call(this, jqueryElement);
};
A.prototype = Object.create(Parent.prototype);
// this is supposed to override the Parent's
A.prototype.doClick = function ($element) {
console.info('click event from A');
};
var test = new A($('.selector'));
test.attachClick();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="selector">Click me</button>
https://jsfiddle.net/ekw6vk43/
I am working on jstree checkbox plugin and I want to get the checked and unchecked state of the checkbox items. The changed.jstree event is not working in the _setEvents() method. But it is working fine when I add the event inside of _setTree() method. I need to get the event trigger in _setEvents() method.
This is the code I am using:
export default class Test {
constructor(container) {
this._tab = null;
this._container = container;
this._setEvents();
}
get tab() {
return this._tab;
}
show(data) {
this._data = data;
this._setTree();
return this;
}
_setEvents() {
const self = this;
$(document)
.on('click', '#js-image-container', () => {
$('#js-image-uploader').trigger('click');
});
$('#js-categories-container').on('changed.jstree', () => this._handleSelection());//this wont work
return this;
}
_setTree() {
$('#js-categories-container').jstree(jsonTreeGenerator.generate(this._data.categories));
$('#js-categories-container').on('changed.jstree', () => this._handleSelection()); //this will work
return this;
}
_handleSelection() {
alert(1);
}
}
Since you are adding the js-categories-container element dynamically, I believe it is not there yet at the time when you bind an event to it. So you have to delegate event handling, e.g. same way as you do for the js-image-container element. Check demo - Fiddle Demo:
$(document).on('click', '#js-image-container',
() => { $('#js-image-uploader').trigger('click'); }
);
$(document).on("click", '#js-categories-container',
() => {
// get the node if you need it
var node = $('#js-categories-container').jstree().get_node(event.target);
// do something
this._handleSelection();
}
);
I have been writing a plugin, and i really like this format
Function.prototype._onClick = function() {
// do something
}
Fuction.prototype.addListner = function() {
this.$element.on('click', this._onClick.bind(this));
}
the problem is sometimes i need the element being clicked and the main object. Doing as below i loose the dom element and not using bind looses the main object.
Fuction.prototype.addListner {
this.$element.find('.some-class').on('click', this._onClick.bind(this));
}
To achieve that i go back to ugly version
Fuction.prototype.addListner = function() {
var self = this;
this.$element.find('.some-class').on('click', function() {
self._onClick($(this));
});
}
Is there any better way to do this?
As zerkms, you can use the event.target to achieve what you want.
When using .on, the handler is :
handler
Type: Function( Event eventObject [, Anything extraParameter ] [, ...
] ) A function to execute when the event is triggered. The value false
is also allowed as a shorthand for a function that simply does return
false.
So your _onClick function will receive click event as its 1st parameter, then from event.target, you can now get the clicked item.
var Test = function(sel) {
this.$element = $(sel);
this.value = 'My value is ' + this.$element.data('val');
};
Test.prototype.addListner = function() {
this.$element.find('.some-class').on('click', this._onClick.bind(this));
}
Test.prototype._onClick = function(evt) {
// Get the target which is being clicked.
var $taget = $(evt.target);
//
console.log(this.value);
// use $target to get the clicke item.
console.log($taget.data('val'));
}
var test = new Test('#test');
test.addListner();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div id="test" data-val="divVal">
<button class="some-class" data-val="Button-A">btnA</button>
<button class="some-class" data-val="Button-B">btnB</button>
</div>