How can I achieve amazon like "hover to load" functionality?
If you see in certain wordpress blogs, if there are any images towards the end of the blog it loads only when the control comes to that particular section of the blog. Similarly, in amazon there a开发者_开发知识库re certain sections down the product page like "Customers Who Viewed This Item Also Viewed", these details are loaded thru an ajax call only when the user hovers to that section of the page.
Which jQuery event can be used to fire such an ajax call? I want to achieve this functionality in rails 3.1, is there a particular way in rails to do it or is it just a simple js ajax call?
these details are loaded thru an ajax call only when the user hovers to that section of the page.
It looks like you are looking for the .mouseenter()
function: http://api.jquery.com/mouseenter/
var loaded = false;
$(".mySection").mouseenter(
if(!loaded){
function(){
$.get("URL FOR AJAX", function(data){loaded = true; /*do stuff with data*/});
});
}
EDIT: As a reaction to your comment:
.mouseenter
of course only works for the "hover" part of the question. To load when the scrollbar reaches a certain point of the document is a whole different thing. For that to happen you can use the.scroll()
function. You'd the have to read the currrent scroll position using$(window).scrollTop()
.- To stop the script from loading the same content twice you can simply set a flag, when the content has loaded and then not load it again, I edited the code example accordingly.
You can assess if something is visible by measuring the distance from the top of the document to the top of the element, and loading the item if that number is within the height of the window + the scroll.
You'll need an ever present parent element for this method, but it does factor in flexible document heights.
var scroll = $(window).scrollTop();
var win_height = $(window).height();
var document_height = $(document).height();
var element_height = $(element).height();
var element_offset = (document_height-(win_height+scroll));
if(element_height-element_offset>=0){
//load element contents
}
you could do something like this:
var success = function(data) {
//Show data!
}
$(".mySection").mouseenter(function(){
var that = this,
data = $(this).data("loaded");
// If the element has any loaded data display that, else call AJAX to get the data.
if($(this).data("loaded")) {
success(data);
} else {
$.get("URL FOR AJAX", function(data){
//check if its a success AJAX response ...
//Run the amazon like code.
success(data);
//Save data to the element, so we dont call AJAX all the time.
$(that).data("loaded", data);
});
}
});
so if you loaded the AJAX once (per page load) then you will call the data from the data object "loaded" on the element.
Try this.
var hasEntered = false;
$(window).scroll(function () {
if($(window).scrollTop() > $("#block-to-be-loaded").offset().top && !hasEntered ){
function(){
$.get("URL", function(data){
hasEntered = true; /*.....*/
});
});
}
}
精彩评论