Cannot change src of image with Javascript in some versions of Chrome - php

Never could have imagined that chrome would have been the browser giving me grief, but the slideshow for our new website does not function properly in some versions of Chrome.
The error occurs here:
"mainPicture.src = \''.$directory.$current_pic.'\'; setMarkerPos('.$i.')"
Claiming that I can't modify mainPicture, an id that doesn't exist.
Obviously, other browsers don't have a problem seeing this object.
All help is much appreciated!
.
You can find the page here.
Source code:
<?php
/********************************************************************
* GATHER IMAGES FROM IMAGE DIRECTORY *
********************************************************************/
// Define directory where images are stored
$directory = "../../images/slideshow/";
// Create blank array to store image names
$pic_array = array("");
$num_pics;
// Create number to define position of images in array
$counter = 0;
// Gather pictures from image directory
if(is_dir($directory))
{
// Open directory to view files
if($dh = opendir($directory))
{
// Continue while still files to view
while(($file = readdir($dh)) !== false)
{
// Stop if picture limit of 6 reached
if($counter == 6)
break;
// Gather if object found is file or directory
$file_check = filetype($directory.$file);
// If object is a file, add it to the slideshow
if ($file_check == "file")
{
$extension = substr($file, strpos($file, "."));
if ($extension == ".png" || $extension == ".jpg")
{
$pic_array[$counter] = $file;
$counter++;
}
}
}
}
}
// Determine number of pics gathered
$num_pics = count($pic_array);
?>
<html>
<head>
<link href="scripts/slideshow.css" rel="stylesheet" type="text/css">
<?php
/********************************************************************
* CONTROL BEHAVIORS OF SLIDESHOW *
********************************************************************/
?>
<!-- Begin script to control slideshow -->
<script type = "text/javascript">
var thumbTop = 450; // starting value of thumb.style.top (make sure multiple of increment)
var highestTop = 342; // highest point mask can be on screen ,-, (make sure multiple of increment)
var lowestTop = 450; // lowest point mask can be on screen ,_, (make sure multiple of increment)
var delay = 2; // speed in which slide up and down methods are called
var increment = 5; // value that thumbTop increments with each method call
var intervalUp; // interval for thumb upward movements
var intervalDown; // interval for thumb downward movements
function startThumbSlideUp()
{
window.clearInterval(intervalDown);
intervalUp = window.setInterval(thumbSlideUp,delay);
}
function startThumbSlideDown()
{
window.clearInterval(intervalUp);
intervalDown = window.setInterval(thumbSlideDown,delay);
}
function thumbSlideUp()
{
thumbTop -= increment;
if (thumbTop <= highestTop)
{
thumbTop = highestTop;
window.clearInterval(intervalUp);
}
else
thumbMask.style.top = thumbTop;
}
function thumbSlideDown()
{
// Added to fix issue where images would start from too large a height
if (thumbTop <= highestTop)
thumbTop = highestTop;
thumbTop += increment;
if (thumbTop >= lowestTop)
{
thumbTop = lowestTop;
window.clearInterval(intervalDown);
}
else
thumbMask.style.top = thumbTop;
}
// Move marker above image <pos>
function setMarkerPos(pos)
{
marker.style.left = 600 - (66 * (pos)) + 19;
}
</script>
</head>
<?php
/********************************************************************
* DISPLAY SLIDESHOW *
********************************************************************/
// Start body and make images unhighlightable
echo '<body onselectstart="return false" style="margin: 0px;">';
// Create base value to increment horizontal position of thumbnails
$curr_thumb_left = 595; // (ignore this comment) 660<width of image> - 66<width of thumb> - 10<space between side> // 660
// Create and display main (large) image and image thumbnails
echo '<div id="mask" onmouseout = "startThumbSlideDown()" onmouseover = "startThumbSlideUp();">
';
echo '<img src = "'.$directory.$pic_array[0].'" id = "mainPicture" height = "420" width = "660" style = "z-index: -1; position:absolute;"/>
';
echo '<div id="thumbMask" height="66" width="660" style="z-index: 1; top: 450px; position: absolute;">
';
echo '<img id="marker" src="images/marker.png" height="10" width="10" style="z-index: 2; top: 0px; position: absolute;" onload="setMarkerPos(0);"/>';
// Search through image array, then assign names to and display thumbnails
for ($i=0; $i < $num_pics; $i++)
{
// Point to pic in array
$current_pic = $pic_array[$i];
// Create and display image thumbnails
if ($current_pic !== "")
{
echo '<img src = "'.$directory.$current_pic.'" id = "thumb'.$i.'" height = "50" width = "50" style = "left:'.$curr_thumb_left.'px; top: 10px; border: 3px white solid; position: absolute;" onclick = "mainPicture.src = \''.$directory.$current_pic.'\'; setMarkerPos('.$i.')"/>
';
// Move left value to the left [50px width + (3px padding * 2 sides) + 10px space between = 66px]
$curr_thumb_left -= 66;
}
}
echo '</div>';
echo '</div>';
?>
</body>
</html>

