I'm loading a simple page using:
$.get('../admin/login.php', function(data) { $('#box-contents').html(data); });
Now, on this login.php page I have an input field, and in my global JavaScript file, I have an event that triggers on .change() - but this isn't firing!?
Is this because I have loaded this file on the page so jquery doesn't know that it's now there? Do I need to also include my global JS file within the 'login.php' page too?
Any help on this would be much appreciated
instead of using .get(), use .load() as it was intended for this purpose. Also for your .change() event, you need to either attach it after the element exists (which could be done in your callback below), or you can use .live() to attach the event to any current or future DOM elements.
Callback method
$('#box-contents').load('../admin/login.php', function() {
$('input').change(function() {
//do stuff on change
});
});
Live method
$('input').live('change', function() {
//do stuff on change
});
Related
I have a slider button created using a JavaScript plugin, which automatically generates an element with class name .flex-next. However, when I run the following code, nothing is logged in my console:
$(window).load(function() {
$( ".flex-next" ).on( "click", function() {
console.log("youclick");
})
});
Since the button is added dynamically after the dom is loaded, you need to use event delegation so the click event can be used on this button:
$(document).on('click','.flex-nex',function() {
console.log("youclick");
})
Your setting your call to fire when the window loads by using $(window).load(...);. A flexsider is initiated on $(document).ready(...) which happens after the window loads and all of the content is loaded into the DOM. So when your script fires, it looks for an element that isnt there yet.
Get around this by firing your script on $(document).ready(), and use event delegation. The best practice way is to declare your function like so:
$(document).ready(
$(document).on('click', ".flex-next", function() {
console.log("youclick");
});
});
this way your click listener will wait until the page is ready and will put a click event on to any .flex-next event, even those created dynamically. That way if your using large imagery that is loaded asynchronously the code will still work.
You are probably calling your $(".flex-next").on call before the slider button has been executed. So, basically, your .flex-next class doesn't exist in the DOM yet when you call the .on
You should call the .on call after plugin has been initialized.
I have an html form that loads its contents through ajax and includes buttons that, when clicked, should execute a JavaScript function that is defined in the html page's script tag. SO: Button is loaded through ajax (works), but when button is clicked, it doesn't trigger the desired action and doesn't trigger a JavaScript error in Firebug. How does one get the onclick signal of a bunch of buttons loaded through ajax to bind to an already existing JavaScript function?
EDIT: I should have noted also that I am not using JQuery. I am willing to do so if it is the only way, but otherwise, I would prefer to use only native JavaScript.
EDIT2: My problem was a bit more involved, but as was stated in the chosen answer, you should be able to set the onclick event handler in the php script before sending the data through ajax. If you have a data-heavy response and want to reduce bandwidth, you might consider doing everything client-side, but I find it easier in most situations just to set the onclick attribute in the php script.
Your dynamically generated button could have an inline event bound to it. When generating the button, simply make sure it has an onclick="alreadyExistingFunc();" and the page will happily execute it.
Alternatively, when your AJAX data is finished writing itself into the document, find the new button(s) and bind the event to them:
function ajaxSuccess()
{
document.getElementById('newButtonIdHere').onClick = function() {
alreadyExistingFunc();
}
}
That should do the trick. Also note that if you ever "need" a small part of jQuery to do something (like selectors or event handling), you can almost always do it without loading the whole library.
Append/insert the HTML (retrieved AJAX response) to DOM and bind click event to it:
function alreadyExistingFunc() {
alert('button is clicked!');
}
var ajax_data ="<button id='my-button'>My Button</button>";
$('body').append(ajax_data).find('#my-button').on('click', function(e){
alreadyExistingFunc();
// some more code...
});
OR:
$('body').append(ajax_data).find('#my-button').on('click', alreadyExistingFunc);
You could also use a callback:
function getAjaxContent(callback) {
$.ajax({url: "url"}).done(function() {
callback(data);
});
}
getAjaxContent(function (data) {
//ajax content has been loaded, add the click event here
}
When using jQuery.load to dynamically load HTML content into a webpage, what is the best way to "rebind" any handlers?
Normally you bind handlers in jQuery.ready, but they obviously don't work on newly loaded content. This is for handlers used both outside and inside the loaded content, so just binding them in the load success function is not really nice.
When subscribing to those handlers you could use the .on function which allows you to subscribe to even non existing yet DOM elements and when they are added the subscription will be done. The .on function was introduced in jQuery 1.7. If you are using an older version you could use the .delegate function to achieve the same effect which was introduced in jQuery 1.4.2. And if you are using an even older version you could use the .live method.
Here's an example of how you could subscribe to the click event of some element (existing or not yet existing that will be added in the future):
$('#someParentElement').on('click', '#someElement', function() {
});
You need to delegate events for the new content to a static parent element, for example:
$("#myDiv").load(myUrl);
$("#myDiv").on('click', '#myElement', function() {
// do stuff when #myElement (which was part of the HTML
// returned in the load() call) is clicked.
})
This assumes you're using jQuery 1.7+, if not, use delegate():
$("#myDiv").delegate('#myElement', 'click', function() {
// do stuff when #myElement (which was part of the HTML
// returned in the load() call) is clicked.
})
I noticed that in jquery appended text won't be processed by jquery functions. For example, you append a code containing dropdown-list and you have a function that invokes on changing its value. This function works on existing code only, not on appended one.
And the correct answer is:
Instead of using:
$('#purchase-table select').change(function() {
});
Use:
$('#purchase-table select').live('change', function() {
});
You need it to be able to process ajax-appended content by your jquery functions. Have a nice day.
Thanks to everyone helped.
You can use JQuery .live()
Append new content:
$('body').append('<div class="clickme">Another target</div>');
Add handler to it:
$('.clickme').live('click', function() {
// Live handler called.
});
Then clicks on the new element will also trigger the handler.
The easiest way to handle events on interactive content is the jQuery.live method.
http://api.jquery.com/live/
Description: Attach a handler to the event for all elements which match the current selector, now and in the future.
I've my jQuery code as
$('#tarea').click(function() {
// Do stuffs
});
This works fine for the button #tarea loaded along with this script. If the button #tarea had been loaded using ajax in future, than the above code doesn't work.
Now I changed the code to
$('#tarea').live('click', function() {
// Do stuffs
});
This time, the button #tarea if loaded along with the script doesn't work. But the script works with the button if generated using ajax.
How do I write the script so that in both cases, it works??
.live() works in both cases without doing anything additional to what you have already done. I would check for some other problems in your code that might be preventing this from happening.
Important: One thing to check is to make sure that your .live() event is being bound and that it doesn't rely on some other event happening. It might help to post the important parts of you JavaScript file. Personally I like to declare my .live() events globally.
I do something like this:
// this is what I mean by global because it is outside the document.ready
$("#test").live("click", function() {
// do stuff
});
$(function() {
// do stuff when document is ready
});
If you want to prove what I said above, you only need to put the button and the .live() JavaScript code in a new HTML file.
You put :
$('#tarea').click(function() {
// Do stuffs
});
in a function.
And when you load via ajax, you add a callback function (the one above) in second parameter of .load()
For example :
.load(target_url, function() { $('#tarea').click(function() { blablabla; }})