Iam getting offsetwidth of an div tag. Below is code.
<body>
<div id="marqueeborder" onmouseover="pxptick=0" onmouseout="pxptick=scrollspeed">
<div id="marqueecontent">
<?php
// Original script by Walter Heitman Jr, first published on http://techblog.shanock.com
// List your stocks here, separated by commas, no spaces, in the order you want them displayed:
$stocks = "idt,iye,mill,pwer,spy,f,msft,x,sbux,sne,ge,dow,t";
// Function to copy a stock quote CSV from Yahoo to the local cache. CSV contains symbol, price, and change
function upsfile($stock) { copy("http://finance.yahoo.com/d/quotes.csv?s=$stock&f=sl1c1&e=.csv","stockcache/".$stock.".csv"); }
foreach ( explode(",", $stocks) as $stock ) {
// Where the stock quote info file should be...
$local_file = "stockcache/".$stock.".csv";
// ...if it exists. If not, download it.
if (!file_exists($local_file)) { upsfile($stock); }
// Else,If it's out-of-date by 15 mins (900 seconds) or more, update it.
elseif (filemtime($local_file) <= (time() - 900)) { upsfile($stock); }
// Open the file, load our values into an array...
$local_file = fopen ("stockcache/".$stock.".csv","r");
$stock_info = fgetcsv ($local_file, 1000, ",");
// ...format, and output them. I made the symbols into links to Yahoo's stock pages.
echo "<span class=\"stockbox\">".$stock_info[0]." ".sprintf("%.2f",$stock_info[1])." <span style=\"";
// Green prices for up, red for down
if ($stock_info[2]>=0) { echo "color: #009900;\">↑"; }
elseif ($stock_info[2]<0) { echo "color: #ff0000;\">↓"; }
echo sprintf("%.2f",abs($stock_info[2]))."</span></span>\n";
// Done!
fclose($local_file);
}
?>
<span class="stockbox" style="font-size:0.6em">Quotes from Yahoo Finance</span>
</div>
</div>
</body>
below is the javascript function which will be called onlaod of the page.
<script type="text/javascript">
// Original script by Walter Heitman Jr, first published on http://techblog.shanock.com
// Set an initial scroll speed. This equates to the number of pixels shifted per tick
var scrollspeed=2;
var pxptick=scrollspeed;
function startmarquee(){
alert("hi");
// Make a shortcut referencing our div with the content we want to scroll
var marqueediv=document.getElementById("marqueecontent");
alert("marqueediv"+marqueediv);
alert("hi"+marqueediv.innerHTML);
// Get the total width of our available scroll area
var marqueewidth=document.getElementById("marqueeborder").offsetWidth;
alert("marqueewidth"+marqueewidth);
// Get the width of the content we want to scroll
var contentwidth=marqueediv.offsetWidth;
alert("contentwidth"+contentwidth);
// Start the ticker at 50 milliseconds per tick, adjust this to suit your preferences
// Be warned, setting this lower has heavy impact on client-side CPU usage. Be gentle.
var lefttime=setInterval("scrollmarquee()",50);
alert("lefttime"+lefttime);
}
function scrollmarquee(){
// Check position of the div, then shift it left by the set amount of pixels.
if (parseInt(marqueediv.style.left)>(contentwidth*(-1)))
marqueediv.style.left=parseInt(marqueediv.style.left)-pxptick+"px";
// If it's at the end, move it back to the right.
else
marqueediv.style.left=parseInt(marqueewidth)+"px";
}
window.onload=startmarquee();
</script>
when iam running the above code on server, iam getting javascript error as "object required" at line 46 also the alert("marqueediv"+marqueediv); is "marqueedivnull" after that alert iam getting the javascript error.
Here my question is, did the div tag is not getting recognized?why?
so that only it is getting as null object, how can i resolved this?
Thanks.
You are calling startmarquee immediately and trying to assign its return value (undefined) to window.onload.
Presumably the script appears in the <head> and this the div does not exist at the time you run it.
Assign the function to onload, not its return value.
window.onload=startmarquee;
You could copy the script and put it before the body closing tag and remove window.onload=startmarquee(); thus making sure all elements have been loaded and accessible
Just like #Quentin said, that element with the id might not have been loaded into the DOM when you referenced it
Related
I have created a php page to display a image from a set of five images. The image is displayed based on the data read from a text file.Another application is continuously updating data in that text file.So my php page need to read data from that file whenever the file is updated and display image based on that data. I created a infinite loop to read data. But when i tried to access the php page from a browser , it is not loading because of the infinite loop.
$myfile1 = fopen("readfile.txt", "r") or die("Unable to open file!");
$readJsonData = fread($myfile1,filesize("readfile.txt"));
fclose($myfile1);
$obj = json_decode($readJsonData);
$urllogo = 'tatalogo.png';
if(($obj->{"FrontLeft"}) == "TRUE")
{
$url = 'images/FrontLeft.png';
}
else if(($obj->{"FrontRight"}) == "TRUE")
{
$url = 'images/FrontRight.png';
}
else if(($obj->{"RearLeft"}) == "TRUE")
{
$url = 'images/RearLeft.png';
}
else if(($obj->{"RearRight"}) == "TRUE")
{
$url = 'images/RearRight.png';
}
else
{
$url = 'images/Normal.png';
}
// infinite loop
while(1)
{
//reading from the file and refreshing the page.
}
In PHP Set header like this to refresh the php page
header("Refresh: 5;url='pagename.php'");
In HTML Head tag
<html>
<head>
<meta http-equiv="refresh" content="5;URL='pagename.php'">
</head>
</html>
<?php
Your php script here..
?>
Using Javascript
<script type="text/javascript>
window.setInterval(function(){
reload_page();
}, 5000);
//Here 5000 in miliseconds so for 5 seconds use 5000
function reload_page()
{
window.location = 'pagename.php';
}
The most reasonable way to do it would be to use the client side to refresh the page.
Get rid of all that infinite loop stuff on the PHP side. PHP will only output the image as it stands at the moment it was generated.
On the client side you could do something as simple as:
<META http-equiv="refresh" content="5;"> to force a refresh every 5 seconds.
If you only want to update when the file is updated you have to get more advanced. You could do an ajax call that checks if the file has changed and if so it refreshes. Websockets would be another option.
You could possibly do some nasty hack on the PHP side to make it work using ob_flush and sleep and header within a loop that checks to see if the file has changed but this will cause you to lose sleep once you realize what you've done. As pointed out below, this would never work.
I have a li and inside that i have a div class="reload" that have some content that should be reloaded for every 10 sec.
<li class="b1">
<div class="reload">
</div>
</li><!--col-->
So therefore i have got a script that does just that.
<script type="text/javascript">
$('.b1').children('.reload').load('php/reload/reload.php'); // load the content at start
window.setInterval(function(e) {
$('.b1').children('.reload').load('php/reload/reload.php'); // reload the content every 10 sec
}, 10000);
In the reload.php i get some content from a database. It looks like this, sort of..
<?php
// login info
require("../../connection_to_database_login.php");
// My query
$result = mysqli_query($l,'SELECT * FROM abcd WHERE efg=1 LIMIT 1');
// include some stuff
$r = mysqli_fetch_row($result);for ($p = 0; $p < $r[4]; ++$p){include("../some/stuff_$p.php");};
// include a random picture script or just load a picture
if ($r[4] == 0){include ('getRandPic.php');}
else {echo ('<img src="images/picture.png" />');}
?>
So far so good.. everything works.
The getRandPic.php file.. select one random picture from a folder
<?php
$img_dir = "images/images";
$images = scandir($img_dir);
$html = array();
foreach($images as $img) {
if($img === '.' || $img === '..') {continue;}
if ( (preg_match('/.jpg/',$img)) || (preg_match('/.gif/',$img)) || (preg_match('/.tiff/',$img)) || (preg_match('/.png/',$img)) ) {
$html[] .= '<img class="img-responsive" src="'.$img_dir.$img.'" />';
}
else { continue; }
};
echo $html[rand(0,6)];
?>
So this works ok.
But the thing is, i want to check if it shall "include a random picture script or just load a picture" every 5sec.
Therefore i need to check "if ($r[4] == 0)" every 5 sec.
So my question is: Is there any other way to do that?
As you asked in the comment... This is a rough guide only. You will have to develop and write your own code based on this guide.
Step 1a: optional
Make an ajax call from your webpage to the server. to get image file names.
Step 1b:
On server side in php file perform DB operation.
Let assume you have a table imageTable and column name images so you would read from DB using query SELECT images FROM imageTable
You will have to change the query, add condition (e.g. all images with animal and cute tags) to it and if you want limit the number of files that you want to randomize then you will have to add that as well.
Step 2:
Once you read from DB, as you are already doing, read all image names and put it in json format (json_encode). I personally prefer json. If you prefer, you can also return all names in simple string where names are separated by comma.
Step 3:
Store your response in JS.
var imagesArray = new Array();
$.ajax({
type: 'post',
url: pathtophpfile,
success: function(htmll) {
// get object with all data
imagesArray= JSON.parse(htmll);
},
});
Step 4:
Once you have it in your js object named imagesArray, use setInetval to perform task every 5 seconds.
Read a random value from 0 to imagesArrays length, and change the source of your image tag, <img class="img-responsive" src="+ randomimage +" />
Periodic updater will do your task.
Use ajax framework, it will reduce your db connection burden at the server side.
Have a look at it. It is a simple and nice way to achieve your task.
http://prototypejs.org/doc/latest/ajax/Ajax/PeriodicalUpdater/
I have bits of code I want to throw in to my site, and provisioned a space right after <body> using 'flairs' (divs) that sit outside the design. Here's the code:
//Add Flair Containers as needed
if($flairs>0){
echo "<!--Flair Graphics (if needed)-->\n";
while($fQty = --$flairs+1){ //-- subracts 1, +1 accounts for 1 being 0
$flair = array($flair1, $flair2, $flair3);
foreach($flair as $flairCode){
echo "<div id=\"flair-".$fQty++."\">".$flairCode."</div>\n";
};
};
};
It prints correctly, where content = $flair1, $flair2, and so on.
<div id="flair-1">Content1</div>
<div id="flair-2">Content2</div>
<div id="flair-3">Content3</div>
But if $flair2/$flair3 is empty, it still prints a div. How can I fix this?
Within your foreach loop you can check if the value is empty and continue (i.e. skip) to the next value if it is.
Like so:
if($flairs>0){
echo "<!--Flair Graphics (if needed)-->\n";
while($fQty = --$flairs+1){ //-- subracts 1, +1 accounts for 1 being 0
$flair = array($flair1, $flair2, $flair3);
foreach($flair as $flairCode){
if (empty($flairCode)) continue;
echo "<div id=\"flair-".$fQty++."\">".$flairCode."</div>\n";
};
};
};
I suspect that you could simply prepend if($flairCode) to your echo statement. That would make your inner loop:
foreach($flair as $flairCode){
if($flairCode) echo "<div id=\"flair-".$fQty++."\">".$flairCode."</div>\n";
};
Some points to note:
Since the $flair array will always be the same, construct it outside of the loop (this will let you evaluate the condition only once too.
Using $fQty++ is not enough to guarantee unique ID's, especially since every time it hits the while the value is reset. I suggest $fQty should not be part of the while condition and simply stay as an independent tally.
Stop using double-quotes. They're slow.
An issue with a dropdown menu. The problem isn't the menu code itself ie ul..etc, but a php chat program im currently embedding. After inserting this code to embed the chat box which appears with no errors the ability to use the ul dropdown link is disabled. The embedded php is in an entirely seperate div from the menu which is located in the #zonebar div.
the embedded code <?php $chat->printChat(); ?> which is in a specific div.
The thing is when i remove this code the dropdown menu buttons work again..
To be more specific the only php code in my html file with appropriate htaccess which allows me to use php in an html document is..
the code below is located at the very top of my page above all tags
<?php
require_once dirname(__FILE__)."/src/phpfreechat.class.php";
$params = array();
$params["serverid"] = md5(__FILE__); // calculate a unique id for this chat
$params["title"] = "A simple chat with user's parameters";
$params["frozen_nick"] = true; // do not allow to change the nickname
$params["shownotice"] = 0; // 0 = nothing, 1 = just nickname changes, 2 = connect/quit, 3 = nick + connect/quit
$params["max_nick_len"] = 20; // nickname length could not be longer than 10 caracteres
$params["max_text_len"] = 300; // a message cannot be longer than 50 caracteres
$params["max_channels"] = 1; // limit the number of joined channels tab to 3
$params["refresh_delay"] = 2000; // chat refresh speed is 10 secondes (10000ms)
$params["max_msg"] = 15; // max message in the history is 15 (message seen when reloading the chat)
$params["height"] = "230px"; // height of chat area is 230px
$params['admins'] = array('daddo' => '1234', 'berthill' => '1234');
$params["debug"] = false; // activate debug console
$chat = new phpFreeChat( $params );
?>
and then the code in the specific div
<?php $chat->printChat(); ?>
link directly the html file without any php content
edited out address after fix
link with the php code embedded
I am going to wager a guess at this since looking through about a dozen javascript files is not something I really want to do.
Your dropdown menu uses jQuery... which is great.
Your chat uses Prototype... also great.
They are most likely not playing well together. You can try doing this:
var $j=jQuery.noConflict();
$j(document).ready(function(){
$j("#zone-bar li em").click(function() {
var hidden = $j(this).parents("li").children("ul").is(":hidden");
$j("#zone-bar>ul>li>ul").hide()
$j("#zone-bar>ul>li>a").removeClass();
if (hidden) {
$j(this)
.parents("li").children("ul").toggle()
.parents("li").children("a").addClass("zoneCur");
}
});
});
It may or may not work, but using $j instead of $ may fix the issue.
NOTE: This is a long question. I've explained all the 'basics' at the top and then there's some further (optional) information for if you need it.
Hi folks
Basically last night this started happening at about 9PM whilst I was trying to restructure my code to make it a bit nicer for the designer to add a few bits to. I tried to fix it until 2AM at which point I gave up. Came back to it this morning, still baffled.
I'll be honest with you, I'm a pretty bad Javascript developer. Since starting this project Javascript has been completely new to me and I've just learn as I went along. So please forgive me if my code structure is really bad (perhaps give a couple of pointers on how to improve it?).
So, to the problem: to reproduce it, visit http://furnace.howcode.com (it's far from complete). This problem is a little confusing but I'd really appreciate the help.
So in the second column you'll see three tabs
The 'Newest' tab is selected by default. Scroll to the bottom, and 3 further results should be dynamically fetched via Ajax.
Now click on the 'Top Rated' tab. You'll see all the results, but ordered by rating
Scroll to the bottom of 'Top Rated'. You'll see SIX results returned.
This is where it goes wrong. Only a further three should be returned (there are 18 entries in total). If you're observant you'll notice two 'blocks' of 3 returned.
The first 'block' is the second page of results from the 'Newest' tab. The second block is what I just want returned.
Did that make any sense? Never mind!
So basically I checked this out in Firebug. What happens is, from a 'Clean' page (first load, nothing done) it calls ONE POST request to http://furnace.howcode.com/code/loadmore .
But every time you load a new one of the tabs, it makes an ADDITIONAL POST request each time where there should normally only be ONE.
So, can you help me? I'd really appreciate it! At this point you could start independent investigation or read on for a little further (optional) information.
Thanks!
Jack
Further Info (may be irrelevant but here for reference):
It's almost like there's some Javascript code or something being left behind that duplicates it each time. I thought it might be this code that I use to detect when the browser is scrolled to the bottom:
var col = $('#col2');
col.scroll(function(){
if (col.outerHeight() == (col.get(0).scrollHeight - col.scrollTop()))
loadMore(1);
});
So what I thought was that code was left behind, and so every time you scroll #col2 (which contains different data for each tab) it detected that and added it for #newest as well. So, I made each tab click give #col2 a dynamic class - either .newestcol, .featuredcol, or .topratedcol. And then I changed the var col=$('.newestcol');dynamically so it would only detect it individually for each tab (makin' any sense?!). But hey, that didn't do anything.
Another useful tidbit: here's the PHP for http://furnace.howcode.com/code/loadmore:
$kind = $this->input->post('kind');
if ($kind == 1){ // kind is 1 - newest
$start = $this->input->post('currentpage');
$data['query'] = "SELECT code.id AS codeid, code.title AS codetitle, code.summary AS codesummary, code.author AS codeauthor, code.rating AS rating, code.date,
code_tags.*,
tags.*,
users.firstname AS authorname,
users.id AS authorid,
GROUP_CONCAT(tags.tag SEPARATOR ', ') AS taggroup
FROM code, code_tags, tags, users
WHERE users.id = code.author AND code_tags.code_id = code.id AND tags.id = code_tags.tag_id
GROUP BY code_id
ORDER BY date DESC
LIMIT $start, 15 ";
$this->load->view('code/ajaxlist',$data);
} elseif ($kind == 2) { // kind is 2 - featured
So my jQuery code sends a variable 'kind'. If it's 1, it runs the query for Newest, etc. etc.
The PHP code for furnace.howcode.com/code/ajaxlist is:
<?php // Our query base
// SELECT * FROM code ORDER BY date DESC
$query = $this->db->query($query);
foreach($query->result() as $row) {
?>
<script type="text/javascript">
$('#title-<?php echo $row->codeid;?>').click(function() {
var form_data = {
id: <?php echo $row->codeid; ?>
};
$('#col3').fadeOut('slow', function() {
$.ajax({
url: "<?php echo site_url('code/viewajax');?>",
type: 'POST',
data: form_data,
success: function(msg) {
$('#col3').html(msg);
$('#col3').fadeIn('fast');
}
});
});
});
</script>
<div class="result">
<div class="resulttext">
<div id="title-<?php echo $row->codeid; ?>" class="title">
<?php echo anchor('#',$row->codetitle); ?>
</div>
<div class="summary">
<?php echo $row->codesummary; ?>
</div>
<!-- Now insert the 5-star rating system -->
<?php include($_SERVER['DOCUMENT_ROOT']."/fivestars/5star.php");?>
<div class="bottom">
<div class="author">
Submitted by <?php echo anchor('auth/profile/'.$row->authorid,''.$row->authorname);?>
</div>
<?php
// Now we need to take the GROUP_CONCATted tags and split them using the magic of PHP into seperate tags
$tagarray = explode(", ", $row->taggroup);
foreach ($tagarray as $tag) {
?>
<div class="tagbutton" href="#">
<span><?php echo $tag; ?></span>
</div>
<?php } ?>
</div>
</div>
</div>
<?php }
echo " ";?>
<script type="text/javascript">
var newpage = <?php echo $this->input->post('currentpage') + 15;?>;
</script>
So that's everything in PHP. The rest you should be able to view with Firebug or by viewing the Source code. I've put all the Tab/clicking/Ajaxloading bits in the tags at the very bottom. There's a comment before it all kicks off.
Thanks so much for your help!
I think you're right to suspect this code block:
var col = $('#col2');
col.scroll(function(){
if (col.outerHeight() == (col.get(0).scrollHeight - col.scrollTop()))
loadMore(1);
});
My take on this is that you keep adding additional event handlers (duplicates, essentially) each time you run this code. You need to remove (unbind) the existing event handlers with every tab click so that you can be sure that it's only firing once:
$('#col2').unbind();
var col = $('#col2');
col.scroll(function(){
if (col.outerHeight() == (col.get(0).scrollHeight - col.scrollTop()))
loadMore(1);
});
Or some such thing. See http://api.jquery.com/unbind/
$('.featurecol'); , $('.topratedcol'); and $('.newestcol'); all refer to the same column and division (<div>). As such, whenever you switch pages, you need to unbind the old scroll before rebinding the new scroll handler. (Or else you'll be appending another scroll handler and getting multiple requests sent, like now)
You can do this by adding an unbind as follows:
var col = $('.newestcol');
col.unbind('scroll');
col.scroll(function(){
if (col.outerHeight() == (col.get(0).scrollHeight - col.scrollTop()))
loadMore(1);
});
You need to do this for all of the columns as they load (code/newest, code/toprated and code/featured).
It could also be
$('#col3').fadeOut('slow', function() {
as the ajax loads there... n number of times as it fades out it calls another ajax request.
not saying its the defenet answer but something looking into...