Call function which was load in footer - javascript

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.

Related

how to using javascript function in smarty tpl

i have a fake visitor's counter script which code in javascript but i want to use it in smarty tpl file i am try to do it but its not displaying where i want. the script code is below
<!--Simply copy and paste it where you wish the counter to appear.-->
<SCRIPT language="JavaScript" type="text/javascript">
// counter - from http://rainbow.arch.scriptmania.com/scripts
function fakecounter(){
//decrease/increase counter value (depending on perceived popularity of your site!)
var decrease_increase=2460
var counterdate=new Date()
var currenthits=counterdate.getTime().toString()
currenthits=parseInt(currenthits.substring(2,currenthits.length-4))+decrease_increase
document.write("You are visitor # <b>"+currenthits+"</b> to my site!")
}
fakecounter()
</script>
and i am trying to using it in after </script> .
This script should work without a problem. If you put it in clean Smarty template file you get information similar to:
You are visitor # 945155 to my site!
However in older versions of smarty you need to use {literal} to use JavaScript, so your code should look like this:
<!--Simply copy and paste it where you wish the counter to appear.-->
<SCRIPT language="JavaScript" type="text/javascript">
{literal}
// counter - from http://rainbow.arch.scriptmania.com/scripts
function fakecounter() {
//decrease/increase counter value (depending on perceived popularity of your site!)
var decrease_increase = 2460
var counterdate = new Date()
var currenthits = counterdate.getTime().toString()
currenthits = parseInt(currenthits.substring(2, currenthits.length - 4)) + decrease_increase
document.write("You are visitor # <b>" + currenthits + "</b> to my site!")
}
fakecounter()
{/literal}
</script>

PHP Include inside DIV Styles Background

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>

External Javascript File Fetch?

I am currently using this code:
var wordRandomizer = {
run: function (targetElem) {
var markup = this.createMarkup();
targetElem.appendChild(markup);
},
createMarkup: function () {
var that = this;
var frag = document.createDocumentFragment();
this.elem = document.createElement('span');
var button = document.createElement('button');
button.innerText = 'Change Item';
button.addEventListener('click', function () {
that.changeItem();
});
frag.appendChild(this.elem);
frag.appendChild(button);
return frag;
},
changeItem: function () {
var rand = this.getRandInt(1, this.items.length) - 1;
console.log(rand);
this.elem.innerText = this.items[rand];
},
getRandInt: function (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
},
items: ['itemA', 'itemB', 'itemC', 'itemD']
};
wordRandomizer.run(document.body);
I code is a button which when pressed grabs one of the items in the list. However, I don't want the items to show on the same page as the generator as people simply look at the source code. How can I make it so once the button is pressed it grabs the random item from another location where people cannot view them all using the source code.
If it helps, you can see the code in action here - http://jsbin.com/ESOdELU/1/edit
I will give you a solution using PHP since it is a free scripting language and is the most likely to be supported by a host or default web server...
For starters, here is the code to include jquery and the basic AJAX script
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/JavaScript">
$(document).ready(function(){
$("#generate").click(function(){
$("#madlibs p").load("script.php");
});
});
</script>
Here is the code for script.php
<?php
header("Cache-Control: no-cache");
// For testing you can use an inline array like the lines below
// Just remove the comment slashes "//" from the beginning of the line
// and comment out the external declarations
//$actors = array('Denzel Washington','Michael J. Fox','Jim Carey','Boris Kodjoe');
//$roles = array('Mental Patient','Homeless Musician','Drag Queen Detective','Tormented Mathematician');
// In production, you would put these in a text file or a database.
// For $actors, put an entry on each line of a text file and save it as 'leads.txt'
// Do the same with a separate file for $roles (roles.txt).
$actors = file("leads.txt");
$roles = file("roles.txt");
// This selects a random element of each array on the fly
echo $prefixes[rand(0,count($actors)-1)] . " stars as a "
. $suffixes[rand(0,count($roles)-1)] . " in the next blockbuster film.";
// Example output:
// Michael J. Fox stars as a Tormented Mathematician in the next blockbuster film.
?>
Put this in the body of your page and be sure to style everything up for display.
<body>
<div id="madlibs"><p> </p></div>
<button id="generate">Surprise Me!</button>
</body>
A couple of notes:
- You can include your basic layout HTML in the script.php file and then would only need the ID of the DIV in which you will be displaying the result $("#madlibs")
You can use any server side language to achieve the same result, just swap out the external file call to the appropriate name and extension (.asp, .cfm, etc.)
Here is a link to the original tutorial that helped me with a similar project:
http://www.sitepoint.com/ajax-jquery/
I hope this helps. Sorry, but I couldn't come up with a purely Java of JavaScript solution on lunch.

