Can I iterate through for loop to create more javascript? - javascript

I need to have multiple .click() functions populated on page load, based on how many image records are stored within a mysql database.
so far i have a page that will nicely switch between photos with a <ul> of image buttons
but i have to hand write the jquery that deals with it.
is there a way that i can populate a .js file with the correct amount of .click() functions based on the amount of records on in the data base.

In addition to Alex's answer, if you want to set the click event of elements that don't exist yet or haven't been added to the page, you could do:
$(body).on('click','a.record',function(){
//any existing or future a element with class record will have this click function
});

Instead of adding a separate onclick handler to each element, you should use event delegation and attach a single event handler to some container. Said event handles would catch all the onclick events , as the bubble up through DOM.

You don't need to write a click() for each unique element.
Instead, you could select a bunch of elements with a selector, such as $('a.record') and then chain click() to that...
$('a.record').click(function() {
// Any `a` element with a class of `record` was clicked.
});
The disadvantage of doing it this way is you add a bunch of event listeners and it won't be triggered for future elements.
As others have mentioned, event delegation using on() (if using a newer jQuery) or delegate() (if using an older) is the best, as it only attaches one event listener and will work with future elements added after the event is attached.
$(document).on('click', 'a.record', function() {
// Any `a` element with a class of `record` was clicked, now or in the future.
});
I've used document here, but you should use the nearest ancestor which won't change, which may be the ul element you have described.

Related

How to use jQuery filter function with event delegation?

I need to bind the change of all the textboxes(having class .box) under Box2 column who have the blue button(having class .blue which is dynamic in some cases) in their row.
Below is the screenshot of the HTML I have which is just a HTML table which has 3 columns(Box1,Box2 & for the button):
Class .blue could be present on some buttons on the page load & also could be removed/added to the buttons as result of another Ajax operation.
jQuery .on() has
.on( events [, selector ] [, data ], handler )
is it possible to use .filter() in the selector part where I can use a function like
jQuery('.box').filter(function(){
return jQuery(this).closest('tr').find('.blue').length
});
to filter out the needed textboxes & then bind there change event?
Considering the #parent is the parent div of the HTML I was trying
jQuery('#parent').on('change','.box',..); but this will listen to the change of all the box2 elements whereas I want it to listen to the specific ones only.
Ideas please?
Thanks.
In event delegation, we are binding events on the parent element and listening events on it based on the target(selector). The only thing we are certain about is the specific-selector of the target-element. Well, in the cases link specific-child or specific-sibling of the dynamically appended element, doing things in the handler(callback) is the only way!
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.
Note: Attaching many delegated event handlers near the top of the document tree can degrade performance. Each time the event occurs, jQuery must compare all selectors of all attached events of that type to every element in the path from the event target up to the top of the document. For best performance, attach delegated events at a document location as close as possible to the target elements. Avoid excessive use of document or document.body for delegated events on large documents. [Reference]
use a if to test if the button(.box) has a blue class
$('.parent').on('change','.box2 input',function(){
if($(this).closest('tr').find('.box').is('.blue')) {
//do code here
}
});
Include a separate check for the button. Without any code it's not possible to give you the correct code
jQuery('#parent').on('change','.box',..);
if ($(this).next().hasClass('blue')) {
// Do other stuff
}

Which is better: using onclick or find element that triggered the event for handling events in jQuery?

I always wondered which is the better way of handling events in terms of code manageability, cleanliness and code reuse.
If you use the former then say a list of 10 anchor tags with click handler will have something like:
Click Me
Click Me
Click Me
... 10 times
which looks kind of odd.
With the latter method, using anonymous function, it'd be like:
$('a').on('click', function(e){});
At the end of the day, every event is bound to some element in the DOM. In the case of .bind, you're binding directly to the element (or elements) in your jQuery object. If, for example, your jQuery object contained 100 elements, you'd be binding 100 event listeners.
In the case of .live, .delegate, and .on, a single event listener is bound, generally on one of the topmost nodes in the DOM tree: document, document.documentElement (the element), or document.body.
Because DOM events bubble up through the tree, an event handler attached to the body element can actually receive click events originating from any element on the page. So, rather than binding 100 events you could bind just one.
For a small number of elements (fewer than five, say), binding the event handlers directly is likely to be faster (although performance is unlikely to be an issue). For a larger number of elements, always use .on.
The other advantage of .on is that if you add elements to the DOM you don't need to worry about binding event handlers to these new elements. Take, for example, an HTML list:
<ul id="todo">
<li>buy milk</li>
<li>arrange haircut</li>
<li>pay credit card bill</li>
</ul>
Next, some jQuery:
// Remove the todo item when clicked.
$('#todo').children().click(function () {
$(this).remove()
})
Now, what if we add a todo?
$('#todo').append('<li>answer all the questions on SO</li>')
Clicking this todo item will not remove it from the list, since it doesn't have any event handlers bound. If instead we'd used .on, the new item would work without any extra effort on our part. Here's how the .on version would look:
$('#todo').on('click', 'li', function (event) {
$(event.target).remove()
})
Second method is preferrable, since we should not be mixing our JavaScript with the HTML. (Separation of Concerns) . This way your code is kept clean.
This also works well with dynamically inserted HTML code.
`$('a').on('click', function(e){});` // Using jQuery.
Using Vanilla JS:
document.getElementById("idName").addEventListener("click", function(){}); // Bind events to specific element.
document.addEventListener("click", function(){}); // Bind events to the document. Take care to handle event bubbling all the way upto the document level.

Cloned element on click not working Javascript

