Image substitution - php

In the gallery of products I have choice to choose a color of item, seria, or side view. Each option has own picture. When I click one of these options I have src-substitution of image, for the effect I'm using fadeIn/fadeOut, it looks like:
$('button').click(function(){
$('img').fadeOut("slow",function(){
$(this).attr("src",newSRC);
$(this).fadeIn("slow");
});
});
but when fadeIn completed The picture does not have time to draw, even if it has already been loaded into the cache and it's looking very wierd for the site-gallery intercoms
I can not use preCache all images, because if the products will be a count of over 100 items the site will loading whole day, in the main case at low connections. I wanted to remove item fully, and then use load, but I can't remove items 'caz the gallery will crash (it's a flexible site, I can't remove items, all will collapse). Now I did a little gif, but ... facepalm, sorry.
So what do you think the best solution could be ?

I would wait for the next image to load before fading it in, like:
var loadFail;
$('button').click(function(){
$('img').fadeOut("slow",function(){
$(this)
.attr("src",newSRC)
.load(function(){
$('img').fadeIn("slow");
clearTimeout(loadFail);
});
loadFail = setTimeout(function(){
$('img').fadeIn("slow");
}, 4000);
});
});

I'd start the loading of the new image right away (into a temporary image object) on the click so it's available sooner (perhaps even before the fadeOut is done) rather than waiting until you actually need it to start the loading. This will get the image into the browser cache so it will load immediately when you assign the src of the real image and there will be less waiting:
$('button').click(function(){
var imgLoaded = false, fadeDone = false;
var fadeTarget = $('img');
// fadeIn the new image when everything is ready
function fadeIfReady() {
if (imgLoaded && fadeDone) {
fadeTarget.attr("src", newSrc).fadeIn("slow");
}
}
// create temporary image for starting preload of new image immediately
var tempImg = new Image();
tempImg.onload = function() {
imgLoaded = true;
fadeIfReady();
};
tempImg.src = newSrc;
// start the fadeOut and do the fadeIn when the fadeOut is done or
// when the image gets loaded (whichever occurs last)
fadeTarget.fadeOut("slow",function(){
fadeDone = true;
fadeIfReady();
});
});

Related

Variables not sent when pressing back button

