$("#").on("click",function () {
$("#").load('', function () {
$(".").on("click",function(event) {
event.preventDefault();
var data = $(this);
$.ajax({
.........etc
Can we use $.ajax function inside .load in jquery or is there any better way to handle this ?
I'm guessing you are trying to do that because you can't bind the click function on an element that hasn't been created yet. What you should probably be using is event delegation:
$("#id").on("click",function () {
$("#id2").load('');
});
$('#id2').on('click','.class', function() {
//do stuff
});
This will find any click that happens inside of #id2, which already exists, and if it originated from .class, which may or may not exist at the time of binding, will execute the "do stuff" code.
Related
i use ajax to load some data into one of my divs , i have a each function that do not work on newly added doms , how can i bind it with something like "live" or "on" to take effects on newly added DOMs by ajax ?
$('ul.bigs > li').each(function(){
console.log(this)
})
i mean "on" to something like :
$(document).on('click', '.header a', function() {
//do something
})
Wrap it in a function and call it after you've appended the data to the DOM.
function update() {
$('ul.bigs > li').each(function(){
console.log(this)
})
}
// Below is pseudo-code
$.ajax(..., function (data) {
// Add the data to DOM
update() // Call the update function at the end.
})
What do you mean by "newly added Doms"?
Because if you use something like element.innerHtml = <div id='tst' >/div> It won't work.
Since It does not update the DOM because you're just modifying a String.
I have put together a small script as part of a larger quiz project and am struggling to understand why the this keyword is being set in the function before it is called. Here is my code:
$(document).ready(function ($) {
function nextCard() {
console.log('yes');
$(this).closest('.card').hide();
$(this).parent().next().show();
}
$("#start").on('click', function (e) {
e.preventDefault();
//First card to appear
nextCard();
});
$("#next").on('click', function (e) {
e.preventDefault();
nextCard();
});
});
Why would 'this' not be set to element #start for instance?
Within nextCard(), this will refer to the window as that's the default scope. Hence your DOM traversal methods most likely are not working as you expect them to.
Assuming you want this within the function to refer to the clicked #start or #next element, you could provide the reference of nextCard() to the event handler methods, like this:
$(function($) {
function nextCard(e) {
e.preventDefault();
console.log('yes');
$(this).closest('.card').hide();
$(this).parent().next().show();
}
$("#start, #next").on('click', nextCard);
});
Why would 'this' not be set to element #start for instance?
Why would it be? It's not that it can sense what you want it to do.
Use Function#call to define what object this should point to during the call. If you don't explicitly define it, this will default to the global object (Window in browsers).
$(document).ready(function ($) {
function nextCard() {
console.log('yes');
$(this).closest('.card').hide();
$(this).parent().next().show();
}
$("#start").on('click', function (e) {
e.preventDefault();
//First card to appear
nextCard.call(this);
});
$("#next").on('click', function (e) {
e.preventDefault();
nextCard.call(this);
});
});
Using someFunction.call(this); will effectively "transfer the current meaning" of this to the called function, or more technically, call someFunction in the context of whatever object this is referencing at the moment.
jQuery does something like the above automatically - it sets this for you to the proper DOM element when it calls event handlers. You can make use of the automatic this handling like #Rory McCrossan's answer shows – or you handle this yourself.
Problem:
I have some selects with options in my HTML code and I have set an on change event handler, to figure out, when a selection will be changed.
The following code shows the jQuery code to get the on change:
$(document).on('change', '.anyHtmlSelect', updateState);
I have an existing Javascript function, that should be used as callback function.
The Javascript function looks like:
function updateState(element)
{
var currentId = element.attr("id");
}
Question:
How can I get the changed select as element?
I have tried the following:
$(document).on('change', '.anyHtmlSelect', updateState($(this));
but it doesn't work.
The first argument that is automatically passed to an event handler is a reference to the event itself, not the element that caused the event. To access the DOM element that triggered the event, use this:
Simply change:
function updateState(element)
{
var currentId = element.attr("id");
}
to:
function updateState(event) {
var currentId = this.attr("id");
}
After some research I have found a solution I would share with you.
In my solution, I created an anonymous function, which calls the updateState function with $(this) as parameter.
$(document).on('change', '.anyHtmlSelect', function () {
updateState($(this));
});
Is there a better solution?
I have this function executed in a script
$(document).ready(documentReady);
function documentReady(){
console.log("Ready");
$(".loadMore").on("click",loadMoreClicked(this.id));
}
function loadMoreClicked(elementID){
//do something with elementID
}
However, everytime the document loads up, it executes instantly the loadMoreClicked function - thus giving an error.
It seems that if I just want to assign a function to the click event without it being executed directly, I have to remove any argument.
Why does it happen, and how can I avoid it?
Just remove the parentheses and the argument, this will be available in the callback
$(".loadMore").on("click", loadMoreClicked);
function loadMoreClicked(){
var elementID = this.id;
}
You need to use an anonymous function to make the callback call
$(".loadMore").on("click",function(){ loadMoreClicked(this.id) });
Without this, the function is called immediately on document load causing the direct execution behavior you are observing. It will also assign the return value of the function (undefined in this case) to the click handler which is also undesirable.
$(document).ready(function(){
$('.loadMore').click(function(event) {
var self = $(this);
var element = self.attr('id');
});
});
Another option is to set an anonymous function as handler like this
function documentReady(){
console.log("Ready");
$(".loadMore").on("click",function(){
var element = this.id;
});
}
Its a good practice to delegate .off() before .on() to prevent multiple click event listener added to prevent memory leak. ie.
$(".loadMore").off("click").on("click",loadMoreClicked(this.id));
next, an event.preventDefault() would prevent any default action and intercepted by your function.
$(".loadMore").off("click").on("click", function(e) {
e.preventDefault();
loadMoreClicked(this.id);
});
Hope this helps.
If I make an AJAX request and want to call all functions that were set up by $(document).ready(). How can I do it? Thank you
$(document).ready();
If that doesn't work, try this:
function startup() {
// All your functions in here.
}
$(document).ready(startup);
And after your AJAX request is finished:
startup();
The easiest way is to use a shared function:
$(document).ready(function() {
setup();
});
$.post('/', {}, function() {
setup();
}, 'json');
But if you're using it to re-assign listeners, you would probably be able to get away with assigning them before they're created, like this:
$(document).ready(function() {
$(document).delegate('.my-button', 'click', function() { });
});
Using this code, all .my-button clicks will be handled by your custom function, regardless of whether the button existed in your DOM upon DOMReady.
Note that:
$(document).ready(function() { ... }); can be minimized to $(function() { ... });
If you're using jQuery 1.7+, prefer .on over .delegate: $(document).on('click', .my-button', function() { });
Prefer narrower context over broader, i.e. $('#close-parent').delegate over $(document).delegate
Instead of triggering document.ready by hand (which would be bad practice IMHO), make a function that's called setup which sets up all listeners etc. and invoke this function when you need to re-apply things etc.