Load script only for returning USER - once!

I need a script which will load another script only for returning user!
The script which will need to load this script
<a href="http://www.w3.org/" >W3C</a>
I have a script which loads a popup only for new customers:
<SCRIPT LANGUAGE="JavaScript">
<!-- Script courtesy of http://www.web-source.net - Your Guide to Professional Web Site Design and Development
function GetCookie(name) {
var arg=name+"=";
var alen=arg.length;
var clen=document.cookie.length;
var i=0;
while (i<clen) {
var j=i+alen;
if (document.cookie.substring(i,j)==arg)
return "here";
i=document.cookie.indexOf(" ",i)+1;
if (i==0) break;
}
return null;
}
var visit=GetCookie("COOKIE1");
if (visit==null){
var expire=new Date();
window.name = "thiswin";
newwin=open("yourpagename.html", "dispwin",
"width=450,height=455,scrollbars=yes,menubar=no");
expire=new Date(expire.getTime()+7776000000);
document.cookie="COOKIE1=here; expires="+expire;
}
// -->
</SCRIPT>
Yet I need the script only to load once for the returning customers every 1 day
thanks again
7776000000 equals 90 days.
Make the cookie expire every 24 hours [86400000] and you get once a day.

Why won't my script update my div dynamically like it's supposed to?

<html>
<head>
<style type="text/css">
body {
background-color: #000000;
font-family: Arial, Helvetica, sans-serif;
font-size: 20px;
text-align: center;
color: #FFFFFF;
}
</style>
<script type="text/javascript" src="jquery-1.4.js"></script>
<script type="text/javascript">
function sleep(ms)
{
var dt = new Date();
dt.setTime(dt.getTime() + ms);
while (new Date().getTime() < dt.getTime());
}
function update() {
while (0 < 1) {<?php $contents = file_get_contents("my url here");
?>
var count = <?php echo $contents ?>;
document.getElementById('div').innerHTML = count;
sleep(1500);
}
}
</script>
</head>
<body onload=update()>
<iframe id="iframe" src="my url" style="visibility: hidden;"/>
<table width=100% height=100%>
<tr height=80%>
<td width=100%>
<center>
<div id="div"></div>
</center>
</td>
</tr>
</table>
</body>
</html>
When viewing the source code in-browser, the var is set correctly, but it won't set the content of the div. I am positive that the url the PHP script is pointing to is accurate and contains only a script to grep a number from an external page.
Thanks in advance!
To answer the question, why isn't it running... your onload needs quotes:
<body onload="update()">
but the others have posted better ways to go about it using jquery.
Assuming that the value of file_get_contents("my url here") yields 42 (for example), you are aware that you're creating an infinite loop which will set the content of #div to 42 over and over again every 1.5 seconds? I.e., var count will always, constantly be 42 and won't change, since PHP is evaluated only once on the server.
Furthermore I would suspect that your sleep function could pose a bit of a problem, since it creates another tight loop. I wouldn't be surprised if this script simply blocked the browser without ever updating anything since it's caught in an infinite loop. The way to delay execution in Javascript is to use window.setTimeout or window.setInterval.
I guess what you're looking for is an AJAX solution of some kind, if you would tell us what it is you want to do. Since you're including jQuery (without actually using it), you should have a look at jQuery.get(), coupled with a setInterval to update the div periodically.
Something like:
window.setInterval(function () {
$.get("my url here", function (data) {
$('#div').html(data);
});
}, 1500);
var count = <?php echo $contents ?>;
document.getElementById('div').innerHTML = count;
You are asking the webserver for variable $contents through php, which will always be a static number unless you reload the page. Try using jQuery, as the poster above mentioned.

Categories

Resources