how to fix javascript after ajax call? [duplicate] - javascript

This question already has answers here:
jQuery .live() vs .on() method for adding a click event after loading dynamic html
(7 answers)
Closed 7 years ago.
So the structure of my web page is split into three files. I have an index.html file with 3 divs; My navigation bar, a content box, and footer. Then I have two other .html files with different content that I want to load when clicking on links.
My Javascript looks like this:
$( ".content" ).load( "home.html" );
$( ".parents-link" ).click(function() {
$( ".content" ).load( "parents.html" );
});
$( ".home-link" ).click(function() {
$( ".content" ).load( "home.html" );
});
All files use some javascript and when I first open index.html everything works perfectly fine, but once I start clicking on the links the javascript doesn't fire anymore in the content div. My navigation bar in index.html uses javascript and still works regardless.
also, all my custom js is in one .js file for all three .html files. I'm also using some plugins.
How can I fix this issue?

You are loading dynamic content on click. .click() works only for elements currently in DOM, not for future elements. You must use $(staticElement).on('click', 'dynamicElementSelector') for that:
$(document).on('click', ".parents-link", function() {
$(".content" ).load("parents.html");
});
I suggest using dynamic structure:
$(document).on('click', '.loading-link', function (event) {
event.preventDefault(); // Prevent browser from following link.
$.load($(this).attr('href'));
});
There will be only one function for all links that must load some content.

Let's try this:
$('html').on('click', '.parents-link', function() {
$('.content').load('parents.html');
});
$('html').on('click', '.home-link', function() {
$('.content').load('home.html');
});
And as I said in my first comment, we need to bind events to an upper parent and make use of event propagation.

Related

javascript conflict with jquery fadein of button

I have a conflict with my javascript which is causing elements not to fadein. I have a button set to fadein after 10 seconds which works fine when I remove my javascript that I'm using for something else.
Can anyone help me figure out what the conflict might be?
You can see the test page I'm working on here: https://training.handcraftedbusinessfilms.com/test-fade-in/
I've currently removed the javascript that is causing the conflict but you can see it below.
<script type="text/javascript">
// Custom code by James
jQuery( document ).ready( function ( jQuery ) {
// binds to the plugin's function
jQuery( "input[name='gform_payment_method']" ).on( 'click', gfpStripeToggleCreditCard() );
// triggers the change to default option
jQuery( "input[id^=gform_payment_method_card_]" ).click();
console.log("Hello James");
});
</script>
Bro, your script is correct, but I see that you have 2 calls of "document.ready" in different parts of the html, so just need use once. I have merged and tested the script in the "head" tag and it works:
<script>
$(document).ready(function() {
$("div.button").fadeIn(2000);
//By James
//binds to the plugin's function
jQuery( "input[name='gform_payment_method']" ).on( 'click', gfpStripeToggleCreditCard );
//triggers the change to default option
jQuery( "input[id^=gform_payment_method_card_]" ).click();
console.log("Hello James");
});
</script>
The jquery was being called before it was defined in the header b/c the scripts were injected into the header via the theme and we couldn't control exactly the order of the scripts.
The solution was to create a site specific plugin that set a function to hold off on calling any jquery before the jquery was defined.

jQuery Widgets not working on tabs loaded by Ajax

I have an application that has many tabs, apart from the first tab - all others are loaded via Ajax.
The tab content all loads correctly.
However if I have a jQuery widget in a (ajax loaded) tab, the widget does not work.
I attempted to use:
$(document).on('click', '#dateOfBirth', function() {
$( '#dateOfBirth' ).datepicker();
});
But the datepicker does not display.
Confusingly (for me):
$(document).on('click', '#dateOfBirth', function() {
alert('This works properly');
});
Works properly! The alert displays when the date field is "clicked".
And of course if I have a simple page without the tabs / ajax content - the datepicker displays as expected when the date field is clicked.
I am using the jQuery 2.2.0 and
jQuery UI 1.12.0 with the "redmond" theme / CSS.
The view html follows the following;
<div class = "emr-bodycontent">
<div id="tabs">
<ul>
<li>Patient Details</li>
<li>Carers</li>
...
...
Here is the JS used for the TABS;
$( "#tabs" ).tabs({
beforeLoad: function( event, ui ) {
ui.jqXHR.fail(function() {
ui.panel.html(
"There seems to be an error retrieving the data you requested."
);
});
}
});
Instead of using click use focus and datepicker will work . Assumes that the element id is valid and is an input
$(document).on('focus', '#dateOfBirth', function() {
$( '#dateOfBirth' ).datepicker();
});
For any other plugins inside tabs you can use load callback of tabs ... see api docs
DEMO
I will suggest you to setup the datepicker() after Ajax content loaded, do not use click event. Because the initiate call of $('#dateOfBirth').datepicker() is to set up the datepicker, you may need to click again to trigger the calendar.
Or, you can try to manually trigger it right after set.
$(document).on('click', '#dateOfBirth', function() {
$(this).datepicker();
$(this).datepicker("show");
});
Firstly, thanks very much for the answers / comments.
Both answers work successfully.
Kieran's worked straight away as it was manually triggering the event.
Charlie's worked, too - but only after I clicked several times.
Though after fixing my underlying issue, Charlie's worked straight away, too.
The underlying issue was indeed a duplicate ID.
(thanks for the prompt to check, Charlie).
Because the TAB contents are their own individual forms / pages - I only ever worried about making ID's unique within individual TABs.
After ensuring that ALL IDs are unique, the widget works correctly / as expected.

