I have few divs which will be created by a script not in my control on the web page. These divs will be created after page has completely loaded, based on AJAX data. How can I associate onready event with these divs.
It sounds like you are looking for event delegation. jQuery's .on() method has a very simple approach to attaching event handlers to dynamically created elements. For example:
$( "#dataDiv" ).on( "click", "div", function() {
$( this ).fadeOut();
});
That code will listen for click events on all current and future div elements within #dataDiv and then hide whatever was clicked on.
You can delegate all standard jQuery event types in this manner. Hope that helps!
You cannot but you can use event delegation if its about clicks/hovering etc. See http://api.jquery.com/on/#direct-and-delegated-events
If you have no control on the scripts, what you can do is use ajaxComplete() to check if your divs are present after each ajax request completes.
Related
I have a heading.html file that is being loaded into my index.html.
heading.html
<header id="header">
<div class="logo"></div>
<nav>
Home
About Me
Why Me?
Contact
</nav>
</header>
Then in my javascript file where I am loading in this file, it doesn't let me do any other functions.
functions.js
$( document ).ready(function() {
$(function(){
$("#includedHeader").load("/assets/_includes/header.html");
});
$(function(){
$("#includedFooter").load("/assets/_includes/footer.html");
});
$(function(){
$("#includedWhyme").load("/assets/_includes/why-me.html");
});
$(".slide-section").click(function(){
alert('clicked');
});
});
As you can see I'm trying to make a alert popup just to test if it is working but it doesn't.
Is there a way where I can still use other functions on these html files that are being loaded.
When you're binding the event like this $(".slide-section").click(), the element is not there yet. The .load() is still grabbing the contents from the server.
You can, however, use on method in the document (delegated events). It does a live event attachment (the event will be catched even if the element only exists in the future).
From the .on() 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.
Another suggestion (if I might) is to remove $(function(){} from around your load calls. $(handler) is a shorthand for $(document).ready(handler). So, as if you're calling it once, you don't need them anymore.
So, my suggestion would be something like this:
$( document ).ready(function() {
$("#includedHeader").load("/assets/_includes/header.html");
$("#includedFooter").load("/assets/_includes/footer.html");
$("#includedWhyme").load("/assets/_includes/why-me.html");
});
$(document).on("click", ".slide-section", function(){
alert('clicked');
});
Don't Use directly click() method.. it would not work if the content is not already in the document..instead of this use .on() method to specifie click method its delegate have the advantage that they can process events from descendant elements that are added to the document at a later time.
so i from my point of view use following-
$(document).on("click", ".slide-section", function(){
alert('clicked');
});
I want to use click() as eventhandler and that event handler is not working you can see code below
$('.ajax-close').click(function( event ){
event.preventDefault();
alert('hi');
$( '.ajax-live-on' ).removeClass('ajax-live-on');
});
I have used all the code to initialize the jquery no problem , all right. But this piece of code not working
Here is the jsBin link
http://jsbin.com/doxeravizo/1/edit?html,css,js,output
The $('.ajax-close') collection doesn't contain the elements taking that class after the binding.
Change
$('.ajax-close').click(function( event ){
to
$(document.body).on('click', '.ajax-close', function( event ){
You should also move that binding outside of the loop, there's no reason to do it at every iteration.
Note also that in order to have your span clickable, it must have some content.
Demonstration (I added the jQuery library to make the fiddle work)
I'm guessing that because you're using ajax, your .ajax-close is not created when the event listener is being created.
You're going to want to delegate your click function:
$(document).on('click', '.ajax-close', function(event) {
event.preventDefault();
alert('hi');
$('.ajax-live-on').removeClass('ajax-live-on');
});
This article will help, but just for reference, this bit in particular:
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.
One option is to listen on the click event using a delegate, like so:
$(document).on('click', '.ajax-close', function( event ){
//your code
});
Another option might be to move your click listener inside the original click listener, which creates the "Close" button, while the reason the issue arises is that the click event on "ajax-close" is bound too soon (before the <span> is appended to the DOM even):
ajaxcontent.click(function(event) {
event.preventDefault();
$( '.ajax-live' ).addClass('ajax-live-on');
$( this ).after('<span class="ajax-close animated bounceInRight">Close</span>');
$('.ajaxshow').append().load(ajaxUrl);
$('.ajaxshow').addClass('animated bounceInUp');
// Move this section here, which was previously located below
$('.ajax-close').click(function( event ){
event.preventDefault();
alert('hi');
$( '.ajax-live' ).removeClass('ajax-live-on');
});
});
Make sure to include some content in your "ajax-close" span to be able to click it like the word "Close".
Add JQuery library to your HTML head :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
In your given link you are adding element dynamically, so need to use event delegate for dynamically created elements event binding.
$(document).on('click', '.ajax-close', function( event ){
//your code
});
I have a button that is loaded into my page using ajax:
<button id="submit">Submit</button>
I am using this code on the page that the button is being loaded into:
<script type="text/javascript">
$(function() {
$("button#submit").click(function(){
alert('Submit Clicked');
});
});
</script>
Why is it not detecting the click from the ajax content?
When you attach the click event you attach it to the existent elements in the DOM, when the ajax content comes, new DOM elements are created and the event wasn't attached to them.
One option is to use events delegation a way (but not recommended) to do it is using the document to read the event
$(document).on('click', 'button#submit', function(){
//do something
});
A better way is put the delegation to the element which gets the new content, lets assume is a form with an id formElement, It would be something like
$("#formElement").on('click', 'button#submit', function(){
//do something
});
Using that event delegation the new content from ajax will fire the click event.
PD if you have an ID in a element just use the id, like #submit, It makes a faster selector than tag#id because It used getElementById internaly
In your code you have attached the event handler to buttons before the button is created. You need to attach the handler afterwards. Add the handler in the ajax success() function instead, after you have created the button, and everything will work ok.
Its because its dynamically added button.For that you have to use on() method try following
$(document).on('click', 'button#submit', function(){
alert("hi");
});
I have a page where content is spread over several tabs. The user clicks each tab (anchor inside an <li>) in order to switch. I would like to anchor some other text to trigger the onClick of a tab in order to also switch the content.
Is this possible with javascript/jquery?
Yes. You can invoke a click event on another element using jQuery's .click();
Trigger tab click
Where #tablink is the ID of the tab you want to trigger.
More info: http://api.jquery.com/click/
You can achieve that with Jquery which is simple and easy to use. what you can actually do is that , you can attach a event eg., click to a event handler, which would do the stuff like loading appropriate content on to your current tab.
well this can be achieved by attaching the event to the event handler using a selector. .on() function is used as per the latest jquery lib although .click() also would work but its advisable to use .on() as it handles event delegation as well.
Example:
$( ".tab a" ).on( "click", function() {
// load the appropriate content to the current clicked tab
});
REF:
http://api.jquery.com/on/
Jsfiddle to play with :
http://jsfiddle.net/dreamweiver/h4JXs/1732/
Happy Coding :)
At the outset, let me be clear I'm not trying to use load() in an Ajax context to load a remote resource.
I'm just trying to bind a function to an object that doesn't exist at page load time, such that I can do stuff to it when it does appear.
I'm using jQuery 1.7
I have a form with class="contact-form").
This form is created on the fly, so it doesn't exist when document.ready() fires.
What I want to do is make some stuff happen when the form is created.
Presumably there should be a "load" or "ready" or some such event fired when the thing is available.
Under previous versions of jQuery I'd have used delegate() or live(); but these have been deprecated, and the current documentation says to use on( "load", handler ) or its shortcut, load().
I'm getting this from https://api.jquery.com/load-event/.
All of the following have so far failed to work:
$(".contact-form").load(function(){
console.log("Hi there!");
});
and
$(".contact-form").on("load", function(){
console.log("Hi there!");
});
and, in a hail-mary based on ideas from Jquery event handler not working on dynamic content,
$(document.body).on("load", ".contact-form", function(){
console.log("Hi there!");
});
Any pointers appreciated.
If you use .load() which is a shortcut for .on('load') called the load event, the matching element (form in this case) must exist at the time the page was loaded. jQuery < 1.7 had a .live() function which would listen for new elements dynamically added to the page, but it was removed in jQuery 1.7 for various reasons, performance being a major one.
Other options
jQuery LiveQuery is a plugin that sounds like it will do exactly what you're looking for.
https://github.com/brandonaaron/livequery
jQuery Entwine will watch for new DOM elements using livequery, but also allows you to create DOM elements and use them as full objects with their own methods defined.
https://github.com/hafriedlander/jquery.entwine
More info from jQuery's .on() docs
You can use Delegated events to create a click handler which will fire when an element is dynamically added to your original selector (typically a container), such as:
$( "#dataTable tbody" ).on( "click", "tr", function() {
alert( $( this ).text() );
});
Now, when a new <tr> is added dynamically, it will have the click handler bound to it. However, there is no event for the actual loading of an element into the DOM.
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. Or, use delegated events to attach an event handler, as described next.
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.
Why do you need an event at all? If the form is being added dynamically then run what you need to at the time
var form = '<form class="contact-form"></form>';
$('body').append(form);
console.log("Hi there!");
This method is a shortcut for .on( "load", handler ).
The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.
For example, consider a page with a simple image:
<img src="book.png" alt="Book" id="book">
The event handler can be bound to the image:
$( "#book" ).load(function() {
// Handler for .load() called.
});
As soon as the image has been loaded, the handler is called.
Now put that inside a ready handler
$( document ).ready(function() {
// onload functions here
});