Execute script after loaded in div [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Initialize script
I have a page (Page1.html) and in this page a div (#div1) that get its content from other divs in another page (Page2 #div1/2/3/4/5). The content is loaded in by jQuery load script. The content is loaded in based on choice in a select box, so the content is loaded in after Page1 has finish loaded.
Problem:
When I get some content from Page2 that's depending on jQuery, these elements don't work. They don't execute.
My questions:
Is there any way to make the a whole inloaded #div from Page2 (all the content) to execute WHEN its loaded in? Right now the existing elements "initialize" when they are loaded in, for example: function initializeSlider(){ slider };.
Now I am trying to add in some more elements depending on jQuery, and wounder if initializing all the objects is the correct way of execute all these scripts, or is there any way that execute all the jQuery elements at once so no need to initializing all object one by one?
Executing or Initializing one script:
If there is no way to execute/initialize all scripts at once when a div is loaded in. I am trying to execute or initialize this script without success, have tried both the "$(document).ready(function() {" and initialize it similar to the slider but the element is not executing.
$(document).ready(function() {
$(".lil").click(function () {
$(this).toggleClass("highlight");
});
});

Depending on what you're initializing; for events make sure and use .on():
$("#div1").on('click', '.lil', function () {
$(this).toggleClass("highlight");
});

Use:
$(document).ready(function() {
$("#div1").on('click', '.lil', function () {
$(this).toggleClass("highlight");
});
});

You could give that function a name. Something like:
function toggleClasses(classToToggle) {
$(classToToggle).click(function () {
$(this).toggleClass("highlight");
});
}
Then, your main page could have:
$(document).ready(function() {
toggleClasses('.lil');
});
And at the bottom of the partial view that you load from page 2, add this:
<script>
toggleClasses('.partialViewClass');
</script>
That way, as soon as that Partial View is done loading, it will call that same function.
If all you're doing is toggling that class, you might want to add a parameter for a secondary class to differentiate the elements in the partial view from the elements in the original page, that way the ones in the original page won't get toggled back when the partial view gets loaded.
So the ones in your partial view would need the highlight class as well as that secondary differentiation class (class="lil partialViewClass"). Pass the class as the parameter to the function so each one will only toggle what it should.

Related

How do I add another div id to setInterval load?

I have this AJAX script that refreshes/updates a div with the id #main.
Is it possible to add yet another id #count to also refresh/update along with the other where it says /// can add another function here
I don't know javascript or ajax but I've tried to add function timingLoad() { $('#count').load(' #count', function() and just $('#count').load(' #count', function() but without any luck to get it working.
$(document).ready(function() { /// Wait till page is loaded
setInterval(timingLoad, 3000);
function timingLoad() {
$('#main').load(' #main', function() {
/// can add another function here
});
}
}); //// End of Wait till page is loaded
Sounds like you want to load the current page (via AJAX) at regular intervals and extract the contents of two separate HTML elements (#main and #count).
I would use jQuery.get() instead of .load() for this
$.get().done(doc => {
$("#main").html($("#main", doc))
$("#count").html($("#count", doc))
})
This loads the current page via $.get() then sets the HTML content of #main and #count with their counterparts from the loaded document.

How to bind a future event when using jQuery Mobile external page linking?

In jQuery Mobile, the external page is linked via Ajax (i.e. the content of the external page is loaded into current page via Ajax).
The problem is: How to bind a event on the future (i.e. to be loaded) content?
Let say the content to be loaded has the following HTML input
<input type='text' id='foo' name='foo'>
How to bind a input event on it?
With just static HTML, the following code would work
$('#foo').on('input', function () {
...
Now it didn't work now since the DOM is loaded dynamically, I tried to use delegation but also not work
$(document).on('#foo', 'input', function () {
...
Any idea?
You can include the script in the external page as long as the script tag is within the data-role="page" div (Only the content of the first found data-role="page" element is loaded into the current page.
$(document).on("pagecreate", "#extpagedivid", function(){
$(document).on("input", "#foo", function(){...});
});
You can also include this code in the pagecreate handler of the main page as long as you are using event delegation. Make sure the ID of the input is unique across all pages that will be loaded into the main page.
How about using var
var myFunc = function() { ... }
$(document).ready(function() {
$('#foo').on('input', myFunc );
});

Wrapping all AJAX calls jQuery

I populate many parts of my website using
$("#theDivToPopulate").load("/some/api/call.php", callBackToBindClickEventsToNewDiv);
Where /some/api/call.php returns a built list, div, or some other HTML structure to place directly into my target div. The internet has been running slow lately and I've noticed that the time between a button click (which kicks off these API calls) and the div populating is several seconds. Is there an easy way to globally wrap all the load calls so that a div containing "Loading..." is displayed before the call is even made and hidden once the API call is complete.
I can not simply put the code to hide the div into the callBackToBindClickEventsToNewDiv as some load events have different call backs. I would have to copy the code into each function which is ugly and defeats the purpose. I want the flow of any .load to go as follows:
1) dispplayLoadingDiv()
2) Execute API call
3) Hide loading div
4) do callback function.
The loading div must be hidden first as the callback contains some animations to bring the newly loaded div in nicely.
EDIT:
Expanding on jacktheripper's answer:
var ajaxFlag;
$(document).ajaxStart(function(){
ajaxFlag = true;
setTimeout(function (e) {
if(ajaxFlag) {
hideAllDivs();
enableDivs(['loading']);
}
}, 500);
}).ajaxStop(function(){
ajaxFlag = false;
var load = $("#loading");
load.css('visibility','hidden');
load.css('display','none');
load.data('isOn',false);
});
This way loading is only displayed if the page takes more than 500 MS to load. I found the loading flying in and out real fast made things kind of choppy for fast page loads.
Use the following jQuery:
$(document).ajaxStart(function(){
$('#loader').show();
}).ajaxStop(function(){
$('#loader').hide();
});
Where you have an element called #loader that contains what you want to show when an AJAX request is being performed. It could be a span with text, an image (eg a gif), or anything similar. The element should be initially set to display: none
You do not even need to call the function anywhere else.
Try this
$("#someButtonId").click(function(e){
e.preventDefault();
$("#theDivToPopulate").html("Loading...");
$.get("/some/api/call.php",function(data){
$("#theDivToPopulate").fadeOut(100,function(){
$("#theDivToPopulate").html(data).fadeIn(100,function(){
//Do your last call back after showing the content
});
});
});
});

Reload? Javascript after Jquery .live/.load

I wanted to load some fragments of external content inside a div, through a menu.
Found "load" and "live", found a tutorial used it = success!
Except, like what's explicit in the documentation, it doesn't load JavaScript.
The thing is, the destination page already loads, inside the header, that same JavaScript, 'cause Wordpress loads it in every page. In this particular page, I'm only using the plugin (nextgen gallery) through the jQuery AJAX call.
So, what I believe is my problem is that I somehow need to alert/reload the JavaScript, right?
And how can I do this?
<script type="text/javascript" charset="utf-8">
jQuery(document).ready(function(){
// ajax pagination
jQuery('#naveg a').live('click', function(){ // if not using wp-page-numbers, change this to correct ID
var link = jQuery(this).attr('href');
// #main is the ID of the outer div wrapping your posts
jQuery('#fora').html('<div class="loading"><h2>Loading...</h2></div>');
// #entries is the ID of the inner div wrapping your posts
jQuery('#fora').load(link+' #dentro')
return false;
});
}); // end ready function
</script>
PS: I've substituted "live" with "on" but didn't work either.
I'm not sure if I understand... your load() command is puling in some Javascript that you want executed? I'm not sure if you can do that. But if you just need to call some JS upon load() completion, you can pass it a function like so:
jQuery('#fora').load(link+' #dentro', function() {
console.log("load completed");
// JS code to be executed...
});
If you want to execute Javascript code included in the loaded page (the page you retrieve via .load()), than you have to use the url-parameter without the "suffixed selector expression". See jQuery documentation for (.load()):
Note: When calling .load() using a URL without a suffixed selector expression, the content is passed to .html() prior to scripts being
removed. This executes the script blocks before they are discarded. If
.load() is however called with a selector expression appended to the
URL, the scripts are stripped out prior to the DOM being updated,
which is why they are never executed. An example of both cases can be
seen below:
Here, any JavaScript loaded into #a as a part of the document will
successfully execute.
$('#a').load('article.html');
However in this case, script blocks in the document being loaded into
#b are stripped out prior to being executed:
$('#b').load('article.html #target');
I think that's your problem (although I have no solution for you, sorry).
Proposal: Maybe you can load the whole page (including the Scripts) and remove (or hide) the parts you don't need?
Cheers.

Basic jQuery problems

I am struggling with jQuery for a long time now. It is very powerful and there are lot of great things we can do with jQuery.
My problem is that I use a lot of jQuery features at the same time. E.g. I have a site that displays items, 12 items per page and I can paginate through the pages using jQuery. On the same page I implemented a thumpsUp button that uses jQuery too.
The more jQuery features I use, the harder it gets to arrange them properly. E.g.:
$(document).ready(function() {
$(".cornerize").corner("5px"); //cornerize links
$('a#verd').live('click', exSite); //open iframe
$("a.tp").live('click', thumpsUp); //thumps up
$("a#next").click(getProgramms); //next page
$("a#previous").click(getProgramms); //previous page
//for the current page reload the content
$("a#page").each(function() {
$(this).click(getProgramms);
});
//this isn't working...
$('.smallerpost').live('click', alert('test'));
});
Have a look at the last code line. I want to perform an alert when the div element is clicked. Instead of doing so the page shows me the alert when I refresh the page. A click on the div has no effect.
What am I doing wrong? What would be a strategy here to have clean and working jQuery?
Change that line to
$('.smallerpost').live('click', function () {
alert('test');
});
and while you're there...
$("a#page").each(function() {
$(this).click(getProgramms);
});
has exactly the same effect as:
$('a#page').click(getProgramms);
... but technically there should be only one element with id='page' anyway
Your code $('.smallerpost').live('click', alert('test')); calls the alert immediately and passes its return value into the live function as the second parameter. What you want to pass there is a function to call, so you want:
$('.smallerpost').live('click', function() {
alert('test');
});
or
$('.smallerpost').live('click', handleSmallerPostClick);
function handleSmallerPostClick() {
alert('test');
}
...depending on how you structure your code.

Categories

Resources