jQuery is not working after div reload [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 7 years ago.
Maybe someone can help me with the following problem.
The problem is that i'm trying to add new photo album(with jQuery) and after adding- to show new album i'm reloading DIV with jQuery .load function
$($classid).load('..')
Everything is working fine, except that after reloading function like folder hovering (where bar with buttons appear - delete,etc..on hover) just don't work.
It looks like after DIV reloading jquery is dissabled and it need's to be called out again to run all functions.
I'v tryed to add this code
<script>
$.getScript("/data/sys.js" ); // item hovering functions styling etc..
$.getScript("/data/late.js" ); //for button clicks
</script>
at reload DIV'S Content..
Everything worked fine except that when I try to add new photo album at next album adding it multiply's added folder count.. so when i add one there show's up one, at next click there is two new folders..
I'v tryed alot and I cant figure out how to stop this or do it in diffrent way..
here is late.js file that is responsible for new folder adding..
late.js file
Thanks in advance..
Does adding this code below make any difference, as the page wont load up until everything is ready.
$(document).ready(function(){
});
Try:
function loadSelectors() {
// here paste sys.js code
$('#lfd').live('click', function(e) {//form button
$.post( $("#frm1").attr("action"),//form
$("#frm1 :input").serializeArray(),//form input
function(info){
$("#ui_info_anim_s").html(info);//popup
$("#afolder").css("display","none");
$("#fn_nameid").val('New Folder');
//a lot of animation stuff for popup
$("#ui_info_anim_s").animate({top: '40px'}, 'slow', function() {
$('#load_anim_privf').fadeIn( 500);
$('#load_anim_pubf').fadeIn( 500);
$('#load_anim_privf').fadeOut(1000,function(){});
$('#load_anim_pubf').fadeOut( 500);
$(this).delay(3000).animate({top: '+=40px',opacity:'0','filter':'alpha(opacity=0)'},'slow',function(){
$(this).css({"top": "-42px","margin-top": "-42px", "opacity": "1","filter":"alpha(opacity=0)" });
});});
});
loadUp(1,'.ui_treetype','');// Reloading func
});
$("#frm1").submit( function() {
return false;
});
}
Now you need to call function loadSelectors() two times. First on document load & second where div created
This happens because when you attach event handlers to div's and then replace them you lose all event bindings.
What you need is to attach event handlers through their parent container element which stays on page regardless of reload. I think it may be the one you refer to as $classid in your code.
In this case attach event handlers this way, only once, at your page dom ready event:
$(document).ready(function(){
$($classid).on("hover", "yourSelectorHere", function() {
... your code to handle event
})
$($classid).on("click", "yourSelectorHere", function() {
... your code to handle event
})
...
})

How to bind jquery function to specified element

I want to make function working only on page with specified element.
I have search page, search fields and results are in search-block div.
I want to bind function to this block, so function will not work on other pages (without <div id='search-block>...</div>)
I have next js code atm:
$(document).ready(function()
// instructions for another page (handlers for some links)
$(function(){
setInterval(findSomething,1000);
});
});
It working fine on page with search-block div, but it works fine on the other pages too. Browser tries to run this function on all other pages. I don't need this.
I tried jquery bind, but it now worked for me, don't know why :(
$("#search-block").bind(function(){
setInterval(findSomething,1000);
});
How I can bind handler to speciges too.fied block?
Instead of bind you have to check for the length of that elem:
$(document).ready(function(){
if($('#search-block').length > 0){ // <---checks the availability
setInterval(findSomething,1000);
}
});
Bind is always used with an event to bind to:
$( "#foo" ).bind( "mouseenter mouseleave", function() {
});
if you want to execute that only when the block is available on the page, use this:
if ($('#search-block').length) {
setInterval(findSomething,1000);
}
This checks the number of times #search-block is found on the page and if it is not 0(false) it executes the code.

jQuery Mobile no styling after using Ajax .load()

I'm using an Ajax call to get a list of checkboxes to appear in a panel after the user presses login. The data loads in fine but there is no JQM styling on it, its only the default browser styling. The id of the checklist is filterlist, and the div where I want to put it is called test1.
javascript:
$(document).on('click', '#loginbutton', function() {
$( "#test1" ).load( "test.html #filterlist" );
});
Try using
$(document).on('click', '#loginbutton', function() {
$( "#test1" ).load( "test.html #filterlist" );
$( "#test1" ).trigger ('create');
});
this will apply the jquery mobile styling to the newly created elements, if it is loading a page you might try 'pagecreate' instead

Categories