I have a javascript that runs on a set of checkboxes to filter some items shown via PHP.
When someone filters the information and then clicks on an item, he is directed to that item's description. My issue is when that user clicks on the BACK button in the browser, since my filtering is already gone.
This happens because my script loads a .php but only inside a DIV (so I don't need to reload the whole page). This means my sent variables are just loaded at the DIV level and not at the URL level, so when they go to the description of a specific product and then go back, those variables are not there anymore and the filtering is gone.
Here is my JS:
$(function() {
$("input[type='checkbox']").on('change', function() {
var boxes = [];
// You could save a little time and space by doing this:
var name = this.name;
// critical change on next line
$("input[type='checkbox'][name='"+this.name+"']:checked").each(function() {
boxes.push(this.value);
});
if (boxes.length) {
$(".loadingItems").fadeIn(300);
// Change the name here as well
$(".indexMain").load('indexMain.php?categ=<?php echo $category; ?>&'+this.name+'=' + boxes.join("+"),
function() {
$(".indexMain").fadeIn('slow');
$(".loadingItems").fadeOut(300);
});
} else {
$(".loadingItems").fadeIn(300);
$(".indexMain").load('indexMain.php?categ=<?php echo $category; ?>', function() {
$(".indexMain").fadeIn('slow');
$(".loadingItems").fadeOut(300);
});
}
});
});
Any idea to solve this?
Either open the item description in a new window, or (more elegantly) open the item description in a modal dialog (e.g. using jQuery UI dialog).

Scroll through web images after thumbnail

I searched, but did not find the answer to this.
I have a website that displays hundreds of images in thumbnail format. I'm currently using php to display all of the images in thumbnail, then when the thumbnail is clicked upon to display the images in full-size.
What I would like to do is be able to click on a thumbnail and see the resulting full-size image, then at that point be able to scroll both back and forth through the full-size images without going back to the thumbnails.
As an added feature, when viewing the thumbnails, I would like to only load the ones that are currently displayed on the client page...ie - if the client screen resolution supports 20, then load only 20 and wait to load the rest on the client until the user scrolls down. The primary client in this use case is an iphone.
Thanks in advance!
you need to use a slider jquery plugin
Like
Jquery Light Box Plugin
When you click on the image, it should point to a new PHP file containing the full size image, or even better, load it in a new <div> with php you can get the client resolution with other tools
You actual have two seperate questions. One is to show the thumbs fullsize and be able to click to the next image. Almost every plugin to show images has that options. Personally i use fancybox, but pick anyone you like. To enable the next/prev buttons you need to group the images useing the rel tag.
Now to load the images per page, similar to google does it, you need to load it all in by javascript. Below is a setup of how you could do it. This is untested, as I did not have an image gallery at hand.
In the code below I load all images into the array at once, which is not perfect when you have a lot of images (like 1000+). In that case your better of using AJAX to load a new page. But if you have a smaller amount of images, this will be faster.
<script>
//simple JS class to store thumn and fullimage url
function MyImage(thumbnail, fullimage, imgtitle) {
this.thumb = thumbnail;
this.full = fullimage;
this.title = imgtitle;
}
//array that holds all the images
var imagesArray = new Array();
var currentImage = 0;
<?php
//use php code to loop trough your images and store them in the array
//query code to fetch images
//each row like $row['thumb'] and $row['full'] and $row['title'];
while ($row = mysqli_fetch_assoc($result))
{
echo "imagesArray.push(new MyImage('".$row['thumb']."', '".$row['full']."', '".$row['title']."'));";
}
?>
//the thumb width is the width of the full container incl. padding
//In this case I want to use 50x50 images and have 10px on the right and at the bottom. Which results in 60x60
var thumbWidth = 60;
var thumbHeight = 60;
var screenWidth = $('body').width();
var screenHeight = $('body').height();
var maxImagesPerRow = Math.round(screenWidth / thumbWidth);
var maxImagesPerCol = Math.round(screenHeight / thumbHeight);
var totalImagesPerPage = maxImagesPerRow * maxImagesPerCol;
//function to load a new page
//assuming you use jquery
function loadNextPage() {
var start = currentImage;
var end = currentImage + totalImagesPerPage;
if (end >= imagesArray.length) {
end = imagesArray.length - 1;
}
if (end<=start)
return; //last images loaded
$container = $('#thumbnailContainer'); //save to var for speed
$page = $('<div></div>'); //use a new container, not on stage, to prevent the dom for reloading everything on each iteration of the loop
for (start;start<=end;start++) {
//add a new thumbnail to the page
$page.append('<div style="margin:0;padding:0 10px 10px 0;"><a class="fancybox" rel="mygallery" href="'+imagesArray[start].full+'" title="'+imagesArray[start].title+'"><img src="'+imagesArray[start].thumb+'" alt="" /></a></div>');
}
currentImage = start;
//when all images are added to the page, add the page to the container.
$container.append($page);
}
$(function() {
//when loading ready, load the first page
loadNextPage();
});
//function to check if we need to load a new page
function checkScroll() {
var fromTop = $('body').scrollTop();
//page with a 1-based index
var page = 1 + Math.round(fromTop / screenHeight);
var loadedImages = page*totalImagesPerPage;
if (loadedImages==currentImage) {
//we are scrolling the last loaded page
//load a new page
loadNextPage();
}
}
window.onscroll = checkScroll;
</script>
<body>
<div id='thumbnailContainer'></div>
</body>

Making Tab Persist when Reloading Page

I'm trying to modify Gaya Design's Tabbed Content (Available Here) to have the current tab persist when the page is reloaded, yet have it change when a new tab is clicked. I've already changed it a little to be able to change default tab by using a PHP GET variable. The current condition of the page I'm working on can be viewed here.
So here's my likely scenario. If you've clicked on the link above, you'll see I'm working on a simple PHP shopping cart. Now when a user clicks an add link, it has to reload the page, and when it does that it resets the tab. So, I'm thinking this should easily be solved with a cookie that updates whenever a new tab is clicked....I'm just not too sure how to go about this. Any thoughts, suggestions, or advice will be greatly appreciated.
Here's my current JS:
var TabbedContent = {
init: function() {
$(".category").click(function() {
var background = $(this).parent().find(".selected");
$(background).stop().animate({
left: $(this).position()['left']
}, {
duration: 350
});
TabbedContent.slideContent($(this));
});
},
slideContent: function(obj) {
var margin = $(obj).parent().parent().find(".sliderContainer").width();
margin = margin * ($(obj).prevAll().size() - 1);
margin = margin * -1;
$(obj).parent().parent().find(".displayContent").stop().animate({
marginLeft: margin + "px"
}, {
duration: 1
});
},
gotab: function( obj ) {
var background = $(obj).parent().find(".selected");
$(background).stop().animate({
left: $(obj).position()['left']
}, {
duration: 1
});
TabbedContent.slideContent( $(obj) );
}
}
$(document).ready(function() {
TabbedContent.init();
});
Here's how a tab is initialized when it is linked to:
<?php
// Load a specific tab if required
if(isset($_GET['tab'])) {
// Array storing possible tab IDs
$tabChoices = array('productsTab', 'specsTab', 'brochuresTab', 'bannersTab', 'kitsTab', 'displaysTab');
$tab = '';
if(in_array($_GET['tab'], $tabChoices)) $tab = $_GET['tab'];
// Default to productsTab if not in array list
else $tab = 'productsTab';
// JS to actually do the switch
echo '<script>$(document).ready(function() {TabbedContent.gotab($("#' . $tab . '"))});</script>';
}
?>
You're painting yourself into a corner by inline scripting a solution. You should always only have one $(document).ready... call in your entire product, in order to avoid order dependent explosions in code, and have a clear point of entry.
That said, you are almost there. Instead of calling a function, assign a value.
echo "<script>var selectedTab=$tab;</script>"
Then during your initialization function, make use of that value. My example is in global scope. There may be a race condition if you try to assign it to a namespace. In that case, try putting that script at the bottom of the page.
One more suggestion, have one and only one function handle all of your animations calls for that object.
Instead of using get/post params you could use hash; creating links like this in the tabs:
<a class="tab_item" href="#one_go" id="one">
And then put this in the javascript:
var gototab = document.location.hash.replace('_go',"")
if(gototab){
$(gototab).each(function(){
var pos = $(this).prevAll(".tab_item").length,
left = pos * $(this).outerWidth(),
margin = pos * $(this).parent().parent().find(".slide_content").width() * -1;
$(this).parent().find('.moving_bg').css('left',left)
$(this).parent().parent().find(".tabslider").css('margin-left',margin)
})
}

Remove DIV only if empty

I have a PHP notification system, and the amount of notifications is put into a DIV using jQuery. The only problem is that when there are 0 notifications, the empty DIV still shows up. This is the jQuery I am currently using:
$(document).ready(function() {
$.get('/codes/php/nf.php', function(a) {
$('#nfbadge').html(a);
$('#nfbadge:empty').remove();
})
});
setInterval(function() {
$.get('http://localhost/codes/php/nf.php', function(a) {
$('#nfbadge').html(a);
$('#nfbadge:empty').remove();
})
}, 8000);
The only problem is that if at document load there is 0 notifications and a notification is added, the badge will not show up, so basically if the element is removed it won't come back unless the page is reloaded, but I made the notification system so that the page wouldn't have to be reloaded. How can I fix this?
.remove() takes the element out of the DOM as well as the content. This is why it doesn't come back unless you reload. Use .fadeOut() or .hide() instead
You should probably do something more like this:
var elm = $('#nfbadge'),
T = setInterval(getCodes, 8000);
function getCodes() {
$.get('/codes/php/nf.php', function(a) {
elm.html(a);
if (elm.is(':empty') && elm.is(':visible')) {
elm.hide();
}else{
elm.show();
}
});
}
Will need some more work on your part, but should get you on the right track!
If you have control over the PHP, you shouldn't be using jQuery to be removing DIVs, it's a waste of resources and load time, even if it's just a few lines of code.
In your PHP template you should include the #nfbadge div in a conditional statement, something like:
if($notifications) {
echo '<div id="nfbadge">';
//notification stuff
echo '</div>';
}
Then with your jQuery code you could do something like the following:
var $nfbadge = $('#nfbadge');
if($nfbadge) {$nfbadge.html(a)}
Why don't you just make the div hidden?
http://www.randomsnippets.com/2008/02/12/how-to-hide-and-show-your-div/

using a cookie with anything slider. possibly ajax

I am looking at writing a cookie that will be updated everytime the 'news scroller' moves to the next image/news item. when a user returns to the page it will automatically then start the scroller from the next news item.. helping to ensure our users get to see all the items.
i am using the 'anything scroller' by chris coyier et al, with php to pull in the news data.
each element has a unique id and are in numerical order so my cookie needs to retrieve the latest value and then +1 . the scroller allows for triggers to specific items.. but i can't seem to get the cookie to update on each, moreover it loads once the maximum id of those rendered in html...
is this even practical? assuming a maximum of 10 news items, would it slow the website down.
edit this is the could trying to get some output to the browser / console... but nothing.
<script>
// Set up Sliders
// **************
$(function(){
$('#slider').anythingSlider({
theme : 'minimalist-round',
easing : 'swing',
infiniteSlides : true,
delay : 8000, // How long between slideshow transitions in AutoPlay mode (in milliseconds)
resumeDelay : 8000, // Resume slideshow after user interaction, only if autoplayLocked is true (in milliseconds).
animationTime : 1, // How long the slideshow transition takes (in milliseconds)
autoPlayLocked : true, // If true, user changing slides will not stop the slideshow
})
$('#slider').bind('slide_complete', function(event, slider){
console.debug( 'You are on page ' + slider.currentPage );
// Do something else
})
});
</script>
solution: using local storage this works
<script type="text/javascript">
var ls = null, // local storage
sp = 1; // starting page
if ('localStorage' in window && window['localStorage'] !== null) {
ls = window.localStorage;
sp = ls.getItem('anythingSlider') || 1;
}
</script>
and
<script>
$('#slider').anythingSlider({
startPanel: sp,
// Callback when slide completes - no event variable!
onSlideComplete: function(slider) {
if (ls) {
ls.setItem('anythingSlider', (slider.currentPage+1));
$('.storage').val(slider.currentPage);
}
}
</script>

Categories