PHP Include inside DIV Styles Background - javascript

I've got a rotating image that changes daily and I'm trying to make this the background image of a DIV so I can have a menu over it. For some reason it just displays all the information inside the includes file instead of showing the daily image?
<div styles="background-image: url(<?php include('includes/promotions.php'); ?>)">MENU</div>
Inside the includes file:
<SCRIPT LANGUAGE="JavaScript">
today = new Date();
day = today.getDay();
arday = new Array("images/daily-offers/sunday.png", "images/daily-offers/monday.png", "images/daily-offers/tuesday.png", "images/daily-offers/wednesday.png", "images/daily-offers/thursday.png", "images/daily-offers/friday.png", "images/daily-offers/saturday.png");
document.write("<img src='"+arday[day]+"'>");
</script>`
I'm kind of new to this but I appreciate the help!

You are trying to put javascript into the style attribute of a div, this isn't possible. Either you need to have php code come up with the filename instead of using an include, or you need to create the div give it an id the use javascript (outside the div's style) to change the background-image.
<div id='changeme'>Menu</div>
<SCRIPT LANGUAGE="JavaScript">
today = new Date();
day = today.getDay();
arday = new Array("images/daily-offers/sunday.png", "images/daily-offers/monday.png", "images/daily-offers/tuesday.png", "images/daily-offers/wednesday.png", "images/daily-offers/thursday.png", "images/daily-offers/friday.png", "images/daily-offers/saturday.png");
//ASSUMING YOU HAVE JQUERY
$('#changeme').css('background-image',arday[day]);
</SCRIPT>
Or simply use php:
<?php
$arday = array("images/daily-offers/sunday.png", "images/daily-offers/monday.png", "images/daily-offers/tuesday.png", "images/daily-offers/wednesday.png", "images/daily-offers/thursday.png", "images/daily-offers/friday.png", "images/daily-offers/saturday.png");
$day = date('w');
?>
<div styles="background-image: url('<?php echo $arday[$day]; ?>')">MENU</div>
Or if the naming convention of the images is always the same you could simply do:
<div styles="background-image: url('images/daily-offers/<?php echo strtolower(date('l')); ?>.png')">MENU</div>

You can set the backgroundImage like this:
document.getElementById("mymenu").style.backgroundImage="url(...)";
Your code could go like this:
<div id="mymenu">MENU</div>
<SCRIPT LANGUAGE="JavaScript">
today = new Date();
day = today.getDay();
arday = new Array("images/daily-offers/sunday.png", ...);
document.getElementById("mymenu").style.backgroundImage="url('"+arday[day]+"')";
</script>`

You can't execute javascript inside an attribute like that.
You could try this - change the contents of your includes/promotions.php file to the following:
<?php
$day = strtolower(date('l'));
echo '<img src="images/daily-offers/' . $day . '.png">';
?>
Additionally, the attribute on your div should be style, not styles.

I would not use PHP to do that.
I would right the following javascript code at the page where you showing right now the div with the background.
<div id="bgdiv">MENU</div>
<SCRIPT LANGUAGE="JavaScript">
today = new Date();
day = today.getDay();
arday = new Array("images/daily-offers/sunday.png", "images/daily-offers/monday.png", "images/daily-offers/tuesday.png", "images/daily-offers/wednesday.png", "images/daily-offers/thursday.png", "images/daily-offers/friday.png", "images/daily-offers/saturday.png");
document.getElementById('bgdiv').style.backgroundImage = "url(' + arday[day] + ')";
</script>

Related

PHP, JS - Documenting and saving DATE/TIME to re-appear after browser closed