Chrome doesn't make image elements available by just their "id" value; you have to use document.getElementById("mainPicture") to get a reference to the DOM element. That'll work in all browsers anyway, so it's safe to just code it that way.

You are attempting to alter the src of mainPicture as though it were a global variable:
mainPicture.src = '.....';
Try referencing mainPicture by its id instead:
document.getElementById('mainPicture').src = '......';

You're not actually setting what mainPicture is, other browsers must be guessing whereas Chrome is doing what it should. Change:
echo '<img src = "'.$directory.$current_pic.'" id = "thumb'.$i.'" height = "50" width = "50" style = "left:'.$curr_thumb_left.'px; top: 10px; border: 3px white solid; position: absolute;" onclick = "mainPicture.src = \''.$directory.$current_pic.'\'; setMarkerPos('.$i.')"/>
to
echo '<img src = "'.$directory.$current_pic.'" id = "thumb'.$i.'" height = "50" width = "50" style = "left:'.$curr_thumb_left.'px; top: 10px; border: 3px white solid; position: absolute;" onclick = "document.getElementById('mainPicture').src = \''.$directory.$current_pic.'\'; setMarkerPos('.$i.')"/>

Related

how to make a php file work more than once

I have a little generator, It generate a random phone numbers and here is my code.
<?php
limit_phone = 8; //limit phone number
$randomphone = substr(str_shuffle(str_repeat("0123456789", $limit_phone)), 0, $limit_phone); //random numbers
$randomphonecomp = array('010','011','012','015'); // company
$randomphonecomp1 = array_rand($randomphonecomp);
$phonefinaal = $randomphonecomp[$randomphonecomp1] . $randomphone;
echo $phonefinaal. "<br>";
?>
What I want is, when i run this file to work more than one time, means that i want this file to generate automatically with out stop until i stop the page from the browser
You can use a loop to generate specified number of phone numbers, Don't use an infinite loop, it will kill your browser and you will not able to stop the loop.
<?php
$total_numbers = 100;
$i=1;
while($i<=$total_numbers){
$limit_phone = 8; //limit phone number
$randomphone = substr(str_shuffle(str_repeat("0123456789", $limit_phone)), 0, $limit_phone); //random numbers
$randomphonecomp = array('010','011','012','015'); // company
$randomphonecomp1 = array_rand($randomphonecomp);
$phonefinaal = $randomphonecomp[$randomphonecomp1] . $randomphone;
echo $phonefinaal. "<br>";
$i++;
}
?>
As #bcperth said, you most likely need to generate phone numbers using Javascript in the page, it could be something like this:
var divNumbers = document.getElementById("numbers")
var btnStop = document.getElementById("stop")
function generate() {
var randomphone = ""
for(var i = 0; i < 8; ++i) randomphone += Math.floor(Math.random()*10)
var randomcomp = ['010', '011', '012', '015'][Math.floor(Math.random()*4)] + ""
divNumbers.innerHTML += randomcomp + randomphone + "<br>"
}
generate() // first generated number
var intervalGen = setInterval(generate, 2000) // others generated number
function stop() {
clearInterval(intervalGen)
}
btnStop.addEventListener("click", stop)
#stop {
border: 1px solid grey;
padding: 2px 5px;
cursor: pointer;
}
<span id="stop"> STOP </span>
<div id="numbers"></div>
Documentation:
setInterval() - Web APIs | MDN
Math.random() - JavaScript | MDN
Math.floor() - JavaScript | MDN

div and class not showing up

