using a cookie with anything slider. possibly ajax - php

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>

Related

detect active jqueryui tab with php?

Is there a way to detect which tab is active using php? Reason is I want to 'reset' inactive tabs to display their default content instead of the last action performed.
I found this code that helps remembering what tab is active (after page refresh) - works great:
<script type="text/javascript">
$(function() {
// http://balaarjunan.wordpress.com/2010/11/10/html5-session-storage-key-things-to-consider/
//
// Define friendly index name
var index = 'key';
// Define friendly data store name
var dataStore = window.sessionStorage;
// Start magic!
try {
// getter: Fetch previous value
var oldIndex = dataStore.getItem(index);
} catch(e) {
// getter: Always default to first tab in error state
var oldIndex = 0;
}
$('#tabs').tabs({
// The zero-based index of the panel that is active (open)
active : oldIndex,
// Triggered after a tab has been activated
activate : function( event, ui ){
// Get future value
var newIndex = ui.newTab.parent().children().index(ui.newTab);
// Set future value
dataStore.setItem( index, newIndex )
}
});
});
You cannot detect HTML content with PHP, when the output is done the connection to the server is closed and you have no more access to the server.
The only way would be Ajax but this is nonsense for live modifiers without page reload.
You should use pure JQUery to solve that.
You could make 2 content containers, and display one original version of your content in a hidden state and one to edit.
<div id="original" style="display: none;">
original content
</div>
<div id="custom">
custom content
</div>
If you want to restore the original text you can toggle the containers display:
<script type="text/javascript">
$("#original").toggle();
$("#custom").toggle();
</script>
Or even overwrite the modified content with the original one:
<script type="text/javascript">
$("#custom").html($("#original").html());
</script>

Javascript countdown timer that stops when window is not in focus

Ok , I'm having trouble to solve this , I'm a php / C# web developer , and have no experience or knowledge in Javascript, I have to do just this one thing that needs Javascript:
When a certain page loads, a counter starts. The client must stay on this page for 20 seconds. after, I want to execute php code.
So there are 2 issues concerning me, first: how do I stop the counter, if client leaves the page (meaning the page is not in focus).
2) How can I execute php in javascript? , or call a php function from Javascript.
The code I have so far is this:
<html>
<head>
</head>
<body>
<div id='timer'>
<script type="text/javascript">
COUNTER_START = 20
function tick () {
if (document.getElementById ('counter').firstChild.data > 0) {
document.getElementById ('counter').firstChild.data = document.getElementById ('counter').firstChild.data - 1
setTimeout ('tick()', 1000)
} else {
document.getElementById ('counter').firstChild.data = 'done'
}
}
if (document.getElementById) onload = function () {
var t = document.createTextNode (COUNTER_START)
var p = document.createElement ('P')
p.appendChild (t)
p.setAttribute ('id', 'counter')
var body = document.getElementsByTagName ('BODY')[0]
var firstChild = body.getElementsByTagName ('*')[0]
body.insertBefore (p, firstChild)
tick()
}
</script>
</div>
</body>
</html>
and I also want the timer to start ticking when the client gets back on page
Thank you very much for ur help in advance
You could do this using jQuery.
Recycling an old Stackoverflow post, try this:
var window_focus;
var counter = 1000;
// on focus, set window_focus = true.
$(window).focus(function() {
window_focus = true;
});
// when the window loses focus, set window_focus to false
$(window).focusout(function() {
window_focus = false;
});
// this is set to the ('click' function, but you could start the interval/timer in a jQuery.ready function: http://api.jquery.com/ready/
$(document).one('click',function() {
// Run this function every second. Decrement counter if window_focus is true.
setInterval(function() {
$('body').append('Count: ' + counter + '<br>');
if(window_focus) { counter = counter-1; }
}, 1000);
});
Demo and old post
DEMO | Old So post
Update
Probably because the demo runs in 4 iframes, the $(window).focus bit only works on the iframe actually running the code (the bottom-right window).
jQuery
jQuery.com (How jQuery works) | Example (back to basics halfway down the page) | If you use the 2nd link, also read this
In regards to your first question about detecting if the window is out of focus, see this answer: Is there a way to detect if a browser window is not currently active?
It is possible, but only very new browsers support this so it may not be useful based on current browser support.
To trigger PHP code from Javascript, you would have to make an AJAX call to a server-side PHP script to invoke PHP since JS is client-side and PHP is server-side.