I currently have a sitation where I can click on an image and it will return a new image, and in the previous grid-item, it will return the day and time I clicked it.
What I want is to have this BUT where I also can see the updated image and clicked time after closing and re-opening the browser. - What is the easiest / quickest way to achieve this?
I feel like adding to my database would be a way forward, but if that is what I would need to do, how would I go about storing and out-putting the time based on the time I click?
(This is not intended to be a live site, or for others to see or use, so local quick-fixes are viable).
foreach ($flavours as $key => $flavour) {
echo "<div class='grid-container'>";
echo "<div class='item7'><p id='p3'>Sylus: </p></div>";
echo "<div class='item8'><img src='htts://i.i.com/k.jpg' onclick='cS(this)' /></div>";
echo "</div>";
}
function cS(element) {
if (element.src == "htts://i.i.com/k.jpg")
{
element.src = "http://i.i.com/v.jpg";
var d = moment().format('dddd HH:mm');
element.parentElement.previousElementSibling.firstChild.innerHTML = "Sylus: " + d;
}
else
{
element.src = "htts://i.i.com/k.jpg";
element.parentElement.previousElementSibling.firstChild.innerHTML = "Sylus: ";
}
}
Try this example using localStorage. This will find the <p> tag elements within the body, and then uses each element to get the id for reference.
I tried using a fiddle here, but the site has a security complaint with the localStorage.
Copy/paste this code to a file to give it a try. Note that you will likely need to update the moment.js reference in this code to match your file path.
<!doctype html>
<html>
<head>
<title>localStorage example</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="moment.js"></script>
</head>
<body>
<div class='grid-container'>
<div class='item7'><p id='p0'>Sylus: </p></div>
<div class='item8'><img src='htts://i.i.com/k.jpg' onclick='cS(this)' /></div>
</div>
<div class='grid-container'>
<div class='item7'><p id='p1'>Sylus: </p></div>
<div class='item8'><img src='htts://i.i.com/k.jpg' onclick='cS(this)' /></div>
</div>
<script>
function cS(element) {
var pTag = element.parentElement.previousElementSibling.firstChild;
if (element.src == "htts://i.i.com/k.jpg")
{
element.src = "http://i.i.com/v.jpg";
var d = moment().format('dddd HH:mm');
var pText = 'Sylus: ' + d;
pTag.innertHTML = pText;
// Set (save) a reference to browser localStorage
localStorage.setItem(pTag.id, pText);
}
else
{
element.src = "htts://i.i.com/k.jpg";
pTag.innerHTML = "Sylus: ";
// Remove the stored reference. (delete this if not needed)
localStorage.removeItem(pTag.id);
}
}
$(document).ready(function() {
pElements = $('body').find('p').each(function(index, element) {
// Get the localStorage items. The retrieved <p> elements,
// we use their id value to reference the key in storage.
storageItem = localStorage.getItem(element.id);
if (storageItem) {
$('#' + element.id).text(storageItem);
}
});
});
</script>
</body>
</html>
After clicking an image (will need to replace with something real), open the browser's web inspector interface, click the Storage tab, and then expand the Local Storage in the list (see image below), and choose the file being tested.
There will be key/value pairs displayed. The keys are references to the <p> tag id's, and the value will have a label-date strings such as Sylus: Wednesday 22:28.
Once you see an entry, or two, being set to the storage, close and then reopen the browser tab. The <p> elements that had dates should be reloaded with their values from the storage.
The browser's Local Storage area should be similar to the image below:
save it to local storage, or a cookie with the exp. date too far in the future

Loading text from a txt file depending on day of week

I am using this which loads images depending on day of the week, but I also would like to show text and load it from a file, too. I like to use it as todays menu, so the cook uploads text files, like monday.txt tuesday.txt, and does not need to mess up with coding.
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<META HTTP-EQUIV="refresh" CONTENT="60">
<title>LOUNAS</title>
<style type="text/css">
body {
overflow:hidden;
}
</style>
<script type="text/javascript"><!--
var imlocation = "";
function ImageArray (n) {
this.length = n;
for (var i =1; i <= n; i++) {
this[i] = ' '
}
}
image = new ImageArray(7);
image[0] = 'sunday.jpg';
image[1] = 'monday.jpg';
image[2] = 'tuesday.jpg';
image[3] = 'wednsday.jpg';
image[4] = 'thursday.jpg';
image[5] = 'friday.jpg';
image[6] = 'saturday.jpg';
var currentdate = new Date();
var imagenumber = currentdate.getDay();
document.write('<img src="' + imlocation + image[imagenumber] + '"> style="width:100%;height:100%;" border="0" /');
//--></script></head>
<body bgcolor="#000000">
</body>
</html>
You need to use AJAX request in order to read files from the server.
(If your intention is to display the data to client and not self-display site)
You'll need a server and back-end language like PHP, and then you'll need to make an AJAX request to server depend on the day of the week (meaning which url?) and then display the data.
Second, about what you did, using document.write it's not best way, becuase it clear the page after using and all the data that you had will gone (meaning HTML), and also create element this way dosen't work good in all browsers , you should use createElement instead.
Also, you can use CSS to give style to that element instead of doing it via JavaScript

