I have a pinterest style site and made a jquery script that spaces the cubes evenly no matter how big the browser is. For some reason on page load it has some overlapping cubes which didn't exist before. I talked with the guy that helped me make it and he said it's probly because of the code before the code that creates the blocks and positions them. It crashes the javascript.
I think it's because of the $(window).scroll ajax loading code but I can't seem to pinpoint the problem. I tried moving positionBlocks(); around and nothing changes. If you load the page in your browser and then change your browser size then it positions them correctly but obviously I want it to look right when the user first gets there.
function setupBlocks() {
windowWidth = $(window).width();
blocks = [];
// Calculate the margin so the blocks are evenly spaced within the window
colCount = Math.floor(windowWidth/(colWidth+margin*2));
spaceLeft = (windowWidth - ((colWidth*colCount)+margin*2)) / 2;
spaceLeft -= margin;
for(var i=0;i<colCount;i++){
blocks.push(margin);
}
positionBlocks();
}
function positionBlocks() {
$('.block').each(function(i){
var min = Array.min(blocks);
var index = $.inArray(min, blocks);
var leftPos = margin+(index*(colWidth+margin));
$(this).css({
'left':(leftPos+spaceLeft)+'px',
'top':min+'px'
});
blocks[index] = min+$(this).outerHeight()+margin;
});
}
// Function to get the Min value in Array
Array.min = function(array) {
return Math.min.apply(Math, array);
};
var curlimit=<?php echo $curlimit; ?>;
var totalnum=<?php echo $num_rws; ?>;
var perpage=<?Php echo $perpage ?>;
var working_already=false;
$(document).ready(function() {
//($(window).scrollTop() + $(window).height() )> $(document).height()*0.8
// old ($(window).scrollTop() + $(window).height() == $(document).height())
$(window).resize(setupBlocks);
$(window).scroll(function() {
if(($(window).scrollTop() + $(window).height() )> $(document).height()*0.90 && totalnum>0 && working_already==false ) {
} else return false;
working_already=true;
$("div#loading_bar").fadeIn("slow");
curlimit=curlimit+perpage;
$("div#loading_data_location").html("");
$.get('get_cubes.php?page=<?php echo $_GET['page'] ?>&curlimit='+curlimit, function(response) {
$("div#loading_data_location").html(response);
$("div#ColumnContainer").append($("div#loading_data_location").html());
$("a#bigpic").fancybox({
'onComplete' : imageLoadComplete,
'onClosed' : imageClosed,
'type': 'ajax' });
if ($("div#loading_data_location").text()=="")
totalnum=0;
else
totalnum=<?php echo $num_rws; ?>;
$('.like:not(.liked)').click(like_box);
$('.save:not(.saved)').click(save_box);
$('.follow:not(.following)').click(follow);
$("div#loading_bar").fadeOut("fast");
$("div#loading_data_location").html('');
setupBlocks();
working_already=false;
});
});
I had to add this to the end of my script:
<script language="javascript">
$(window).bind("load", function() {
setupBlocks();
});
</script>
and then this to the end of the on scroll ajax load. Sometimes jquery just needs a little kick in the face haha:
setTimeout(function(){setupBlocks();},100);
Related
I am doing infinite ajax scrolling with php and api but my data is repeating. i don't want to load data when user is end of page(run perfectly) . What i want when user reach at certain div(check_onload) then load the data but in this case data is repeating.Here is below my code how i stop repeating data.
<div id="post-data"></div>
<div style="display:none;" class="ajax-load"></div>
<div class="check_onload"></div>
<script type="text/javascript">
///this run Perfectly
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $(document).height()) {
var token = $(".tokenId").val();
GetMoreData(token);
}
});
///Repeating or duplication the data
$(window).on('scroll',function() {
if (checkVisible($('#check_onload'))) {
var token = $(".tokenId").val();
GetMoreData(token);
} else {
}
});
function checkVisible( elm, eval ) {
eval = eval || "object visible";
var viewportHeight = $(window).height(), // Viewport Height
scrolltop = $(window).scrollTop(), // Scroll Top
y = $(elm).offset().top,
elementHeight = $(elm).height();
if (eval == "object visible") return ((y < (viewportHeight + scrolltop)) && (y > (scrolltop - elementHeight)));
if (eval == "above") return ((y < (viewportHeight + scrolltop)));
}
function GetMoreData(token){
$.ajax(
{
url: '/loadMoreData.php?token=' + token,
type: "get",
beforeSend: function()
{
$('.ajax-load').show();
}
})
.done(function(data)
{
$('.ajax-load').hide();
$("#post-data").append(data.html);
$("#tokenId").val(data.token);
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('server not responding...');
});
}
</script>
You have 2 window scroll events being triggered, causing duplicates because you are requesting data from the server with the same token twice, each time the user scrolls the page. I will have to assume that removing 1 of them will fix your problem.
Without seeing your server code, this is the only solution.
I have a simple installer that's divided in segments, not by syntax, but just by logic. Here's how it works:
if ($_POST['install'] == "Install")
{
// fetches user values
// creates tables
// creates some files
// creates some emails
// inserts relevant stuff into the database
// finishes
}
The code is too long and unnecessary for this question. Each of those steps counts as 20% complete for the installation, how would I make a progress bar displaying the info to the user? I'd like this for two reasons, one is for them to keep track, other is for them to know they shouldn't close the browser tab before it's done.
Now my idea is to assign a variable to each part of the code, for instance $done = 20% in the first, $done = 40% in the second etc, and simply show progress bar based on that variable. The the only thing I don't know is how to show the progress bar?
Thanks
My recommended solution:
Create separate ajax requests for each step in your process like so...
// do first step
$.ajax({
url: myUrl + '?step=1',
success: function() {
// update progress bar 20%
}
});
// do second step
$.ajax({
url: myUrl + '?step=2',
success: function() {
// update progress bar 40%
}
});
// etc.
If you want to be DRY, try this:
var steps = 5;
for (var i = 1; i <= steps; i++) {
$.ajax({
url: myUrl + '?step=' + i;
success: function() {
// update success incrementally
}
});
}
With jQuery UI progressbar:
$(function() {
$("#progressbar").progressbar({
value: 0
});
var steps = 5;
for (var i = 1; i <= steps; i++) {
$.ajax({
url: myUrl + '?step=' + i;
success: function() {
// update success incrementally
$("#progressbar").progressbar('value', i * 20);
}
});
}
});
Ref. http://jqueryui.com/progressbar/#default
The best practice is to store the progress value in a db or a key-value storage system such as APC, Memcache or Redis. And then retrieve the progress with an ajax query.
A good jquery plugin is progressbar bar from jQuery-ui, and you can use json to encode the progress value:
// GET /ajax/get-status.json
{
"progress":10,
"error":"",
"warning":""
}
The page:
<div id="error" style="color: red"></div>
<div id="warning" style="color: yellow"></div>
<div id="message"></div>
<div id="progressbar"></div>
<script type="text/javascript">
jQuery(document).ready(function() {
$("#progressbar").progressbar({ value: 0 });
$.ajaxSetup({ cache: false });
function updateProgress() {
jQuery.getJSON("/ajax/get-status.json", function(response) {
if (response.error) {
$("#error").html( response.error );
return;
} else {
$("#progressbar").progressbar( 'value', parseInt( response.progress ) ); // Add the new value to the progress bar
$("#message").html( response.message );
$("#warning").html( response.warning );
if(parseInt( response.progress ) < 100){
setTimeout(updateProgress, 1);
}
}
});
}
updateProgress();
});
</script>
You can use an HTML5 progress bar.
Send ajax request and return the percent complete.
Change the progress tag's value.
<progress id='p' max="100" value="50"></progress>
I am using a div refresh script (Given below). The contents of the div contains an auto scroll ul (code from http://www.dynamicdrive.com/). The refresh is working properly. But after the refresh the auto scrolling is not working
Code for refresh
<script type="text/javascript">
window.onload = setupRefresh;
function setupRefresh()
{
setInterval("refreshBlock();",1000);
}
function refreshBlock()
{
$('#list4').load("refreshpage");
}
</script>
Code for auto scroll
<script type="text/javascript">
var delayb4scroll=2000 //Specify initial delay before marquee starts to scroll on page (2000=2 seconds)
var marqueespeed=1 //Specify marquee scroll speed (larger is faster 1-10)
var pauseit=1 //Pause marquee onMousever (0=no. 1=yes)?
var copyspeed=marqueespeed
var pausespeed=(pauseit==0)? copyspeed: 0
var actualheight=''
function scrollmarquee(){
if (parseInt(cross_marquee.style.top)>(actualheight*(-1)+8))
cross_marquee.style.top=parseInt(cross_marquee.style.top)-copyspeed+"px"
else
cross_marquee.style.top=parseInt(marqueeheight)+8+"px"
}
function initializemarquee(){
cross_marquee=document.getElementById("vmarquee")
cross_marquee.style.top=0
marqueeheight=document.getElementById("list4").offsetHeight
actualheight=cross_marquee.offsetHeight
if (window.opera || navigator.userAgent.indexOf("Netscape/7")!=-1){ //if Opera or Netscape 7x, add scrollbars to scroll and exit
cross_marquee.style.height=marqueeheight+"px"
cross_marquee.style.overflow="scroll"
return
}
setTimeout('lefttime=setInterval("scrollmarquee()",30)', delayb4scroll)
}
if (window.addEventListener)
window.addEventListener("load", initializemarquee, false)
else if (window.attachEvent)
window.attachEvent("onload", initializemarquee)
else if (document.getElementById)
window.onload=initializemarquee
</script>
Could some one please help?
It seems like you need to call initializemarquee() after the load is complete. You can do this in the .load()'s callback.
function refreshBlock(){
$('#list4').load("refreshpage", function(){
clearInterval(lefttime);
initializemarquee()
});
}
I almost forgot to add that you'd also want to stop that interval.
You just need:
function refreshBlock()
{
$('#list4').load("refreshpage");
initializemarquee();
}
Why the mix of plain JS and jQuery? If you have jQuery use it
Here is my rewrite. Not tested but apart from typos or things that I thought could be done in jQuery and cannot, it should do the whole thing
$(function() {
var sId = setInterval(function {
$('#list4').load("refreshpage");
},1000);
var $cross_marquee=$("#vmarquee")
var delayb4scroll=2000 //Specify initial delay before marquee starts to scroll on page (2000=2 seconds)
var marqueespeed=1 //Specify marquee scroll speed (larger is faster 1-10)
var pauseit=true //Pause marquee onMousever (false=no. true=yes)?
var copyspeed=marqueespeed;
var pausespeed=(pauseit==0)? copyspeed: 0;
var actualheight=$cross_marquee.height();
var marqueeheight=$("#list4").height();
$cross_marquee.top(0);
if (window.opera || navigator.userAgent.indexOf("Netscape/7")!=-1){ //if Opera or Netscape 7x, add scrollbars to scroll and exit
$cross_marquee.height(marqueeheight);
$cross_marquee.css("overflow","scroll");
}
else var tId = setTimeout(function() {
lefttime=setInterval(
function() {
var top = $cross_marquee.top();
if (top>(actualheight*(-1)+8)) $cross_marquee.top(top-copyspeed)
else $cross_marquee.top(marqueeheight+8);
}
},30)
, delayb4scroll);
});
Been building sites with this code from chris coyier recently. Ajax jquery .load() etc.
everything is working great.
see code dump here http://css-tricks.com/dynamic-page-replacing-content/
$(function() {
var newHash = "",
$mainContent = $("#main-content"),
$pageWrap = $("#page-wrap"),
baseHeight = 0,
$el;
$pageWrap.height($pageWrap.height());
baseHeight = $pageWrap.height() - $mainContent.height();
$("nav").delegate("a", "click", function() {
window.location.hash = $(this).attr("href");
return false;
});
$(window).bind('hashchange', function(){
newHash = window.location.hash.substring(1);
if (newHash) {
$mainContent
.find("#guts")
.fadeOut(200, function() {
$mainContent.hide().load(newHash + " #guts", function() {
$mainContent.fadeIn(200, function() {
$pageWrap.animate({
height: baseHeight + $mainContent.height() + "px"
});
});
$("nav a").removeClass("current");
$("nav a[href='"+newHash+"']").addClass("current");
});
});
};
});
$(window).trigger('hashchange');
});
HOWEVER - I have now been turning all my pages into php - and I can't seem to hack it together... I thought I could just change the "html" to "php" in the jQuery... but that is not working...
Any help ?
Sorry to waste your time guys - I had been in front of this computer an unhealthy amount of time.
I had rushed and replaced href with php ... (thinking it was html)
REMEMBER TO TAKE BREAKS EVERYONE - OR FACE LOOKING LIKE A FOOL (Like me)
-thanks for your time...
I have a script that pops up a div element when a anchor tag is clicked
echo '<h2>' . $row['placename'] . '</h2>';
It's echoed from a PHP script, and is working fine in FF and IE(9).
But chrome won't run it, atleast on ver. 18.0.1025.168 m
The popup(divid); event fires when I click it, but it doesent complete the function calling inside the script the function is in.
var width_ratio = 0.4; // If width of the element is 80%, this should be 0.2 so that the element can be centered
function toggle(div_id) {
var el = document.getElementById(div_id);
if ( el.style.display == 'none' ) { el.style.display = 'block';}
else {el.style.display = 'none';}
}
function blanket_size(popUpDivVar) {
alert(popUpDivVar);
if (typeof window.innerWidth != 'undefined') {
viewportheight = window.innerHeight;
} else {
viewportheight = document.documentElement.clientHeight;
}
if ((viewportheight > document.body.parentNode.scrollHeight) && (viewportheight > document.body.parentNode.clientHeight)) {
blanket_height = viewportheight;
} else {
if (document.body.parentNode.clientHeight > document.body.parentNode.scrollHeight) {
blanket_height = document.body.parentNode.clientHeight;
} else {
blanket_height = document.body.parentNode.scrollHeight;
}
}
var blanket = document.getElementById('blanket');
blanket.style.height = blanket_height + 'px';
var popUpDiv = document.getElementById(popUpDivVar);
popUpDiv_height=0;
popUpDiv.style.top = popUpDiv_height + 'px';
}
function window_pos(popUpDivVar) {
if (typeof window.innerWidth != 'undefined') {
viewportwidth = window.innerHeight;
} else {
viewportwidth = document.documentElement.clientHeight;
}
if ((viewportwidth > document.body.parentNode.scrollWidth) && (viewportwidth > document.body.parentNode.clientWidth)) {
window_width = viewportwidth;
} else {
if (document.body.parentNode.clientWidth > document.body.parentNode.scrollWidth) {
window_width = document.body.parentNode.clientWidth;
} else {
window_width = document.body.parentNode.scrollWidth;
}
}
var popUpDiv = document.getElementById(popUpDivVar);
window_width=window_width/2;
window_width = window_width * width_ratio;
popUpDiv.style.left = window_width + 'px';
}
function popup(windowname) {
alert(windowname); // THIS WORKS
blanket_size(windowname);
window_pos(windowname);
toggle('blanket');
toggle(windowname);
}
The last function in that script is the one that is called first. I put an alert box in it to verify that it was fired. BUT, I put an alert box in the next function that it calls (blanket_size), and it did not fire, as I had the alert box on the first line in the function. It did not fire.
I simply have no clue why. The weird thing is that this stuff works in other browsers, but not chrome. Any ideas?
Thanks!
Edit: And I also verified that the parameter value passed into the popup() function (the 'windowname' param) is valid/has a value. It contains the ID of a DIV that is in the HTML document, and it's not dynamically created.
Edit 2: Ok, I got the script running when and ONLY when I add an alert box with the parameter value in it (windowname) to the popup(windowname) function. But if I remove that box, it stops working again.
Edit 3:
Got no errors on the debugger at all. But now I'm even more confused. After a great deal of tries, it seems like it's working with the alert box at random! Sometimes works, and sometimes not.
Final Edit
Changed logic to jQuery. Should have done this long ago!
// Open property
$(".property-open-link", ".yme-propertyitem").live('click', function() {
$("#yme-property-pop").css({'display': 'block', 'z-index': '9999' });
$("#blanket").css({'display': 'block', 'height', getBlanketHeight(), 'z-index': '1000' });
loadproperties('open', $(this).closest(".yme-propertyitem").attr("id"));
});
// Close property button
$("#yme-property-close").live('click', function() {
$("#yme-property-pop").css('display', 'none');
$("#blanket").css('display', 'none');
});
Couple of things to clear up first:
It really helps if you create a way for us to interact with your
code, especially as you've pasted PHP code here, instead of plain
HTML
Is there a reason why you're not using a library to handle your DOM
interactions? It will make your code more concise and take away some
possible failure points when it comes to cross-browser code.
Right,
I'm a little unsure why your code isn't working in Chrome. I set up a demo in jsfiddle and it seems to work fine.
You'll notice I'm not attaching the events in onclick attributes on the <a/> element, and neither should you. This could be where the problem lies.
Currently, the code in the jsfiddle alerts as expected and only fails when it fails to find a relevent DOM node in toggle.
Note:
addEventListener in the example is not cross-browser, which is another reason to use a DOM library.