How can I run jquery function for a .click() event on a element created by an ajax request ?
For a normal element it works, but I want to do this for an element created by the ajax request. And it's not working ...
$(".links").click(function(){alert("aaaa");})
a class="links" >1</a;
I've also tried with "links" as id.
I need it for a pagination system.
Please help :(
You need to run the code again to bind the click event handler, after the new element is inserted into the DOM. Alternatively, you may want to use .live().
use jquery live
use jquery live,
$(".links").live('click', function(){
//user code here
});
to deal with dynamically loaded doms, you should use live function.
jquery do not load page doms automatically after page loaded.
You should use live() like this:
$(".links").live('click', function(){alert("aaaa");})
This also works with elements added to document
for an onclick to every <a> element you must do like this (if this is what you mean:
$("a").live('click', function(){
alert($(this).attr("id"));
})
This attaches event to all <a> elements and also to those added afterwards.
EDIT - now the alert shows the id of the link: 'this' in this case refers to the <a> that has been clicked
Related
This question is kind of a duplicate, but the answer provided doesn't actually solve the issue. Here's the related question:
Why jQuery click doesn't work when included in a separate file
I've got a php template that has an overlay div I am dynamically populating with different content, depending upon which link is clicked. So for example, I have this in my template:
<a class="icon-search" href="#"></a>
<div id="overlay" class="hidden"></div>
In my global.js file, I have these functions:
$(document).ready(function(){
$("a.icon-search").click(function () {
$("#overlay").load("inc/search.php");
$("#overlay").toggleClass('show hidden');
});
$("#cancel").click(function() {
$("#overlay").toggleClass('show hidden');
});
});
The cancel button is in "inc/search.php"
When you click "icon-search", the overlay toggles properly, and the content of search.php gets loaded, but pressing the cancel button doesn't work, unless I move that function into the search.php file. I really hate doing this, because it makes the html really messy, and it makes reusing things difficult. Is there any way to overcome this issue, so that functions will work on elements that are included?
You need to use event delegation in order to have generated content fire events.
Lookup the .on() method in the jQuery documentation (http://api.jquery.com/on/)
Try this instead:
$(document).ready(function(){
$("a.icon-search").click(function () {
$("#overlay").load("inc/search.php");
$("#overlay").toggleClass('show hidden');
});
$(document).on('click','#cancel',function() {
$("#overlay").toggleClass('show hidden');
});
});
Using .on() will delegate click events on the document to the elements with the specified selector and this will work for all current elements (which are in the DOM when this code runs) and future elements (like those which are appended using AJAX, like when you use the .load() method).
The event handlers like you are using (which I call static event handlers), must be attached directly to the DOM object they are handling events for. That means that when you run the code to attach the event handler, the DOM object you want to attach to must already exist.
If you are running this code on .ready(), but your dynamically loaded content has not yet been loaded, then no event handler will be attached because there's no DOM object yet to attach it to.
There are two general approaches to solving this type of issue:
Run the code AFTER you've loaded the dynamic content (this is what putting the script into your dynamically loaded PHP content does).
Switch to using delegated event handling. In delegated event handling, you attach an event handler to a parent of the dynamic content that is itself not dynamically loaded and thus it already exists. Then, when a click happens on the dynamic content, that click will "bubble" up through it's parents and encounter the click handler you have. jQuery automates a lot of this for you when using the delegated form of .on() which is of this form $("#staticParent").on("click", "#dynamicChild", fn). You can read the details about using the delegated for of .on() in these references:
Does jQuery.on() work for elements that are added after the event handler is created?
jQuery .live() vs .on() method for adding a click event after loading dynamic html
jQuery .on does not work but .live does
I have my code here.
// HTML Code
<div class="article"></div>
// jQuery
$('.article').append('Toggle div');
Is it possible to use that newly created href link and toggle a div like this:
// jQuery
$('.toggle').click(function() {
$('.article').toggle('slow');
});
I have tried the above with no luck. I just get redirected to index page.
Don't use click(): it's deprecated and wouldn't work even if it weren't. Use on():
$('.toggle').on('click', function() {
$('.article').toggle('slow');
});
Also, change your a tag to Toggle div.
As to the reason why on() works and click() doesn't, you need to read jQuery's documentation. In short, the click event has been bound to an element on the page; this scope does not cover future elements that are added to the DOM. On(), however, is a delegated event:
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.
I made a jquery code like :
$('button').click(function(event) {
});
In it; I put $.post and sent data to a php file and return table rows. In every rows, there is an 'add' button.
Then I made another jquery code for these buttons like :
$('.row_button').click(function(event) {
});
Again, I put $.post and tried to send data about that row and wanted to fetch information via ajax request. But it didn't work. Nothing happend. I looked code and there is no error.
Isn't it possible to use ajax within another ajax? Or is there another way? Thank you.
That is because those newly injected elements don't know about the click event binding you already have.
Solution : use jquery on function.
Change
$('.row_button').click(function(event) {
});
to
$(document).on("click",".row_button'",function(event) {
});
jQuery on works for current and future elements (newly injected elements via ajax/dynamically adding new elements using javascript) . It is available from jQuery 1.7+ version. If you are using an earlier version of jQuery, consider using jquery live
(As of jQuery 1.7, the .live() method is deprecated)
Try to use this instead second code:
$('.row_button').live('click',function(event) {
...
});
Jquery .live attach an event handler for all elements which match the current selector, now and in the future.
Edit
.live is now deprected so use .on insted:
$(document).on("click",".row_button'",function(event) {
});
From Jquery documentation:
$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+
I have a jQuery script which is triggered by an onClick event ( through $(".addContent").click(function(){ ) and which updates the page, adding an input text tag.
I am subsequently trying to trigger another script using an onChange event ( through $(".guestInput").change(function(){ ) on the input text tag which was just added, once the viewer makes a change. It doesn't work.
I have tried adding the input text tag as static html, and the subsequent onChange event fires successfully, but not when I add the field through jQuery.
Hope this is clear.
Any idea as to what I am doing wrong?
Thanks,
John
You need to use live() for DOM elements added after the initial page load.
so .click(function() { do_something; });
would now be .live("click", function() { do_something; });
see: http://api.jquery.com/live/
Description: Attach an event handler for all elements which match the
current selector, now and in the future.
I am working on a project which needs to extract text form a predefined div tag.
My requirement is to send the content in the target div in a email body. I have to use javascript or php for this task.
The Process :
When a given link will be clicked; a javascript function will trigger and read that target div. The content of the div will be then submitted to server in dynamic form.
What options I have to get this task done?
Thanks.
jQuery's text() (link) would let you get the text inside the div.
var thetext = jQuery('div#foo').text();
You could then use its post() (link) to send the data to a PHP script for emailing.
So assuming that you have something that looks like
Click Here
<div id="foo">Hello World!</div>
I recommend using jQuery:
<script type="text/javascript">
function someClickHandler() {
var text = $("#foo").text();
$.get("url_on_the_server", {some_query_parameter_name: text}, function(response){
// do something with the response you get back from the server
});
}
</script>
Here's what this is doing:
The onClick attribute causes the someClickHandler function to be called when the link is clicked. Because we put return false in that attribute, the browser will not try to follow the link; instead when clicked it will just execute the click handler and stop.
Saying $("#foo") finds the element on the page with an id of "foo", as documented here. Saying $("#foo").text() returns everything inside that div as text, as documented here.
The $.get call is explained at depth in the jQuery documentation here. Basically you're making an AJAX request to the server and passing the text from the div as a query parameter. The function you pass to $.get defines what you do with the response you get back from the server.
Of course, you could also use the jQuery click method instead of manually setting the onClick attribute yourself, but I figured that this way would be somewhat more intuitive for a beginner.
I would get the innerHTML of the div. So if your div is div_obj:
var div_obj = document.getElementById("...");
alert(div_obj.innerHTML);
Indeed, I'd give the div an id and then use the innerHTML method to get its contents.
After that, you could use XMLHttpRequest to submit the contents to the server.
document.getElementById( ID_OF_DIV ).innerHTML;
should do it if I'm not mistaken. W3Schools is a wonderful website for information on web programming.