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.
Related
We got a simple jQuery script on Drupal site that injects a div class with content:
(function($) {
Drupal.behaviors.myHelpText = {
attach: function (context, settings) {
//code starts
//change placeholder text
$('.form-item-quantity').append('<span class="help-block">For orders over 10 call for volume pricing</span>');
$('.help-block').css("flex-basis", "100%");
//code ends
}
};
})(jQuery);
The page has Drupal Commerce and various product attribute fields that gets processed by Ajax every time selecting an attribute. And when doing that our script injects same duplicate line each time on Ajax load/update.
How to avoid that? We just want jQuery code work once on page load.
Only add the element if it doesn't exist, otherwise do nothing.
(function($) {
Drupal.behaviors.myHelpText = {
attach: function (context, settings) {
if (!document.getElementById('help')) {
$('.form-item-quantity').append(
'<span id="help" class="help-block">For orders over 10 call for volume ricing</span>'
);
$('.help-block').css("flex-basis", "100%");
}
}
};
})(jQuery);
You have to understand that drupal.behaviors fire on page load and when ajax returns results. It is designed this way because you may want your code to run again on the ajax results, for example, if you are updating part of the page via ajax and it needs event listeners applied, or a class added.
The context variable is the key here.
on first page load, the context will be the whole window, but when ajax returns the result, the context will just be what is returned by the ajax.
Knowing this, you should be using context in your jquery selectors.
eg.
(function($) {
Drupal.behaviors.myHelpText = {
attach: function (context, settings) {
//code starts
//change placeholder text
$('.form-item-quantity', context).append('<span class="help-block">For orders over 10 call for volume pricing</span>');
$('.help-block', context).css("flex-basis", "100%");
//code ends
}
};
})(jQuery);
For added protection against something processing multiple times, you can use jquery once(), but this is usually not needed if using the context variable in the selector. jQuery once() separate library that must be loaded.
Why don't use jQuery once? My thought — it's a classic approach. A bunch of examples lives in docs on drupal.org
$('.form-item-quantity').once('help-appended').append('<span class="help-block">For orders over 10 call for volume pricing</span>');
And I'm not sure you need to apply styles via js. A css file is a better place for it. And jquery once should be available in your environment. That's it.
I have Jquery function that executes AJAX query to server.
How can I call this after load page in the specified url page? May I bind this to element HTML, I mean:
<div id="graph" onload="function()"></div>
jQuery handles the HTML file with a variable called document.
Document has two popular event states
load when the page has been loaded
ready when the page has been loaded and all other decorations to the HTML have been applied.
jQuery provides hooks for these states.
To run javascript code after each of the events listed above, you have to put the function within the appropriate event scope.
For loading, this would be…
$(document).load(function() {
// javascript code you want to execute
})
After the page has been ready, but not yet rendered, you can apply some other javascript code using
$(document).ready(function() {
// javascript code you want to execute
})
One way using jQuery:
$(document).ready( function() {
//do whatever you need, you can check if some element exists and then, call your function
if($("#graph").length > 0)
callfunction();
});
No jQuery, only vanilla js:
window.onload = function() {
if(document.getElementById("graph"))
callfunction();
}
I am trying to import multiple HTML External pages into a single div.
Example: I am page1.HTML, page2.html and so on. I have this piece of JQuery:
<script type="text/javascript">
$(document).ready(function() {
$('.main').load('page1.html');
});
</script>
This works fine except I am not sure how to add multiple pages to become imported into the same div on page load.
Thank my friends.
If you want multiples then you cant use load. Use $.get instead and specify the callback to add them to the div:
var pages = ['page1.html', 'page2.html', etc..],
$main = $('.main'),
doLoad = function () {
if(pages.length > 0) {
// use shift to get the next page off the array
$.get(pages.shift(), function(content) {
// append content to .main
$main.append(content);
// call do load to get the next entry
doLoad();
});
}
};
doLoad();
var pages=["page1.html","page2.html","page3.html"],
mainDiv=$(".main");
$.each(pages, function(i,page){
var newDiv=mainDiv.append("div");
newDiv.load(page);
});
load() will be easier than get() if you only want to load page fragments (which is usually the case if you deal with complete pages that include head tags).
Create an array of HTML-files to load, and iterate through the array with an ajax call for each page, and then use jQuery prepend() to put the contents into your element.
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.
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
});
});
});
});