I am working on a mobile app, and I am currently using the on() method to implement a swipe-to-delete feature (I understand that there are libraries that would allow me to do this, and am open to any thoughts you have on the merits of different options). I have code that looks like this:
var favArticles = $('#favoritesList li');
favArticles.each(function(i, li){
var id = $(li).attr('id');
$(li).on("swipeLeft",function(){
//console.log('SwipeLeft ' + id);
var html = $(li).html();
var button = '<div ><button onclick="favDelete(id, i)">Delete</a></div>';
$(li).html('<div style="position:relative;">' + html + button + '</div>');
});
});
I am trying to manage a mutable list of articles that, so whenever I render the favorites list, I grab all the current articles, and bind a swipe event to them. If swiped, a button is brought up on top of the article, and when the user hits the button a function runs that removes the swiped li from the list, and deletes it from the stored favorites.
Within favDelete, I use the index i to remove() the correct li. This means that I need to recreate all the events with updated values of i each time an element is deleted.
So, my question: if I call on() again, for the same event on the same DOM element, will the old binding be overwritten? Or do I create a memory leak by constantly adding new on() actions to my list elements?
UPDATE: Yes, JQuery, not Javascript. Apologies. And I know that my favDelete call won't work as it is shown, I omitted chopped a bunch of quotation marks out for the post to try to improve readability.
I would just use two event handlers and event delegation: One for the swipe event and one for the click on the delete button.
I don't know if swipeLeft works with event delegation, but even if not, it would not change much:
$('#favoritesList').on('swipeLeft', 'li', function() {
// show delete button
// or $(this).html(...)
$(this).append('<div class="deleteButton"><button>Delete</a></div>');
}).on('click', '.deleteButton button', function() {
// find ancestor li element
var $li = $(this).closest('li');
// and pass it to favDelete
favDelete($li);
// if you don't remove the element in the favDelete, do it here:
$li.remove();
});
Using event delegation for the delete buttons makes the most sense, since you are "constantly" adding and removing them.
Learn more about event delegation.
All the styling you can do with a CSS rule for the deleteButton class. You'd also have to change your favDelete method to accept a li element (or rather a jQuery object with a li element) instead of an ID and index.
if I call on() again, for the same event on the same DOM element, will the old binding be overwritten?
.on() will always add a new event handler. In your code, you even create a new event handler function for every list element, which is indeed a waste of memory.
In my code above, there are only two event handlers for all li and button elements.
Two other ways you could do this, rather than a hard-coded index:
Use the ID to select the correct LI element (in your favDelete function)
Pass in a selector instead of the index (i.e. $(this).closest('li'))
If You'll call 'on' again, previous bindings will still be alive - for ex. If You'll call few times (let's say 5 times) on('click', function() { console.log('fired'); }. When You'll click one time on the object it'll thorw 'fired' five times.
Related
I'm trying to remove an already existing event listener from an object. I've tried several methods (using jQuery .off(), .unbind(), standard removeEventsListeners()), but as stated in the docs they can only remove previously added ones?
Using the Chrome debugger, I can see and remove the specified event listener,
Also, when trying to list the event listeners via jQuery _data() function, it won't list the event. Have been searching for an answer for a couple of hours now.
Can anyone help? Any workaround?
Edit: I have to keep some, so cloning is not possible.
If the event handler was added with addEventListener, you cannot remove it unless you have a reference to the handler function that was added. I assume that must be the case, because if it were hooked up with jQuery's on (or various shortcuts for it), off would work, and you've said it didn't work.
One way to work around that is to replace the element with a clone. When you clone an element using the DOM's cloneNode, you don't copy its event handlers. So if you start out with element, then you can clone it, use insertBefore to insert the clone, then use removeChild to remove the original:
var newElement = element.cloneNode(true); // true = deep
element.parentNode.insertBefore(newElement, element);
element.parentNode.removeChild(element);
Of course, this is indeed a workaround. The proper thing would be not to set up the handler in the first place, or keep a reference to it if you need to be able to remove it later.
In a comment you've said you can't do that, and asked:
Is there a way to add a new event listener that blocks the already existing one?
Only if you can get there first, otherwise no, you can't.
You can't add a new handler that blocks an existing one (not in a standard way cross-browser), but if you can add yours before the other one is added, you can prevent it being called by using stopImmediatePropagation:
// Your handler
document.getElementById("target").addEventListener("click", function(e) {
console.log("Your handler");
e.stopImmediatePropagation();
e.stopPropagation();
});
// The one that you're trying to prevent
document.getElementById("target").addEventListener("click", function(e) {
console.log("Handler you're trying to prevent");
});
<div id="target">Click me</div>
So for instance, if the other handler is added in the window load event, or a jQuery ready handler, you may be able to get yours in first by putting your code in a script tag immediately after the element in question.
A very easy way of doing this is to append nothing to the parent element with .innerHTML. Just be aware this destroys all event listeners that are descendants of the parent element. Here's an example (click 2 to destroy the event listener attached to 1):
const d1 = document.querySelector('#d1');
d1.addEventListener('click', () => console.log(123));
const d2 = document.querySelector('#d2');
d2.addEventListener('click', () => d1.parentNode.innerHTML += '');
<div><button id="d1">1</button></div>
<div><button id="d2">2</button></div>
Problem Fiddle:
Click To View (Attempt #1, using Delegated Events)
Click To View (Attempt #2, brute force approach as below)
Click To View (Attempt #3, refactored, has problem I am trying to solve)
On a project I'm working with, I'm exploring a rather dynamic form. In addition to some static elements, there are various interactive elements, which can be cloned from a hidden 'template' markup set and added at various points in the business process.
Because of the dynamic nature, my tried-and-true method of setting up a jQuery element cache and event handlers on-load, then letting the user do whatever isn't working out, because of this dynamic nature; I was finding that my dynamically-added elements had no click events.
To solve this problem, I manually set up a rebind method for each scripted element in question. The rebind process involves A) re-acquiring the set of elements for a given descriptive selector, B) dropping any existing events on that cache, as those events apply to an incomplete element set, and C) calling a bind method to apply the new events to the entire set.
The brute-force, working way that I got, had this going on:
var $elementCache = $('.some-class');
function rebindSomeLink() {
// Re-acquire the element cache...
$elementCache = $('.some-class');
// Drop all existing events on the cache...
$elementCache.unbind();
// Call a bind function to establish new events.
bindSomeLink();
}
function bindSomeLink() {
$elementCache.click(function (e) {
// ...Behavior...
});
}
// There are four other links with a similar rebind/bind function relationship set up.
Naturally, I seized on the rebind being repeated so often with nearly the exact same code - ripe for a refactor. We have a common library namespace, where I added a rebindEvents function...
var MyCommon = function () {
var pub = {};
pub.rebindEvents = function($elementCache, selector, bindFunction) {
$elementCache = $(selector);
$elementCache.unbind();
bindFunction();
};
return pub;
}();
Upon trying to call that, and run the site, I immediately stubbed my toe on an UncaughtTypeError: method click cannot be called on object undefined.
As it turns out, it seems when I call the following:
MyCommon.rebindEvents($elementCache, '.some-class', bindSomeLink);
The $elementCache is not being passed to the rebindEvents method; when I step to it in my debugger, $elementCache inside of rebindEvents is undefined.
Some handy StackOverflow research revealed to me that JavaScript does not have referential-passing, at least in the C/C++/C# sense that I am familiar with, which leads me to my two Questions:
A) Is it even possible for me to refactor this rebind functionality with a cache reference pass of some sort?
B) If it's possible for me to refactor my rebind function to my common namespace, how would I go about doing it?
Use Jquery On to bind events at an element high-up in the DOM that is always present.
http://api.jquery.com/on/
This is the simplest way to handle event binding to dynamically created elements.
here is a jsfiddle that shows an example.
$('#temp').on('click', 'button', function(){
alert('clicked');
});
$('#temp').append('<button>OK</button>');
The event is bound to a div, which later has a button dynamically added. Because the button has no click event, the event "bubbles" up the DOM tree to its parent element which does have a click event for a button, so it handles it and the event "bubbles" no further.
I am unsure as to how to approach this problem.
I have some buttons made in the HTML with some data attributes added to them. These buttons have a class called roleBtn which will call my jQuery roleBtnClicked function and grab the variables in the HTML's data attributes.
$(".roleBtn").click(roleBtnClicked);
function roleBtnClicked(event){
reg.roleName = $(this).html(); /* Get role name: Actor */
reg.blueBtn = $(this).data('blue'); /* Get blue-btn-1 */
reg.the_Num = $(this).data('num'); /* Get the number */
reg.modal_ID = $(this).data('modal'); /* Get modal-1 */
Now using this information, after the roleBtn is clicked a modal window will come up, I then have a doneButton which will close the modal window and use the variables from the data attributes to then generate new HTML on the fly. This new HTML will contain a button with the class of blueBtn.
My problem is that my click function for blueBtn won't work on a blue button that was created on the fly. It will work on a div that already has the class blueBtn before hand, but doesn't work if it was created on the fly.
Do you know a workaround to this? Or am I missing something simple?
After the doneButton is clicked I have another function that creates the new HTML including the blueBtns on the fly:
$('.selected_row .choices-col-left').append('<div class="blueBtn-holder" id="blueBtnHolder-'+theNum+'"><div class="blueBtn" id="'+blueBtn+'" row="'+rowName+'" modal="'+modal_ID+'" num="'+theNum+'">'+roleName+'</div></div>');
My blue button click function which doesn't work
$(".blueBtn").click(blueBtnClicked);
function blueBtnClicked(event){
alert("Where are you blueBtn on the fly?");
console.log("Where are you blueBtn on the fly?");
};
Try this:-
You need Event delegation for dynamically created elements using .on()
$(".selected_row").on('click', '.blueBtn', blueBtnClicked);
function blueBtnClicked(event){
alert("Where are you blueBtn on the fly?");
console.log("Where are you blueBtn on the fly?");
};
Demo
When you just bind a click event, it will be only bound to the existing DOM elements, so you want to bind the event to the parent element and later any elements you add with the same selector with that container will have the event available by delegation.
From Jquery Docs
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.
That's because you have to reassign event handlers for newly created items.
A better approach would be using .on on the container object, and then specify the child objects that should respond to the clicks:
$(".container").on('click', '.blueBtn', blueBtnClicked);
This way even if you ad objects on the fly, they will still respond. This is actually a lot more efficient way of handling that, because you only create one event handler as oppose to many. This is actually called event delegation.
Remember that when you do $(selector).click, you're telling jQuery to find all elements matching selector and assign the specific "click handler" to them. This does not happen again when you create new objects, because you're not telling jQuery to handle every future object as well (jQuery will not be aware of you adding a new button and will not assign a handler to it).
I need some help with the callbacks. For some reason, they don't work really well.
I'm making a game with jQuery. I have a <div id='button'></div> for all the buttons that are going to be in the game. The game is going to have two buttons that make actions, and a question on top of it. The question is controlled by a <h3 id='text'></h3>. What I want to know, is that for some reason I can't set callback functions to the button's ID's. In example,
I'd have the yes or no, that have their own id's set through jQuery like this:
$('#button').html('<button id='yes'>Yes</button><button id='no'></button>');
But for some reason, I would be able to set this:
$('yes').click(function(){
//function I would want
});
Of course, that's not what my code has, that was just an example. Here's the real code:
$(document).ready(function(){
$('#main,#batman,#car,#cop,#hobo,#knife,#gangfight,#ganggun,#gangknife,#blood,#hr').hide(-100);
var hr=$('#hr');
var main=$('#main');
var batman=$('#batman');
var car=$('#car');
var hobo=$('#hobo');
var cop=$('#cop');
var knife=$('#knife');
var gangfight=$('#gangfight');
var ganggun=$('#ganggun');
var gangknife=$('#gangknife');
var blood=$('#blood');
var text=$('#text');
var button=$('#button');
$('#start').html('Are you ready to play?');
$('#button').html('<button id="yes">Yes</button><button id="no">No</button>');
$('#yes').click(function(){
$('#yes,#no').hide(function(){
$('#start').hide();
main.fadeIn(-100);
hr.fadeIn(-100,function(){
text.delay(1000).html("You were just wandering around in the streets of new york, when suddenly.. You see batman!! You've never really liked him, what do you do?")
button.html('<button id="fight">Fight</button><button id="leave">Leave</button>',function(){
batman.fadeIn(1000);
$('fight').click(function(){
});
$('leave').click(function(){
text.fadeOut(function(){
text.text('Good call. As you leave, you encounter a hobo. What do you do?');
});
});
});
});
});
});
$('#no').click(function(){
$('#yes,#no').hide();
$('#start').text('Oh, okay then. Come back later!');
});
});
I'm just wondering.. How can I set callback functions to the 'fight' and 'leave'.
If you're wondering why there's all these variables at the start, those are just the images and characters.
You can't set a click handler on an element that doesn't exist. What you should do is use .on to bind a element further up the tree. Something like:
$("#someparentelement").on("click", "#yes", function() {
// your code
});
Which version of jQuery are you using? You should probably use jQuery.on() in this situation since your click handler code probably gets executed before the button is actually available in the DOM.
$("#button").on("click", "#yes", function (event) {
// Your yes-button logic comes here.
});
For more details and possibilities, read about the .on(events [, selector ] [, data ], handler(eventObject)) method in the jQuery documentation:
If selector is omitted or is null, the event handler is referred to as direct or directly-bound. The handler is called every time an event occurs on the selected elements, whether it occurs directly on the element or bubbles from a descendant (inner) element.
When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.
In this case, you want to delegate the event since your element is not yet available in the DOM when you're binding the event.
Don't use the click(), use on('click') and attach it to the document.
Creating a handler this way, will ensure that any new elements will be able to trigger the event.
$('fight') selects fight tag, not the tag with fight id. Try to use $('#fight') instead.
Im trying to remove a row. But i can't figure it out really.
First of all I've got a button that'll add a new row, that works.
But I want to give the user the possibility to remove the just added row.
The row has an 'div' inside what acts as an deletebutton. But the deletebutton doesn't work?
I'm I missing something?
Greet,
Juki
function addrow() {
$("#container").append("<div id=\"row_added\"><div class=\"deletebutton\" id=\"delbuttonnumber\"></div><div id=\"addedcolor\" class=\"colorcube\"></div></div>");
}
// deleterow the row
$(".deletebutton").click(function() {
rowclrid = "#" + $(this).parent().attr("id");
$(rowclrid).remove();
});
My guess is that you have assigned the click handler before adding the new content, so the handler is not attached to this particular element. You can use .delegate() to listen for events on all elements below a particular parent element, whether or not they already exist:
$('#container').delegate('.deletebutton', 'click', function(){
$(this).parent().remove();
});
This listens for all click events that happen inside the element #container using a feature of the DOM called event bubbling, then checks to see if they happened on a .deletebutton element, and, if so, calls the handler.
Note also the simplified code inside the handler.
I think what you need to do is use the live method. This will add the events for any new item that is added to the DOM, not just the ones that exist when you set the click handler.
// deleterow the row
$(".deletebutton").live('click', function() {
$(this).parent().remove();
});
You also don't need to get the row by getting the ID - it's simpler in the way above.