Callback when web page download completes - javascript

When the user click on a tab in a web page, the tab opens and its corresponding page downloads from the server.
I want to add some UI in this page through JavaScript or jQuery. I know how I can add this but problem is if I execute my JavaScript function for adding UI on click of the tab, it does not work because the corresponding page has not been downloaded yet.
Basically, what I want to know such function that is called when the page completely downloads.

Have you used JQuery success ?? success handler will be called only after your response is ready.
Try this :
$.ajax({
url: "test.html",
context: document.body,
success: function(){
//Do the stuff here, hence downloading has been completed and response from server is ready
$(this).addUI("done");
}
});

add this in the body of your page..
<body onload="init()">
</body>
Basically your calling your init function -- which initiates all the other functions which you want only after the body of the webpage is loaded..

I have face this problem too.. Problem here is your content is not yet available before you could work on it.
any reference you give will result in returning Null
The solution can be .bind() & .live()
suppose this is your dynamic content
$('body').append('<div class="clickme">Another element</div>');
you can bind the element by,
$('.clickme').bind('click', function() {
// Bound handler called.
});
or register it for live content, by
$('.clickme').live('click', function() {
// Live handler called.
});
when no longer needed, you may unsubscribe the event on dynamic content by .die()
you may also find .delegate() & undelegate() useful as there are little issues with .live() & .die().
Check http://www.alfajango.com/blog/the-difference-between-jquerys-bind-live-and-delegate/ for choosing the one you need for your application.
Remember not to forget you ensure that content is loaded by ajax success as programmer_1 here, mentioned.
Good luck :)
Any further clarifications pls comment.

Related

How to make GTM Tags wait for some jQuery to be loaded?

I would like to track if a toast (or any "popup element") gets displayed using Google Analytics Event Tracking via GTM.
Whether or not the toast gets displayed is defined by jQuery code and based on cookie information like so
function ShowToast(Msg){
$('#toast-msg').html(Msg);
$('#toast').animate({ left: '-10px' });
}
called by
<script type="text/javascript">
$(function() {
ShowToast("SOME HTML");
});
</script>
This is what I got in GTM so far using a custom variable
function(){
if(document.querySelector("#toast #toast-msg").length > 0){
return true;
}
}
with a trigger listening for this variable to be true and the usual Universal Analytics Event Tag. The idea is to simply check if the toast-msg is shown or not, which works fine in preview mode.
Now to the problem: The tag is listening to gtm.js (pageview), but the jQuery code from the toast might load only after gtm.js is ready. Hence, sometimes the toast is not yet displayed when the tracking code is ready to fire and the event is not recorded.
Is there a way to use GTM and Javascript / JQuery to make sure all JQuery is loaded before GTM variables/triggers/tags are resolved? Or a completly different approach?
Make Sure you have the dataLayer initialized in the <head> of your document by including this line of code: <script>window.dataLayer = window.dataLayer || [];</script>
Add this code to your jQuery toasts (or whatever else you want to track) dataLayer.push({'event': 'event_name'});
Create a Custom Event trigger in GTM with the event_name you chose above.
Create a GA Tag of type event with the above trigger
One method is to push an event to dataLayer when the popup is loaded.
the other method is you can fire your code and gtm.dom or gtm.load(when the page is completely loaded)
Check the related article for more details http://marketlytics.com/analytics-faq/control-gtm-tags-to-wait
While using the dataLayer works, as suggested by others, I also found that my code works using two alterations:
Change errenous code: document.querySelector("#toast #toast-msg").innerHTML.length > 0 I forgot the innerHTML attribute
In order to ensure that jQuery has loaded I changed the trigger type to gtm.dom, which triggered the event reliably thus far.

Limited with JavaScript onCLick() when making AJAX call

I am working on an existing project and heavily using jQuery AJAX calls. Existing pages have three different sections header, left menu and main content. Implemented with Spring MVC it is updating whole page whenever view is returned from Spring controller.
Now since I am working with one of the menu item but having tab content I am using jQuery to manipulate data within tabs using jQuery. While doing so whenever I have to work with hyperlink I can't use <a> tag since return from link will replace whole page . So I am always limited to use onClick() even ton the link and do AJAX call then put response back in window using jQuery.
Details
<script>
$.ajax({
type: ...,
url: ...,
success: function(response) {
$('#tab1-content').empty().html(response);
}
});
</script>
So my question is - Is there any other way so that I can use href properties of <a> tag and update window with response view?
I am not sure if I understood you correctly. Could you try something like this:
Details
<script>
$('a').click(function(e) {
e.preventDefault();
var href = $(this).attr('href');
loadDetail(href);
});
function loadDetail(url) {
alert("Load from: " + url);
// Ajax call
}
</script>
Fiddle
You can prevent default behaviour of tag just return false from your function.
See this fiddle http://jsfiddle.net/s8mpwokt/
Or just like in Michael answer attach event from javascript so you'll get event instance in your callback function with preventDefault() and stopPropagation().