I'm testing a barcode on my website but for some reason the div with the class="b128" which stands for the barcodes is not showing up. If I test the same source code on another website it does show up but with different styling.
Does anyone know how I can make this source code show up and keep the original styling at the same time?
<style>
div.b128{
border-left: 1px black solid;
height: 60px;
}
</style>
<?php
global $char128asc,$char128charWidth;
$char128asc=' !"#$%&\'()*+,-./0123456789:;<=>?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~';
$char128wid = array(
'212222','222122','222221','121223','121322','131222','122213','122312','132212','221213', // 0-9
'221312','231212','112232','122132','122231','113222','123122','123221','223211','221132', // 10-19
'221231','213212','223112','312131','311222','321122','321221','312212','322112','322211', // 20-29
'212123','212321','232121','111323','131123','131321','112313','132113','132311','211313', // 30-39
'231113','231311','112133','112331','132131','113123','113321','133121','313121','211331', // 40-49
'231131','213113','213311','213131','311123','311321','331121','312113','312311','332111', // 50-59
'314111','221411','431111','111224','111422','121124','121421','141122','141221','112214', // 60-69
'112412','122114','122411','142112','142211','241211','221114','413111','241112','134111', // 70-79
'111242','121142','121241','114212','124112','124211','411212','421112','421211','212141', // 80-89
'214121','412121','111143','111341','131141','114113','114311','411113','411311','113141', // 90-99
'114131','311141','411131','211412','211214','211232','23311120' ); // 100-106
////Define Function
function bar128($text) { // Part 1, make list of widths
global $char128asc,$char128wid;
$w = $char128wid[$sum = 104]; // START symbol
$onChar=1;
for($x=0;$x<strlen($text);$x++) // GO THRU TEXT GET LETTERS
if (!( ($pos = strpos($char128asc,$text[$x])) === false )){ // SKIP NOT FOUND CHARS
$w.= $char128wid[$pos];
$sum += $onChar++ * $pos;
}
$w.= $char128wid[ $sum % 103 ].$char128wid[106]; //Check Code, then END
//Part 2, Write rows
$html="<table cellpadding=0 cellspacing=0><tr>";
for($x=0;$x<strlen($w);$x+=2) // code 128 widths: black border, then white space
$html .= "<td><div class=\"b128\" style=\"border-left-width:{$w[$x]};width:{$w[$x+1]}\"></div>";
return "$html<tr><td colspan=".strlen($w)." align=center><font family=arial size=2><b>$text</table>";
}
?>
<?php
$test = "12345";
echo '<div style="border:3px double #ababab; padding:5px;margin:5px auto;width:135px;">';
echo bar128(stripslashes($test));
echo '</div>';
?>
You aren't closing most of your tags. Try this:
$html = "<table cellpadding=0 cellspacing=0><tr>";
for ($x = 0; $x < strlen($w); $x += 2) // code 128 widths: black border, then white space
$html .= "<td><div class=\"b128\" style=\"border-left-width:{$w[$x]};width:{$w[$x+1]}\"></div></td>";
return "$html</tr><tr><td colspan=" . strlen($w) . " align=center><font family=arial size=2><b>$text</b></font></td></tr></table>";

Rating system and CSS sprites

I have implemented three star rating system based on popularity count in my website, but now my client wants to change colors of those three stars (default blue) to red, blue and green which shows the (degree of) popularity.
I've implemented this star rating system using CSS sprites, where I included two star images - golden and gray, in one sprite and displaying these using some logic. Works fine for one color, but how to implement three colours for each star?
HTML
<div class="star-box">
<li>
<span class="stars"><?php echo $position;?></span>
</li>
</div>
PHP
if( !isset($_SESSION['ranking']) || $_SESSION['ranking']['points'] <= 1000 ) {
if( !isset($_SESSION['ranking']['points']) || $_SESSION['ranking']['points'] == '' ) {
$position = '0px';
$position = 0.00;
} else {
$position = ($_SESSION['ranking']['points'] * 0.14).'px';
$position = 0.75;
}
$str1 = 'class="active" ';
$str1 .= ' style="background-position:'.$position.' 9px;"';
}
if( $_SESSION['ranking']['points'] > 1000 && $_SESSION['ranking']['points'] <= 5000 ) {
if( !isset($_SESSION['ranking']['points']) || $_SESSION['ranking']['points'] == '' ) {
$position = '0px';
$position = 0.00;
} else {
$position = ($_SESSION['ranking']['points']*0.035).'px';
$position = 1.40;
}
}
jQuery
$(function() {
$('span.stars').stars();
});
$.fn.stars = function() {
return $(this).each(function() {
// get the value
var val = parseFloat($(this).html());
// make sure that the value is in (0 - 5) range, multiply to get width
val = Math.round(val * 4) / 4;
var size = Math.max(0, (Math.min(5, val))) * 16;
// create stars holder
var $span = $('<span />').width(size);
// replace the numerical value with stars
$(this).html($span);
});
}
CSS
span.stars, span.stars span {
display: block;
background: url(../../images/stars.png) 0 -16px repeat-x;
width: 50px;
height: 20px;
text-indent: -9999px;
}
span.stars span {
background-position: 0 0;
}
SPRITE IMAGE :
You could use session variables etc to control your CSS directly by using a php/css file. You could set star color, sprite position, all based on logic.
Link to your css
<link rel='stylesheet' type='text/css' href='css/style.php' />
Your css/php document
<?php
header("Content-type: text/css; charset: UTF-8");
$CSSposition = $position;
?>
span.stars span {
background-position: <?php echo $CSSposition ?>;
}
Here's a link to php/css document tutorial click here
Check this tutorial on knockout they show how to do the star rating system which you can apply to your code http://learn.knockoutjs.com/#/?tutorial=custombindings