Image substitution

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();
});
});

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)
})
}

jquery skip a block

I have a jquery game that you can view here link text
The game starts by you entering a number in a text field.
then you click the play button.
After clicking the play button a set of square appear each rotating random numbers, click on the square that has your number to build up your score, miss 3 times and you are done.
I added the game to my site, you can view it here link text
the problem I'm having is that my site members will just keep the cursor on one box and wait for their number to appear in that one box. Which ruins the game.
Is there a way to make it so they can't click on the same box more than once in a row. They'll have to go click another box before they can come back to this one.
here's my complete script
var hitCount = 0,
missCount = 0;
function IsNumeric(n) {
return !isNaN(n);
}
$("#getit").click(function() {
var hitCount = 0,
missCount = 0;
$('#hitcount').text(0);
$('#misscount').text(0);
$('#message').hide(100);
var li = [],
intervals = 0,
n = parseInt($('#MyNumber').val());
var intervalId = -1;
if (IsNumeric(n)) {
intervalId = setInterval(function() {
li[intervals++ % li.length].text(Math.random() > .1 ? Math.floor(Math.random() * (10 + n) + (n / 2)) : n).attr('class', '') ;
}, <?php echo $time ?>);
}
$('#randomnumber').empty();
for (var i = 0; i < 7; i++) {
li.push($('<li />').appendTo('#randomnumber'));
}
$('#randomnumber').delegate("li", "click", function() {
var $this = $(this);
if (!$this.hasClass('clicked')) {
if (parseInt($this.text(), 10) === n) {
$this.addClass('correct');
$('#hitcount').text(++hitCount);
} else {
$this.addClass('wrong');
$('#misscount').text(++missCount);
}
//New code If the missCount > 3 stop the game and save the value
if(missCount>=<?php echo $limit ?>){
clearInterval(intervalId);
$('#randomnumber').undelegate("li", "click");
// Use a ajax request to save the values
$.ajax({
type : 'POST',
url : 'FBhighscore_hwnd.php',
dataType : 'json',
data: {
tgameid: $('#tgameid').val(),MyNumber: $('#MyNumber').val(),totalHits: hitCount
},
success : function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data.error === true) ? 'error' : 'success')
.text(data.msg).show(500);
if (data.error === true)
$('#loginForm').show(500);
else
$('#send').hide(500);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#loginForm').show(500);
}
});
}
}
$this.addClass('clicked');
});
return false;
});
Have you tried using .one() to bind your click events, instead of .click()? Here's the documentation for it: http://api.jquery.com/one/
If you bind the click event with .one() then you could ensure that the function will only be triggered once. Then, inside that function, rebind the events for all other boxes, thus ensuring that they have to click another box before click the same one again.
Alternately:
Use a combination of .hover() and setTimeout() (and possibly hoverIntent) to disable a box when the user hovers their mouse over it for too long.
EDIT
Have a look at this modified version of your jsFiddle: http://jsfiddle.net/Ender/9ffTA/
Clicking on the same box twice in a row is disallowed. Hopefully you can use that as a guide.
Inside of your click you can mark that box as "locked" and just disable it until the next click.
That will not solve your problem. The user can still just move to another box and wait for their number to appear in that box. I just did it myself on your site. I don't believe there is a solution to your problem with the current game design.
I don't think the problem is with clicking, but with scoring.
Your proposed solution doesn't really defeat "waiting" as a strategy, as Drew points out. To really fix waiting, you need to give it a penalty.
Were it my game, I'd have three scoring metrics — correctly clicked boxes (what you're currently calling "hits"), incorrectly clicked boxes (... "misses"), and unclicked boxes (not in your current game). In other words, if my number is 5 and a box containing a 5 fades (is replaced by another number) before I click it, that's counted against me.
With this scoring system in place, anyone who simply hovers over a box and waits — even if they switch boxes between clicks — will watch their score get lower and lower as they miss boxes.

Categories