use JavaScript to make a webpage that forwards to a URL which includes the date?

I wanted to make a bookmark that uses today's date in the URL; in other words, when the bookmark is launched, the end of the URL would vary each day. So today's would end in .../2017/1/31 and tomorrow's would end in .../2017/2/1.
I thought it might be easiest to just make a barebones HTML page that includes an inline JavaScript to get current year, month, and date and append it to the main URL (which never changes). Does this make sense? Is there an easier way to accomplish this?
I'm okay with HTML elements, but kind of clueless about JavaScript; I literally copied a snippet from another stackoverflow answer that sounded decent and put it into my head tags as you can see below, and tried to adapt my URL into the ahref link:
<HTML>
<head>
<script>var d=new Date();</script>
</head>
<body>
<a href="http://wol.org?t="+d.getTime()>Continue</a>
</body>
</HTML>
The following will run without need for clicking any buttons:
<HTML>
<head>
<script>
Date.prototype.yyyymmdd = function() { //returns YYYY/MM/DD
var mm = this.getMonth() + 1; // getMonth() is zero-based
var dd = this.getDate();
return [this.getFullYear(),
(mm>9 ? '' : '0') + mm,
(dd>9 ? '' : '0') + dd
].join('/');
};
var date = new Date();
window.location.href = "your.url.com/" + date.yyyymmdd();
</script>
</head>
<body>
</body>
</HTML>
Date function from this answer: https://stackoverflow.com/a/3067896/3803371
Note I usually don't condone modification of native prototypes, but I'm feeling lazy today.
You cannot use javascript expression outside script tag. So you cannot call d.getTime like this. Instead of you can do this:
<a id="c" href="">Continue</a>
<script>
(function() { // wait for window load
var d=new Date();
var a = document.getElementById("c");
a.href = "http://wol.org?t="+d.getTime();
})();
</script>
There's a couple problems with your code. First, you're mixing HTML and JavaScript. JavaScript can only go between the <script> tags. Also, the script needs to go below your link you want to modify.
If you want to get the date in the form year/month/day you'll have to do some modification to the date string you get back from your Date object. What I do below is basically get the date string and split it by / into an array. I know the first index is the month, second is the day, and third gives me the year. I store each of those into a variable to use and rearrange later.
I then had to locate the <a> element using getElementById() and then I changed the href value using my date variables.
var dateString = new Date().toLocaleDateString();
var dateArray = dateString.split('/');
var month = dateArray[0];
var day = dateArray[1];
var year = dateArray[2];
var dateOrder = year + "/" + month + "/" + day;
console.log(dateOrder);
var a = document.getElementById('link');
a.href += dateOrder;
<a id="link" href="http://wol.org?t=">Continue</a>
<script>
// Javascript from above goes here
</script>

Call function which was load in footer

In a php foreach, I would convert a date using the client timezone.
Actually, it doesn't work:
<html>
<body>
<?php foreach ($topic as $post) { ?>
<span id="date">
<script type='text/javascript'>
document.write(window.date('<?php echo $date;?>'));
</script>
</span>
<?php } ?>
<script type='text/javascript'>
function date(VarDate) {
var b = VarDate.split(/[: ]/g);
var m = {jan:0, feb:1, mar:2, apr:3, may:4, jun:5, jul:6, aug:7, sep:8, oct:9, nov:10, dec:11};
var isoTime = Date.UTC(b[7], m[b[1].toLowerCase()], b[2], b[3], b[4], b[5]);
var date = new Date(isoTime).toLocaleDateString(navigator.language, {day: '2-digit', month:'2-digit', year:'2-digit'});
var time = new Date(isoTime).toLocaleTimeString(navigator.language, {hour: '2-digit', minute:'2-digit'});
return time + ' ยท ' + date;
}
</script>
</body>
</html>
It works when I put the function before the loop but scripts are launched in footer to optimize the loading.
I'm looking for something better. Sorry for my poor english.
As Sanchit said, you could rewrite the
document.write(window.date('<?php echo $date;?>'));
part, as follows (if you use jQuery)
$(document).ready(function(){
// write here where needed: using jQuery the $('') approach is the easiest way
});
In this way, the script is executed once all the scripts are loaded in the page and all the functions are defined. Anyway, in this case if you move this function definition in the footer the bytes saved are partially used by the overhead required to fire the script when the page is ready.
Depending on the number of $post in the $topic, this approach could slow down the loading time. Maybe, it would be faster to put the definition in an external Javascript (so it can be cached by the browser) included in the header of the page.

