jQuery Event Binding is applied to whole body - javascript

I'm trying to add a some event functions to dynamically generated elements on a page.
I've used the Event delegation as follows.
//For Static Element
$(".get_flickr_image").click(function(){
getFlickrImages();
});
// For Dynamic Element
$(document).on("click", $(".get_more_flickr_image"), function(){
getFlickrImages();
});
But for some reason, the second function is called whenever I click anywhere on the document. Am I doing it wrong?

You should use
// For Dynamic Element
$(document).on("click",".get_more_flickr_image", function(){
getFlickrImages();
});
You're not passing the selector correctly.

on() does not have an overload for passing jQuery objects. Pass the selector as a string instead
$(document).on("click", ".get_more_flickr_image", function(){
getFlickrImages();
});

Related

Click event on appended content in some cases not working [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 8 years ago.
Suppose I have some jQuery code that attaches an event handler to all elements with class .myclass.
For example:
$(function(){
$(".myclass").click( function() {
// do something
});
});
And my HTML might be as follows:
<a class="myclass" href="#">test1</a>
<a class="myclass" href="#">test2</a>
<a class="myclass" href="#">test3</a>
That works with no problem.
However, consider if the .myclass elements were written to the page at some future time.
For example:
<a id="anchor1" href="#">create link dynamically</a>
<script type="text/javascript">
$(function(){
$("#anchor1").click( function() {
$("#anchor1").append('<a class="myclass" href="#">test4</a>');
});
});
</script>
In this case, the test4 link is created when a user clicks on a#anchor1.
The test4 link does not have the click() handler associated with it, even though it has class="myclass".
Basically, I would like to write the click() handler once and have it apply to both content present at page load, and content brought in later via AJAX / DHTML. Any idea how I can fix this?
I am adding a new answer to reflect changes in later jQuery releases. The .live() method is deprecated as of jQuery 1.7.
From http://api.jquery.com/live/
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().
For jQuery 1.7+ you can attach an event handler to a parent element using .on(), and pass the a selector combined with 'myclass' as an argument.
See http://api.jquery.com/on/
So instead of...
$(".myclass").click( function() {
// do something
});
You can write...
$('body').on('click', 'a.myclass', function() {
// do something
});
This will work for all a tags with 'myclass' in the body, whether already present or dynamically added later.
The body tag is used here as the example had no closer static surrounding tag, but any parent tag that exists when the .on method call occurs will work. For instance a ul tag for a list which will have dynamic elements added would look like this:
$('ul').on('click', 'li', function() {
alert( $(this).text() );
});
As long as the ul tag exists this will work (no li elements need exist yet).
Sometimes doing this (the top-voted answer) is not always enough:
$('body').on('click', 'a.myclass', function() {
// do something
});
This can be an issue because of the order event handlers are fired. If you find yourself doing this, but it is causing issues because of the order in which it is handled.. You can always wrap that into a function, that when called "refreshes" the listener.
For example:
function RefreshSomeEventListener() {
// Remove handler from existing elements
$("#wrapper .specific-selector").off();
// Re-add event handler for all matching elements
$("#wrapper .specific-selector").on("click", function() {
// Handle event.
}
}
Because it is a function, whenever I set up my listener this way, I typically call it on document ready:
$(document).ready(function() {
// Other ready commands / code
// Call our function to setup initial listening
RefreshSomeEventListener();
});
Then, whenever you add some dynamically added element, call that method again:
function SomeMethodThatAddsElement() {
// Some code / AJAX / whatever.. Adding element dynamically
// Refresh our listener, so the new element is taken into account
RefreshSomeEventListener();
}
Hopefully this helps!
Regards,
After jQuery 1.7 the preferred methods are .on() and .off()
Sean's answer shows an example.
Now Deprecated:
Use the jQuery functions .live() and .die(). Available in
jQuery 1.3.x
From the docs:
To display each paragraph's text in an
alert box whenever it is clicked:
$("p").live("click", function(){
alert( $(this).text() );
});
Also, the livequery plugin does this and has support for more events.
If you're adding a pile of anchors to the DOM, look into event delegation instead.
Here's a simple example:
$('#somecontainer').click(function(e) {
var $target = $(e.target);
if ($target.hasClass("myclass")) {
// do something
}
});
You can bind a single click event to a page for all elements, no matter if they are already on that page or if they will arrive at some future time, like that:
$(document).bind('click', function (e) {
var target = $(e.target);
if (target.is('.myclass')) {
e.preventDefault(); // if you want to cancel the event flow
// do something
} else if (target.is('.myotherclass')) {
e.preventDefault();
// do something else
}
});
Been using it for a while. Works like a charm.
In jQuery 1.7 and later, it is recommended to use .on() in place of bind or any other event delegation method, but .bind() still works.
Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events.
link text
$(function(){
$(".myclass").live("click", function() {
// do something
});
});
If your on jQuery 1.3+ then use .live()
Binds a handler to an event (like
click) for all current - and future -
matched element. Can also bind custom
events.
You want to use the live() function. See the docs.
For example:
$("#anchor1").live("click", function() {
$("#anchor1").append('<a class="myclass" href="#">test4</a>');
});

Javascript, Jquery ,DOM

After appending a button on Html document the jQuery event associated with it not working ?
For example:
$("#mydiv").append('X');//this is button appending
$("#mybutton").click(function(){
alert("hello");
});
Assuming you call the .click() method on #mybutton before it is actually appended to #mydiv, you need to use .on() as the button doesn't exist when you attach the event handler:
$('#mydiv').on('click','#mybutton',function(){
alert('hello');
});
Should work...
Why don't you set the click inside the append?
This way you wouldn't need to concern about the element being added or not to the document's flow, since you'd be setting the event callback on the actual DOM element variable:
$("#mydiv").append(
$('X').click(function() {
alert("hello");
})
);

Handling event listerners with changing dynamic classname on HTML element?

I have several dynamically generated HTML elements which each uses their own dynamic id as the class name. I have event listeners attached to those elements like this:
$(document).on("click", ".id_" + dynamic_id , clickCallback);
The problem is the dynamic id can change through an ajax success call, and the respective HTML element is updated like so:
$(".id_" + old_dynamic_id).attr("class", new_dynamic_id);
This change will make the previously attached event listener to be lost because it doesn't know that the HTML element now has a new id that was assigned.
What would be a clean way of handling this? I could re-attach the event listeners inside the ajax success function, but that is not ideal since there will be two places where the same event listener code will live: when creating the element and inside the ajax success function.
You could try this:
$(document).on("click", "[class^='id_']", clickCallback);
This seems to work:
$(".link").on("click", function() {
alert("yes");
});
$(".link").attr("class", "new-class");
I.e. if the event is attached to the element directly.
http://jsfiddle.net/5ru2W/

How to select elements added via javascript [duplicate]

This question already has answers here:
adding jQuery click events to dynamically added content
(4 answers)
Closed 9 years ago.
I have a simple code that check a select change and alert a message. This is working ok but when I insert new .select-payment elements on the page this method is only available to the first one and not the ones created via javascript
$(document).ready(function() {
return $(".select-payment").on("change", function() {
return alert("hello");
});
});
Any idea how to make it work for any element that is added after the page is loaded that has a .select-payment class?
$(document).on("change", ".select-payment", function() {
alert("hello");
});
Also returning from within the change handler hardly makes sense, even less, returning the result of an alert.
You could use event delegation like below,
$(document).on('change', '.select-payment', function () {..
Replace the document with any closeby container that exist in DOM when executing the above line
Event delegation binds the event to the parent element and executes the handler when event.target matches the specified selector.
When targeting dynamically created elements, you need to use .on()'s delegated syntax:
$(document).on("change", ".select-payment", function() {
From the docs:
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().
To ensure the elements are present and can be selected, perform event
binding inside a document ready handler for elements that are in the
HTML markup on the page. If new HTML is being injected into the page,
select the elements and attach event handlers after the new HTML is
placed into the page.
why are you putting return statement ? You must attach your event handler to the document and not the existing .select-payment.
Try this : $(document).on("change",".select-payment",function(){...});
$(document).on("change", ".select-payment", function () {
alert("hello"); }
);
You can replace document with any closer parent element which will always exist in DOM for better performance. Like
$('#closestId').on("change", ".select-payment", function () {
alert("hello");
}
);
if you use $("document") jQuery will search for a node/tag named as document like and wont find anything as document is actually an object.
But you could use $("body") as body is a node/element of DOM.

click() assigned in document.ready in jQuery

Do assignments in document.ready (click(fn) specifically) apply to newly appended elements that match the selector?
If not, how can I assign it to this new elements? Do I have to write the assignment after every append or is there a better way?
You are looking for the live functionality. Per the manual:
Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events.
So if you do this:
$(document).ready(function() {
$('div.test').live('click', function() { alert('yipee!'); });
$('body').append('<div class="test">Click me!</div>');
});
When you click on the div you will get the alert even though it was added after the event was bound.

Categories