I have a couple of Divs in my page with CSS class="hello"
Further I use Ajax to fetch a few more Divs with a CSS class="hello"
I have a piece of code which is called on Click event of the Divs as follows:
$('.hello').click(function(){
alert("Hello Clicked");
})
It works fine with the Divs that are present in my page from start but does not work with Divs loaded using Ajax. Is there something I need do in order to bind this little piece of code with the newly loaded Divs too?
you should use .on to bind the handler to another element that is already present during the execution of the binding, like say the <body>, or the document and have it detect the children events. but ideally, you should bind it to the nearest common parent of the content loaded.
demo
//bind to the body a "click" handler for elements that have class names of "hello"
$('body').on('click','.hello',function(){
alert("Hello Clicked");
})
Related
I have question regarding this jquery code block. What I am doing is, onclick on anchor tag, I am creating a anchor tag element and appending it to 'currentFilters' div element.
While debugging through firebug, I can see that anchor element is getting added to the div, then jquery automatically calls onclick again so my anchor tag gets created twice.
Not sure how onclick event is triggered again automatically.
Also, on page load, this functionality works as expected.. But then I am doing ajax call to the server and creates more elements in the same page. then it doesnot work,,
$(document).ready(function() {
$(".matchTypeCheckbox").click(function() {
var parent = "parent_" + $(this).attr('id');
$('#' + parent).removeClass("").addClass("active");
var newElement =
"<a tagid='"+ $(this).attr('id')
+ "' tagtype='mt' href='#' class='rTag'><span class='rTag'>X</span>"
+ $(this).text();
+"</a>";
$('.currentFilters').append(newElement);
});
});
it works fine on page load, only doesnt work after ajax call
and
But then I am doing ajax call to the server and creates more elements in the same page. then it does not work
When you call
$(".class").click(function() ...
it binds that anonymous/inline function to all elements with class "class" (in this example) - that exist at the time the click() is called.
This is why we use $(function() { (or $(document).ready, same thing), so that the click event is wired up after the DOM elements have been created and they already exist (to have the event attached).
If you then create new elements
$('.currentFilters').append(newElement);
the previous call on document ready has already been called so is not applied to the new elements.
There are two ways around this:
After calling append, also attach the click event handler (this works best with a separate function rather than anon/inline), something like (untested, ottomh) :
$(function() {
$(".class").click(clickHandler);
});
$('.currentFilters').append(newElement);
newElement.click(clickHandler)
or using event delegation, something like:
$(function() {
$(document).on("click", ".class", clickHandler);
});
I am using nested_forms with Rails 4 along with turbo-links + jQuery plugin to make it restart on page loads. Once I add a nested field with markup that should triggers events, it fails to do some, seeming like only content on initial page load can trigger the js events.
Example:
$(document).ready(function(){
$('.address_input_type').on('change', function(){
showAppropriateAddressFields(this);
})
});
So function showAppropriateAddressFields will fire if the '.address_input_type' is on the page initially but if added in afterwards it fails. Any ideas?
As the elements are newly inserted, you'll need to use event delegation:
$(document).ready(function(){
$(document).on('change', '.address_input_type', function(){
showAppropriateAddressFields(this);
})
});
Try to find a closer parent element than document (such as a container div) to use as the selector, as using document isn't very efficient.
If you query the DOM at the time of page load for a class, you will return an array-like-object of nodes that will not update itself when other nodes with that class are later added. Append it to the page from the beginning and set it's style "display: none".
I have the following jquery code
$(".delete").on('click', function (e){
e.preventDefault();
var id = $(this).prop('id');
console.log('Delete button id: '+id);
var formWrapper = $(".form-wrapper:nth-child("+id+")");
console.log(formWrapper);
formWrapper.remove();
});
the delete .delete is on a button inside a form
<button class="btn btn-danger delete">-<button>
and the button is loaded on the paged ynamically after the page has loaded. So I used the on function to attach the click event on it. But it won't work and the function is never called. Isn't on supposed to work not only for elements that are on the page during load but for those that get loaded afterwards?
You are saying that the particular button is getting loaded to the DOM dynamically, so in this context you have to use event-delegation to make your code working.
Normally your code will register event for the element with the class .delete immediately after the DOM loaded. Actually we dont have any elements with that identity at that time, So this context is opt for event-delegation.
I actually dont know the exact dom structure of yours, so that i have used document to delegate the click event, But you should prefer some static parent of that element to implement it,
Try,
$(document).on("click",".delete", function (e){
You need to use event delegation for dynamically generated elements. thus use .on() using delegated-events approach.
i.e.
$(document).on('event','selector',callback_function)
Use
$(document).on('click',".delete", function (e){
In place of document you should use closest static container.
The 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, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.
you should either use,
$(document).on('click',".delete", function (){});
or
$(".delete").click(function(){});
You can try jquery delegate() Method.
In jquery version 7 there was a term live however in latest one its removed and replace with delegate
you can check below example
HTML
< div class="delete"> Click Here < /div >
Javascript
$(document).delegate( ".delete", "click", function() {
alert("Hi")
});
This might help: http://jsfiddle.net/webcarvers/7Qtd7/
HTML:
<button id="one" class="delete"type="button">Id on me</button>
<div id="one">This is the div to remove</div>
JS:
$(document).ready(function(){
$("button.delete").on('click', function(){
var id = $(this).attr("id");
$("div#"+id).remove();
});
});
Dear Stack Overflow community,
I have been trying to develop a table creator that creates two tables dynamically when a button is clicked. This has worked... Well it hasn't at least for now.
Right now I am generating a <p> element with class heading and a <div> element with class content. When p is clicked, content is slideToogled.
I have tried using on() with jQuery or attaching any function to the element but it doesn't seem to work. Also .hide() doesn't work on content which is extremely annoying. Can anyone give me some advice as to how to approach this please?
On seems to work for content I hard written with HTML, but it doesn't on AJAX generated code appended to the div.
Here are the related snippets of code:
Ajax:
function submition() {
$.ajax({
type: 'GET',
url: 'phpQueries.php?q=getQueryBuilder&schools=' + mySchools.toString()+ '&depts=' + myDeps.toString() + '&lvls=' + myLevs.toString() + '&srcs='+mySrc.toString() + '&codes='+myCodes.toString(),
success: function (data) {
$("#dump_here").append(data);
}
});
jquery:
$(".heading").on("click", function() {
alert("Hello World");
$(this).next(".content").slideToggle(500);
});
PHP:
echo '<p class="heading">See/Hide Comments</p> ';
echo '<div class="content">I am I am I am.... Superman!</div>';
Kind Regards,
Gempio
This because (if I understand correctly) you create a <p> tag with the class heading after you assign the click event handler.
What you want to do is delegate your events to a container that contains your <p> tag. So, let's assume this is your structure:
<div id="dump_here"></div>
You then do this in your JavaScript:
$("#dump_here").on("click", ".heading", function () {
....
This way you assign an event handler to the parent container which already exists, and the event will bubble up once you click on your paragraph. Now you can dynamically add new elements to your HTML within that container and your event handlers will still work.
Why is that? Because you can't assign event handlers to elements that don't exist.
When you do this:
$(".something").click(...)
You don't tell Javascript to do something whenever you click any element with the something class on the page, you assign an event handler to every single already-existing something on the page. If you create a new element, even if it is the same class, you still need to assign an event handler to it.
A quote from 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()
Also David Walsh wrote a nice article explaining Event Delegation.
Hope this helps.
Change this:
$(".heading").on("click", function() {
alert("Hello World");
$(this).next(".content").slideToggle(500);
});
to:
$(document).on("click", ".heading", function() {
alert("Hello World");
$(this).next(".content").slideToggle(500);
});
Alternatively you can put the definition of $(".heading").on("click", ...) into your AJAX success callback, but if you have multiple .heading elements you'll run into multiple event bindings for elements that were there before the AJAX runs, say if it runs twice and appends 2 tables. The reason your method didn't work is the element has to exist before the event is bound. The 1st option I proposed works because the document is where the event is bound, and the last option works because it's in the callback of the AJAX that creates the element, so the element exists at the time it was bound.
So let's say, that this is your HTML:
<div id="dump_here">
<!-- contents here are dynamic - these don't exist when the page first loads -->
<p class="heading">See/Hide Comments</p>
<div class="content">I am I am I am.... Superman!</div>
<!-- end of dynamic content -->
</div>
Now on doc ready you attach your handler:
$(function() {
// $(".heading").click(//...this won't work, heading doesn't exist on load
$("#dump_here").on("click",".heading",function() {
// this will work - the handler is attached to an element that exists on load
// and will respond to event that bubble up from elements with the class 'heading'
});
submition(); // async function that populates your dynamic parts.
});
Be sure to read the docs on .on()
The important part to understand is this:
$(".heading")
This returns a collection of jQuery objects that represent DOM elements that have the class of heading. If there are no matching elements in the DOM when you execute that line, you will have an empty collection. But jQuery won't complain about this and will still let you chain to that empty collection:
$(".heading").on("click", function() { //...
What this says is attach an event handler to all the matching dom elements in my collection that will execute this function when the click event is triggered. But if your collection is empty, it won't do anything.
i have one page and i have written code
i am using jquery. now i want to append some html elements in some div of FormView.jsp, in response to some of the event fired in showFormPage.jsp.
how can i do it?
help me..
In your event handler you can target a element ID of say section in another frame called say other_frame, like so:
$("#button").click(function() {
$("#section", top.frames["other_frame"].document).append("<b>your html elements</b>");
});