How can I pass PHP variable to Datepicker in jQuery?

I'm trying to set the default date in datepicker with a variable I pass into the html from PHP. Here's a simplified version of both my control file and form:
control file:
<?php
function render($template, $values = []) {
// extract variables into local scope
extract($values);
// render template
require("$template");
}
$default_date = date("m/d/Y") ;
$default_date = strtotime($default_date);
$default_date = $default_date + 604800;
$default_date = date("Y,m-1,d",$default_date);
render("index_month2_form.php",['default_date'=> $default_date]);
?>
and here is the form:
<!doctype html>
<html lang="en">
<head>
<?php print "$default_date"; ?>
<meta charset="utf-8">
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="jqueryui/css/swanky-purse/jquery-ui-1.10.4.custom.css">
<script src="/jqueryui/jquery-1.11.1.min.js"> </script>
<script src="jqueryui/js/jquery-ui-1.10.4.custom.min.js"></script>
<script type="text/javascript">
$(function() {
$("#mydate").datepicker ({
onSelect: function(dateText, inst) {
var dateAsString = dateText;
var date = $('#mydate').val();
}
})
//.datepicker("setDate",new Date());
.datepicker("setDate",new Date(2014,10-1,17));
});
</script>
</head>
<body>
<p>Date: <input type="text" id="mydate"></p>
</body>
</html>
If I use the commented line for setDate I get the current date. If I use the line I have I get the date 7 days forward. When I print $default_date at the top of the form I get 2014,10-1,17 but I can't firgure out of way to pass this into the script. Others have suggested using
The better solution is to assign returned PHP date variable to jQuery variable.
This can be done by following
var phpDate = "<?php echo $default_date; ?>";
Now, you need to assign that to datepicker
$("#mydate").datepicker("setDate",phpDate);
This works...
using echo is the way to go.
I would rather put it in the script rather than the input
I assume $default_date === "2014,10-1,17"
$(function() {
$("#mydate").datepicker ({
onSelect: function(dateText, inst) {
var dateAsString = dateText;
var date = $('#mydate').val();
}
})
//.datepicker("setDate",new Date());
.datepicker("setDate",new Date(
<?php
$date = explode(',', $default_date);
echo $date[0] . ',' . $date[1] . ',' . $date[2];
?>
));
};
edit:
As rss81 noticed it, destructuring the string to rebuild the exact same string is quite dumb. I dont know what I was thinking...
Nevertheless I'll let it like this for educational purpose.
exploding the string enables us to get an array of the string of each chunk separated by a coma. You could use it to reorder the string. For instance if you wanted to transform "2014,10-1,17" to "10-1,2014,17" that would be done by echo $date[1].','.$date[0].','.$date[2]
Echo enables us to output the html page as we like, making it dynamic. So here we are preprocessing the date argument of the .datepicker() by php.
Just give the input the relative value
<input type="text" id="mydate" value="<?php echo $yourdate; ?>">
This will init datepicker with you date value
Hope this helped and my apologies if this is not what you were looking for
You can use <?php echo not in the script, but in the body, in some display:none element with id. And then just to get the date with javascript from that element and set to datapicker
You could pass the $default_date value in a data attribute of an html element. For example:
<p id="myDate" data-date="<?php echo $default_date; ?>"></p>
After that you can extract it with with Jquery like this:
var date = $("#myDate").data("date");
You need to set date format in javascript part because it's create and problem with date.
You can set it given below
$("#datepicker").datepicker("option", "dateFormat", "yy-mm-dd ");

Categories

Resources