I'm looking at using a large image in the background of a home page and would like the image to change every day, using CSS only. I'll obviously have a set of images to call in, not sure how may yet. It would be good if they could loop through though.
Would it be worth using a sprite and shifting the position on a 24 hour loop? I'm sure there's a cleaner way...
Many thanks!
You cannot to this using CSS only.
You can of course create 24 classes, one for each hour (or day, or whatever you like), each having a separate image background:
.hour01 { background:url('image-01.png'); }
.hour02 { background:url('image-02.png'); }
etc....
But you need either a server side language (such as PHP) or a client side language (javascript) to check what date/time it is and based on that, switch the CSS class of the body element.
You can't do that only in css but if you add some js it's doable :
today = new Date(); // will return 1,2,...,7 correpsonding to week days
if (today.getDay() === 1){
document.getElementById("background").className += 'mondayStyle';
}
if (today.getDay() === 2){
document.getElementById("background").className += 'tuersdayStyle';
}
...
Edit:
If you have not exactly 7 images (but less than ~30) you can do :
var nbOfImages = 12;
numDay = (today.getDate())% nbOfImages; // day of the month modulus nbOfImages
if (numDay === 1){
document.getElementById("background").className += 'tuersdayStyle';
}
...
Related
I have a website that has a Radio schedule, Mon - Sun. I would like to be able to display the correct schedule page for the current day, how would I do this? The site is a standard html site. I would also like to be able to highlight the particular show depending on the time of day.
Any ideas, this is all new to me.
Regards
Gary
Imagine that you have the following html documents:
Monday.html
...
Sunday.html
You can use the following code to output the page of the day:
<?php
$page = date('l') . '.html';
readfile($page);
exit(0);
?>
The example uses the function date() to get the day of the week as textual representation.
Place the code in file called pageOfTheDay.php in the same folder as the html documents on your webserver. In your HTML then use a link like
Page of the day
Note: The example assumes that you are using an english locale.
since it's also in the javascript section I'll post a JS version of it:
var days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Weekend","Weekend"];
var d = new Date();
var n = d.getDay();
window.location = days[n - 1]+".html";
place this at the top of your index.html file. In the same folder you need the various Monday.html ... Friday.html files
in the same way you could do:
var d = new Date();
var h = d.getHours();
and then add a class "current-show" to a specific element in the page (with jQuery)
$(".show-time-"+ h).addClass("current-show");
This assumes that you have given the right classes to the show in the page (for example
<div class="show-time-14"></div>
And then in your css you can do:
.current-show { background-color: #BADA55: }
You could benefit from a "page controller", say index.php. This page is the only page the user loads and the actual HTML "page" is included automatically. This could be decided by a URL param or default to the current date.
An untested and very basic example of what I mean:
<?php
if (isset($_GET["day"])) {
$day = $_GET["day"];
} else {
$day = date("l");
}
$fileName = $day . ".php";
if (file_exists(realpath() . $fileName)) {
include $fileName;
}
?>
Note: I have renamed the .HTML files to .PHP, allowing them to be included (you don't actually need to have any PHP code within them.
I'm putting together a contest site built on Wordpress. Legally, the contest has to start at midnight. To avoid being up at midnight to set up the content, i'd like to build some PHP logic to show everything after the start date, and before then display some basic HTML for a splash page. I'm a TOTAL programming newb, but i'm trying to work the problem out, here's what I have so far:
<?php
// The current date
$date = date('Y, j, m');
// Static contest start date
$contestStart = ('2012, 02, 03');
// If current date is after contest start
if ($date > $contestStart) {
//contest content?
}
else {
// splash content?
}
?>
I feel like there is smarter ways to do this. My site is fairly large... wrapping the whole thing in an if statement seems ridiculous. Maybe a redirect to a different page altogether based on the date?
Any help is appreciated.
You will want to modify your WordPress theme so that the changes can be site-wide.
Log in to your WordPress installation.
Navigate to Appearance > Editor
In the Templates section, go to header.php
At the very beginning of header.php, insert your code :
<?php
$date = time();
$contestStart = strtotime('2012-02-03 00:00:00');
if ($date < $contestStart) {
?>
<html>
Insert your whole splash page here.
</html>
<?php
exit;
}
?>
//The normal template code should be below here.
Don't forget to click the "Update File" button on WordPress when you're done; and like the others said, make sure that your specified time is synced with whatever timezone the server is in.
I suppose technically your code's logic would work but yes, there are much better ways of doing this. However, for your purpose we will go simple.
You should be comparing against a timestamp and not a string. Try this:
<?php
// The current date
$date = time();
// Static contest start date
$contestStart = strtotime('2012-02-03 00:00:00');
// If current date is after contest start
if ($date > $contestStart) {
//contest content?
}
else {
// splash content?
}
?>
You can put the splash and content components in separate .php files, and simply include() then within the conditionals.
if ($date > $contestStart) {
include("SECRETDIR/contest.php");
}
else {
include("SECRETDIR/splash.php");
}
You'll want to set up an .htaccess so that people cannot point their browsers towards secretdir and directly access contest.php
You don't have to wrap the content, you can have something like:
<?php
if ( time() < strtotime('2012-02-03 00:00:00') ) {
echo "not yet!";
exit;
}
//code here wont be executed
Be careful of timezones! Your server might be in a different timezone than your content.
// setup the start date (in a nice legible form) using any
// of the formats found on the following page:
// http://www.php.net/manual/en/datetime.formats.date.php
$contestStart = "February 1, 2012";
// check if current time is before the specified date
if (time() < strftime($contestStart)){
// Display splash screen
}
// date has already passed
else {
// Display page
}
Ok,
I've seen a couple of solutions out there but I am looking for the most lightweight version to accomplish this following:
<?php
$number = 20;
$counter = 0;
$i = 1;
$friends = $facebook->api('/me/friends');
foreach($friends['data'] as $friend)
{
if ($counter++ == $number) {
break;
}
echo '<li id="'.$i++.'"><img src="http://graph.facebook.com/'.$friend['id'].'/picture"/>'.$friend['name'].'</li>';
}
?>
I want to be able to increase $number = 20 when the user scrolls past a speecific div.
So for instance I know I can use jQuery for the scrolling mechanism:
<script>
$('#20').waypoint(function(event, direction) {
if (direction === 'down') {
"Increase php variable to 40"
};
});
</script>
If you guys can provide any knowledge it would be much appreciated.
Thanks!
PHP runs server sided, meaning that the whole page gets computed before outputting. What you are doing is not possible the way you are approaching it.
There are two approaches that will work in this situation:
Output all the information to begin with, but hide it and when the user scrolls to whatever point show it programatically with Javascript
Use AJAX to do dynamic page generation.
AJAX allows you to make requests to the server from Javascript to request remote content. For example, you could grab the content of myFile.php?count=123 and output the result in a div.
See http://www.w3schools.com/ajax/ajax_example.asp for an example on how to use AJAX.
I have a site that I want to display ads to 10% of my traffic. I am getting on average around 30,000 hits a day and want 10% of those users to see an ad from one of my advertisers.
What's the best way to go about implementing this?
I was thinking about counting the visitors in a database, and then every 10 people that visit 1 user gets an ad. Or is there a better way of going about it?
I'm no good with math, so I'm not sure what's the best approach.
Generate a random number between 1 and 10, and compare it to a fixed number, and your code will run on average 10% of the time:
if (rand(1,10) == 1) {
echo 'ad code';
}
You can make this per-user instead of per-pageview by storing whether that user was 'chosen' in their session.
session_start();
if (isset($_SESSION['show_me_ads']) || rand(1,10) == 1)
$_SESSION['show_me_ads'] = true;
echo 'ad code';
}
I use Google's DFP (Doubleclick for Publishers) to serve ads on my site. It's pretty robust. You have to have an AdSense account, but that's not very hard to obtain, it's just annoying to wait to be approved.
Once you have it set up and your ads loaded in, you can control how many people see your ad by percentage (such as the 10% you were talking about), total pageviews, etc.
Look into it: http://google.com/dfp
If you'd rather not use 3rd party software, I'd think the simplest way would be to randomize it so 1/10 visitors see your ad. The simple way would be:
if (rand(1,10) == 1) {
echo 'YOUR AD CODE HERE';
}
You said you're not good at math, and I understand that, I'm pretty horrible at it too, but basically, every time the page is loaded, it's "rolling" a 10-sided "dice". Every time it "rolls" a 1 (which would be 1 out of 10 times, or 10%), it'll display the ad. Otherwise, it'll be ignored.
The reason this is better than relying on counting the number of users (aside from simplicity) is that it will still roll 1 10% of the time whether you have 30,000 visitors or 3,000,000.
In its simplest form:
if (rand(1,10) == 1) {
echo $ad_content;
}
if(rand ( 1,10) == 1)
display_ads();
You can use
if(mt_rand(1,10)==10){
//show your code;
}
It will show ads to about 10% users
Why would you show ads to a few unlucky ones instead of randomly deciding per page impression (instead of per visitor)?
In php, you can just go ahead and write:
$adPercent = 10;
if (rand(0, 100) < $adPercent) {
echo '<div class="ads">Buy now!</div>';
}
if this was for google ads, then you would need to make the ad insertion optional (using the prob logic above), suggest something along the lines of Google Ads Async (asynchronous)
<script type="text/javascript"><!--
// dynamically Load Ads out-of-band
setTimeout((function ()
{
// placeholder for ads
var eleAds = document.createElement("ads");
// dynamic script element
var eleScript = document.createElement("script");
// remember the implementation of document.write function
w = document.write;
// override and replace with our version
document.write = (function(params)
{
// replace our placeholder with real ads
eleAds.innerHTML = params;
// put the old implementation back in place
document.write=w;
});
// setup the ads script element
eleScript.setAttribute("type", "text/javascript");
eleScript.setAttribute("src", "http://pagead2.googlesyndication.com/pagead/show_ads.js");
// add the two elements, causing the ads script to run
document.body.appendChild(eleAds);
document.body.appendChild(eleScript);
}), 1);
//-->
</script>
I would like to measure how much time a user spends on my website. It's needed for a community site where you can say: "User X has been spending 1397 minutes here."
After reading some documents about this, I know that there is no perfect way to achieve this. You can't measure the exact time. But I'm looking for an approach which gives a good approximation.
How could you do this? My ideas:
1) Adding 30 seconds to the online time counter on every page view.
2) On every page view, save the current timestamp. On the next view, add the difference between the saved timestamp and the current timestamp to the online time counter.
I use PHP and MySQL if this does matter.
I hope you can help me. Thanks in advance!
This is probably pointless.... what if the user has three tabs open and is "visiting" your site while actually working on the other two tabs? Do you want to count that?
Two factors are working against you -
You can only collect point-in-time statistics (page views), and there's no reasonable way to detect what happened between those points;
Even then, you'd be counting browser window time, not user time; users can easily have multiple tabs open on multiple browser instances simultaneously.
I suspect your best approximation is attributing some average amount of attention time per click and then multiplying. But then you might just as well measure clicks.
Why not just measure what actually can be measured?: referrals, page views, click-throughs, etc.
Collecting and advertising these kinds of numbers is completely in line with the rest of the world of web metrics.
Besides—if someone were to bring up a web page and then, say, go on a two week holiday, how best to account for it?
What you could do is check if a user is active on the page and then send an ajax request to your server every X seconds (would 60 secs be fine?) that a user is active or not on the page.
Then you can use the second method you have mentioned to calculate the time difference between two 'active' timestamps that are not separated by more than one or two intervals. Adding these would give the time spent by the user on your site.
google analytics includes a very powerful event logging/tracking mechanism you can customize and tap into get really good measurements of user behavior - I'd look into that
A very simple solution is to use a hidden iframe that loads a php web page periodically. The loaded web page logs the start time (if it doesn't exist) and the stop time. When the person leaves the page you are left with the time the person first came to the site and the last time they were there. In this case, the timestamp is updated every 3 seconds.
I use files to hold the log information. The filename I use consists of month-day-year ipaddress.htm
Example iframe php code. Put this in yourwebsite/yourAnalyticsiFrameCode.php:
<?php
// get the IP address of the sender
$clientIpAddress=$_SERVER['REMOTE_ADDR'];
$folder = "yourAnalyticsDataFolder";
// Combine the IP address with the current date.
$clientFileRecord=$folder."/".date('d-M-Y')." ".$clientIpAddress;
$startTimeDate = "";
// check to see if the folder to store analytics exists
if (!file_exists($folder))
{
if (!mkdir($folder))
return; // error - just bail
}
if (file_exists($clientFileRecord) )
{
//read the contents of the clientFileRedord
$lines = file($clientFileRecord);
$count = 0;
// Loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line)
{
echo($line);
if ($count == 0)
$startTimeDate = rtrim( $line );
$count++;
}
}
if ($startTimeDate == "")
$startTimeDate = date('H:i:s d-M-Y');
$endTimeDate = date('H:i:s d-M-Y');
// write the start and stop times back out to the file
$file = fopen($clientFileRecord,"w");
fwrite($file,$startTimeDate."\n".$endTimeDate);
fclose($file);
?>
The javascript to periodically reload the iframe in the main web page.:
<!-- Javascript to reload the analytics code -->
<script>
window.setInterval("reloadIFrame();", 3000);
function reloadIFrame() {
document.getElementById('AnalyticsID').src = document.getElementById('AnalyticsID').src
// document.frames["AnalyticsID"].location.reload();
}
</script>
The iframe in the main web page looks like this:
<iframe id="AnalyticsID" name="AnalyticsID" src="http://yourwebsite/yourAnalyticsiFrameCode.php" width="1"
height="1" frameborder="0" style="visibility:hidden;display:none">
</iframe>
A very simple way to display the time stamp files:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
</head>
<body>
Analytics results
<br>
<?php
$folder = "yourAnalyticsDataFolder";
$files1 = scandir($folder);
// Loop through the files
foreach ($files1 as $fn)
{
echo ($fn."<br>\n");
$lines = file($folder."/".$fn);
foreach ($lines as $line_num => $line)
{
echo(" ".$line."<br>\n");
}
echo ("<br>\n <br>");
}
?>
</body>
</html>
You get a results page like this:
22-Mar-2015 104.37.100.30
18:09:03 22-Mar-2015
19:18:53 22-Mar-2015
22-Mar-2015 142.162.20.133
18:10:06 22-Mar-2015
18:10:21 22-Mar-2015
I think client side JavaScript analytics is the solution for this.
You have the google analitycs, piwik, and there also commercials tools in JS that do exactly that.