fire event on closing the page

I wonder if i've unset($_SESSION['enough']); and want to free it up on closing the page.
[ suppose visitor is viewing page of the website pages in new tab ]
i'm using this code
<script language="javascript">
window.onbeforeunload = function() {
console.log('event');
return false;
}
</script>
i wonder how can i apply to fire this code unset($_SESSION['login_id']); , it might look ridicules but this is the basic idea and i'm gonna give example what can be used for
For example : media website would like members not to watching more than one video in same time so the watching page drop session and free it on closing it so can watch more! js indeed is essential for website using jwplayer so no chance of talking about members with disabled js.
In order to load the killsession.php that runs the unset() command, you can run that page with ajax with async:false
Have a look at
Ajax request with JQuery on page unload
jQuery.ajax({url:"http://localhost/killsession.php", async:false})
You can use jQuery to fire on unload with the unload function (http://api.jquery.com/unload/).
$( window ).unload(function() {
// On the unload, we can fire a request back to the server
// .get(), .post(), and .ajax() may be useful.
});

Using jQuery to bind an event to AJAX content

I have a menu that is AJAXed in, thus loads later than the actual page. I would like to know if there is a way to bind an event to the surrounding div (the container div of logged in information).
Basically the container is empty when jQuery(document).ready() runs and gets populated 1-2 seconds after. I would like to run some scripts when this happens - and I'd rather not put the script into the AJAXed content itself.
In short, I want to execute some Javascript when a certain element shows on screen.
you can write your script inside success function of ajax... success is called whn the ajax request succeeds...
$.ajax{(
url:....
...
success:function(result){
//do your stuff like appeding..
//your script here
}
})
it would be easier if you provide us with codes to help you out..

jQuery live doesn't works as expected

i have problems with ajax requests and simple <input type="submit"/>.
i use to load views inside other views, modular i mean, with jquery using .load(url) from one view to another.
so the problem is that if i load view_2 inside view_1 and the js script for view_2 is inside view_1 i need to use live('click') for example to launch an xhr request from view_2, so when i try it launches 3 (multiple) xhr at same time, instead of only 1 at time, don't know why.
the only thing i know is:
using live('click') in view_1 it launches 3 multiple XHR.
using click() in view_1 it doesn't work(obviously i think).
using click() directly inside view_2 it works (but i can't use js
in loaded views, i can use js only in "parents" views)
the functions are really simple, really don't know why i have this problem (i also disabled submit in ajax beforeSend) check this is a view_1 code which runs on loaded view_2 and launches 3 XHR for click :|
$(document).ready(function(){
$('#save-doc').live('click',function(){
var _title = $('#doc-title').val();
var _doc = $('#doc-doc').val();
update_doc(url_update_doc,{'title':_title,'doc':_doc,'id_doc':_choosed_doc,'id_project':id_project},this);
});
});
function update_doc(_url,_data,_starter){
$.ajax({
type:'POST',
data:_data,
url:_url,
dataType:'json',
beforeSend:function(){
$('.ajax-loading').show();
$(_starter).attr('disabled','disabled');
},
error:function(){
$('.ajax-loading').hide();
$(_starter).removeAttr('disabled');
},
success:function(json){
$('.ajax-loading').hide();
$(_starter).removeAttr('disabled');
if(json.error){
$('#error-title').html(json.error_title);
$('#error-doc').html(json.error_doc);
$.scrollTo('.append-form-edit-doc','fast');
}
if(json.confirm){
$.scrollTo('#top','fast');
$.gritter.add({
title:'Document Saved',
text:json.confirm
});
}
}
});
}
If that's a submit button inside the form then unless you prevent the default action, the form will be submitted. (That'd account for 2 POSTs, but not three.)
Remember that .live() is binding the event handler to the document itself. With that in mind, it is searching for #save-doc throughout the document on every click.
If there are multiple elements in the document with the 'save-doc' ID then they'll all be triggered.
However, what I bet is happening to you is you may have multiple forms layered which are all being executed by this one input.
Edit: Third possibility, is what Pointy mentions. Executing a submit via your event handler and another submit occurring because of browser behavior.
Please provide the HTML and what is being loaded into them.

Categories

Resources