I have some javascript that successfully clones a template and appends the resulting html to a div. However when I try to reference an element of the clone it is not accessible, even though if I place the exact same element with the exact same ID (confirmed with Firebug) outside the template (and the cloning system) it is accessible. I believe I need to do an update of some kind after cloning but I am not sure. The code I am trying to use to access the (cloned) element (does not log anything to console and is not working) is:
$("#depminusbutton0").on("click", function () {
console.log('I triggered minus 0');
});
And depminusbutton0 shows up like this in firebug inspect element once cloned (doesn't exist prior to cloning, as ID 0 is inserted dynamically:
<a id="depminusbutton0">
Any ideas how I can make this element accessible?
Two possibilities I can think of:
You are installing the event handler before the element exists so it can't find the element to attach the event handler to?
You have a conflicting ID elsewhere in the document.
If you're going to use this form of event handling:
$("#depminusbutton0").on("click", fn);
Then, the #depminusbutton0 element must exist at the time you run that line of code. It will search the DOM for that element at the time you run the code and will not hook up to an element that matches that ID that you create in the future.
You can work around that issue, either by running that line of code AFTER you create the #depminusbutton0 element and insert it in the DOM or you can switch to use delegated event handling which attaches the event handler to a common parent that does exist before you've created the child element.
To see more about how delegated event handling works, see these references:
jQuery .live() vs .on() method for adding a click event after loading dynamic html
Does jQuery.on() work for elements that are added after the event handler is created?
The general idea would be like this:
$(some parent selector).on("click", "#depminusbutton0", fn);
If you have multiple elements with the #depminusbutton0 id, then you will have to fix that and only have one element with that id. Often times with clones, you want to use a class name rather than an id since you can have multiple elements with the same class name.
Are you attaching the event to an element that doesn't exist yet? As described in the jQuery documentation:
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().
Just make sure you are attaching the event to the cloned element after you create it.
$(document).on('click', '.class-or-id-name', function() {
console.log("Heyyy its clickable");
// do more stuff
});

jQuery event delegation and attachment issue

I have a set of three elements. And there are many coming elements after the page load by ajax when the user clicks on a certain element. I iterate over initial elements with each and attach an event to them like this:
tagSet.each(function(index, element){
tagSet.eq(index).on("click",function(){alert("Alerted! Clicked")});
}
But with this approach those ajax-created elements would not be attached with an event. Thus I have to make a little bit of change to on() for it accommodate the ajax-created elements:
tagSet.each(function(index, element){
$(document).on("click",tagSet.eq(index),function(){alert("Alerted! Clicked")});
}
It solve the problem of event attachment to those ajax-created elements but raises another issue. It attaches the event in a way that all of the elements of the page gets trigged with that specific event at once. I mean, since I have three elements, a click on one of them cause all three alert("Alerted!Clicke!) to trigger. What is the issue and the solution?
Use event delegation to bind to all current and future items that match a query:
$(document).on("click", ".some-class-here", function(){
alert("Alerted! Clicked")
});
Replace .some-class-here with a selector that matches your tagSet elements. Then remove your call to $.each.

How do I register a Javascript event handler to an element that hasn't been added to the page yet

I'm trying to build a greasemonkey script which will dynamically create tables of data based on user interaction with... other dynamically created tables of data. My problem is that I'm having to make two passes every time I create a table: one to create the table, and another to go grab all of the objects in the table I want to add event handlers to (by id) and add the various event handlers to them.
If I attempt to, say, add an onClick event to a table td before I've created the table and inserted it into the HTML, I get a "component is not available" exception.
This is incredibly cumbersome, because I either have to maintain, separately, a list of the ids and what I should do to those elements when I make my second pass to add the handlers, or develop a naming convention by which I know, based on the id, what I should do with the element.
There HAS to be a better way to do this. I just haven't figured it out yet. Anyone have any ideas?
Firstly, I'd love to know why you need a different ID for every single TD. Is the ID holding important information, such as an index? In this situation it might be better creating each TD within a loop. Also, obviously you can't attach an event handler to a DOM element which doesn't exist! It doesn't have to be injected into the DOM but it DOES have to exist in some capacity.
jQuery's live() isn't a magical mystery, it just uses event delegation, so it attaches the event to a parent element, such as the table and then decides what happens dependent on the target of the click. Here's a rudimentary example. I register a handler to the 'body' element, and then I test each time to see what the target is, if it's a TD element I doSomething() ->
document.body.onclick = function(e) {
var realTarget = e ? e.target : window.event.srcElement;
if ( realTarget.nodeName.toLowerCase() === 'td' ) {
doSomething();
}
};
Event delegation relies on something called event bubbling (or "propogation") which is the way in which modern browsers implement the event model. Each event, when triggered will travel upwards through the DOM until it can go no further. So if you click on an anchor within a paragraph the anchor's 'click' event will fire and THEN the paragraph's 'click' event will fire etc. etc.
jQuery 1.3+ has a new live() function that can set up event handlers for elements that don't exist yet .. check it out
You have to wait for the element to be added to the page, then add the event handler then.
There is no easy way to say "add this to all elements of this type, now and in the future".
It is possible to have a timer periodically check the page for new elements, applying a queue of events (or other properties) to them as they appear, all behind the scenes. This can be abstracted out and re-used, for example Jquery can do that sort of thing.
As JimmyP pointed out, your problem can easily be solved using event bubbling. You might consider writing a wrapper function to work around browser inconsistencies - my own version can be found here and would be used like this:
capture('click', '#element-id', function(event) {
// `this` will be the originating element
// return `false` to prevent default action
});

Categories