Javascript Popup Windows

I have a popup window code that I have used before in login forms. The code displays an in-page popup.
This is the code:
<?php
//In Page Popup Box with Faded Background by Jerry Low #crankberryblog.com
//Find other useful scripts at the Crankberry Blog
//SETTINGS
$fade_amount = 60; //In Percentage
$box_width = 400;
$box_background = 'FFFFFF'; //Hex Color
$box_border_width = 2;
$box_border_color = '999999'; //Hex Color
$close_box = 1; //Do You Want The Close Bar on Top 1 = Yes, 0 = No
$extension = ""; // Other Variables that maybe needed, page number etc.
//Begin Popup Box
$left_margin = ( 0 - ($box_width*0.5) );
$page_url = basename($_SERVER['PHP_SELF']);
if ($extension!="") $page_url .= '?' . $extension;
if (isset($_GET['popup'])) {
echo '<div class="popup" style="width:'.$box_width.'px; background: #'.$box_background.'; margin-left:'.$left_margin.'px;';
if ($box_border_width>1) echo ' border: '.$box_border_width.'px solid #'.$box_border_color.';';
echo '">';
//Close Box
if ($close_box===1) echo '<div class="popup_close">Close (x)</div>';
?>
<!–- START YOUR POPUP CONTENT HERE -–>
Popup content goes in here!
<!–- END OF YOUR POPUP CONTENT HERE -–>
<?php
echo '</div>
<div class="fade" onclick="location.replace(\''.$page_url.'\');" style="opacity: 0.'.$fade_amount.'; -moz-opacity: 0.'.$fade_amount.';filter: alpha(opacity: '.$fade_amount.');"></div>
<div class="fade_container">';
}
?>
Activated Box
This code contains a link that reloads the page with parameters/arguments to show the popup.
I want to update this code to make the popup appear/hide without
This is what I have done so far, yet the popup doesn`t show.
Now I want to update the code to work as follows.
<link rel=StyleSheet href="css/popup.css" type="text/css" media=screen></link>
<?php
//In Page Popup Box with Faded Background by Jerry Low #crankberryblog.com
//Find other useful scripts at the Crankberry Blog
//SETTINGS
$fade_amount = 60; //In Percentage
$box_width = 400;
$box_background = 'FFFFFF'; //Hex Color
$box_border_width = 2;
$box_border_color = '999999'; //Hex Color
$close_box = 1; //Do You Want The Close Bar on Top 1 = Yes, 0 = No
$extension = ""; // Other Variables that maybe needed, page number etc.
//Begin Popup Box
$left_margin = ( 0 - ($box_width*0.5) );
$page_url = basename($_SERVER['PHP_SELF']);
if ($extension!="") $page_url .= '?' . $extension;
{
echo '<div id="pop_up" class="popup" style="visibility:hidden; width:'.$box_width.'px; background: #'.$box_background.'; margin-left:'.$left_margin.'px;';
if ($box_border_width>1) echo ' border: '.$box_border_width.'px solid #'.$box_border_color.';';
echo '">';
//Close Box
if ($close_box===1) echo '<div class="popup_close"><a href="#" ChangeStatus()>Close (x)</a></div>';
?>
<!–- START YOUR POPUP CONTENT HERE -–>
Popup content goes in here!
<!–- END OF YOUR POPUP CONTENT HERE -–>
<?php
echo '</div>
<div id="fade_div" class="fade" onclick="location.replace(\''.$page_url.'\');" style="visibility:hidden; opacity: 0.'.$fade_amount.'; -moz-opacity: 0.'.$fade_amount.';filter: alpha(opacity: '.$fade_amount.');"></div>
<div class="fade_container">';
}
?>
Activated Box
<script>
function ChangeStatus()
{
div = document.getElementById('fade_div').style.visibility;
popup = document.getElementById('pop_up').style.visibility;
alert(popup);
if(popup == "hidden")
{
div = "visible";
popup = "visible";
}
else
{
div = "hidden";
popup = "hidden";
}
}
</script>
ignore the CSS files as it is working fine.
I guess the problem is with the JS. Can anyone help me?
change your javascript to this:
if(popup == "hidden")
{
document.getElementById('fade_div').style.visibility = "visible";
document.getElementById('pop_up').style.visibility = "visible";
}
and
else
{
document.getElementById('fade_div').style.visibility = "hidden"
document.getElementById('pop_up').style.visibility = "hidden";
}

Attempting to optimize a pixel reading and outputing function

$img = imagecreatefrompng("img/".$image);
$w = imagesx($img);
$h = imagesy($img);
$pixelcount = 0;
echo "<div id='container' style='width: {$w}px; height: {$h}px;'>\r\n";
for($y=0;$y<$h;$y++) {
for($x=0;$x<$w;$x++) {
$rgb = imagecolorat($img, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$alpha = (imagecolorat($img,$x,$y) & 0x7F000000) >> 24;
if($alpha == 127)
$newcolor = "transparent";
else
$newcolor = sprintf('#%02X%02X%02X', $r, $g, $b);
if(isset($prevcolor) && strcmp($newcolor, $prevcolor) != 0)
{
echo "<div style='background: {$prevcolor}; height: 1px; width: {$pixelcount}px; float: left;'></div>\r\n";
$pixelcount = 0;
}
$prevcolor = $newcolor;
$pixelcount++;
}
echo "<div style='background: {$prevcolor}; height: 1px; width: {$pixelcount}px; float: left;'></div>\r\n";
unset($prevcolor);
$pixelcount = 0;
}
echo "</div>\r\n";
Here's a link to the tool in its current form.
http://schnell.dreamhosters.com/folio/pixelread.php?image=link.png
Mousewheel up, I and +/= key zoom in. Mousewheel down, O and -/_ key zoom out. No need to focus on any particular element, the entire document registers a keystroke/mousewheel.
Edit - Thanks for the fix that that one problem, guys! Got a new one now though. If you go to the tool and attempt to blow it up by zooming in, the sprite just falls apart. If you leave it alone and do nothing, it looks fine. What's weird too is that you can't fix the picture by reseting the size, it will stay messed up until you refresh the page.
Edit2 - Found the source of the trouble.
function resize(width, height)
{
$('div#container').css('height', factor * height);
$('div#container').css('width', factor * width);
$('div#container > div').css('height', factor).css('width', function(i, val) { return parseInt(val * factor) + 'px'; });
$('div#container').css('margin-top', ($(window).height() - $('div#container').height())/2 + "px");
}
Width isn't getting multiplied by 'factor' for some reason. I'm trying to do it in such a way that jQuery does it to each and every child div, basing the new width off the old, without having to do a huge for loop or anything, but nothing I'm coming up with is working.
Edit3 - Finally got it working! I just stored the original lengths of each div as the 'id' attribute in each and then access that when it comes time to resize everything. Thanks to everyone who put up with this and stuck with me to see it through. I swear the resizing is smoother than before! :D
Your code isn't resetting the pixel count after each run of colour. I think you need this:
if(isset($prevcolor) && strcmp($hex, $prevcolor) != 0) {
echo "<div style='background: {$prevcolor}; height: 1px; width: {$pixelcount}px; float: left;'></div>\r\n";
$pixelcount = 0;
}
I believe that the problem lies in the fact that, in the inner loop, you never reset $pixelcount after you use it. Consequently, it's just an accumulation of the total pixels of the row, meaning that each time you print you get a progressively larger width.
Based on your description, you'd want to reset it when you switch colours:
if(isset($prevcolor) && strcmp($hex, $prevcolor) != 0) {
echo "<div style='background: {$prevcolor}; height: 1px; width: {$pixelcount}px; float: left;'></div>\r\n";
$pixelcount = 0; // Incremented back to 1 below
}
The resizing problem comes from the resize function, where width is now set inappropriately because the base width of each block is no longer 1:
var cssObj = {
'width' : factor, // This factor needs to be multiplied by the original width
'height' : factor
};
$('div#container > div').css(cssObj);
I'm sure there's a better way to do this, but you could get the width upfront:
$('div#container').css('margin-top',
($(window).height() - $('div#container').height())/2 + "px");
$('div#container > div').each(function() {
$(this).data('originalWidth', $(this).width());
});
...then in the resize function:
$('div#container > div')
.css('height', factor)
.css('width', function() {
return $(this).data('originalWidth') * factor;
});

Categories