jQuery $.get() adding slashes not saving edits even after slashes removed - php

I have created a simple CSS editing/optimizing system in a WordPress plugin. Basically, the CSS files are stored in a folder. They are accessed to edit though a selection box using jQuery.
HTML
# edit stylesheet
echo '<div id="editStyles" class="s8w-hide">';
echo '<h2>Edit a Stylesheet</h2>';
echo '<form action="" method="post">';
# file name
echo '<div class="s8w-row">';
echo '<div class="s8w-col_12">';
echo '<select id="getStylesheeteEdit" name="filename" class="s8w-expand">';
echo '<option value="">Select Stylesheet to Edit</option>';
foreach(glob(S8W_CSS_GEN . 'common/*.css') as $file) {
$filename = basename($file);
echo '<option value="'.$filename.'">'.$filename.'</option>';
}
echo '</select>';
echo '</div>';
echo '</div>';
# styles
echo '<div class="s8w-row">';
echo '<div class="s8w-col_12">';
echo '<textarea id="showEditStyles" name="styles" class="s8w-expand" style="height: 350px;"></textarea>';
echo '</div>';
echo '</div>';
echo '<div class="s8w-row">';
echo '<div class="s8w-col_12 s8w-center">';
echo '<input type="submit" name="edit_stylesheet" class="s8w navy tiny-radius" value="Edit this Stylesheet">';
echo '</div>';
echo '</div>';
echo '</form>';
jQuery
This jQuery added slashes so I added the commented out line but it did not remove them.
/* GET STYLESHEET TO EDIT
----------------------------------------------------- */
$( "#getStylesheeteEdit" ).change(function() {
var which = $(this).val();
var file = 'https://s8w.org/wp-content/plugins/IDCCST/css/generator/common/' + which;
$.get(file, function(data) {
//data.replace('\\','');
$('#showEditStyles').val(data);
});
});
parsing php
I added stripslashes here which did remove the slashes.
/* EDIT STYLESHEET
--------------------------------------------------------- */
if(array_key_exists('edit_stylesheet',$_POST)){
$filename = $_POST['filename'];
$styles = stripslashes($_POST['styles']);
# update styles
file_put_contents(S8W_CSS_GEN . 'common/'.$filename, $styles);
# parse stylesheets
$msg = 'The stylesheet: '.$filename.' and the S8W Stylesheet have been updated.';
parseStyles($msg);
}
parseStyles($msg); minimizes and writes single style sheet.
<?php
function parseStyles($msg){
/* admin styles
-------------------------------------- */
foreach(glob(S8W_CSS_GEN . 'admin/*.css') as $file) {
$admin_code .= file_get_contents($file);
$prep_styles = file_get_contents($file);
$prep_styles = str_replace("/*","~",$prep_styles);
$prep_styles = str_replace("*/","~",$prep_styles);
preg_match_all("'~(.*?)~'si", $prep_styles, $match);
foreach($match[1] as $val) {
$this_comment = '~'.$val.'~';
$prep_styles = str_replace($this_comment,"",$prep_styles);
}
//$prep_styles = str_replace('\"','"',$prep_styles);
$prep_styles = str_replace("\r","",$prep_styles);
$prep_styles = str_replace("\n","",$prep_styles);
$prep_styles = str_replace("\t","",$prep_styles);
$admin_styles .= $prep_styles;
}
/* common styles
-------------------------------------- */
foreach(glob(S8W_CSS_GEN . 'common/*.css') as $file) {
$common_code .= file_get_contents($file);
$prep_styles = file_get_contents($file);
$prep_styles = str_replace("/*","~",$prep_styles);
$prep_styles = str_replace("*/","~",$prep_styles);
preg_match_all("'~(.*?)~'si", $prep_styles, $match);
foreach($match[1] as $val) {
$this_comment = '~'.$val.'~';
$prep_styles = str_replace($this_comment,"",$prep_styles);
}
//$prep_styles = str_replace('\"','"',$prep_styles);
$prep_styles = str_replace("\r","",$prep_styles);
$prep_styles = str_replace("\n","",$prep_styles);
$prep_styles = str_replace("\t","",$prep_styles);
$common_styles .= $prep_styles;
}
# write admin styles
$admin_styles = $common_styles.$admin_styles;
file_put_contents(S8W_CSS . 's8w-admin-styles.css', $admin_styles);
# write admin styles
$admin_readable = $common_code.$admin_code;
file_put_contents(S8W_CSS_GEN . 'readable-admin.css', $admin_readable);
$common_styles = $common_styles;
# write admin styles
file_put_contents(S8W_CSS . 's8w-styles.css', $common_styles);
# write admin styles
$common_readable = $common_code;
file_put_contents(S8W_CSS_GEN . 'readable.css', $common_readable);
echo '<Script language="javascript">alert("'.$msg.'");</script>';
}
All of this code works great if the styles do not have double quote. The file is called to the editing textarea and parses perfectly and write the minimized file. However, if the styles have double quotes:
CSS Example with Double Quotes
/* BUTTONS
------------------------------------------------------------------- */
button.s8w,
a.button.s8w,
input[type="submit"].s8w,
input[type="button"].s8w {
position:relative;
top:0;
left:0;
padding:10px 15px;
line-height:100%;
vertical-align: middle;
cursor: pointer;
overflow:visible;
font-weight:normal;
font-size:16px;
text-decoration:none;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
display:inline-block;
zoom:1;
background: #fcfcfc;
color:#666;
border:1px solid #cccccc;
text-align: center;
border-radius: 0;
}
The file will save and be minimized. But when the file is called though jQuery, though the edits are saved to the file, the new edits do not render in the textarea and as a result are lost if the file is saved once again. Hope I was able to explain the problem clearly. Any help or thoughts are appreciated.

While I am still not sure what was happening, the problem was in this jQuery:
/* GET STYLESHEET TO EDIT
----------------------------------------------------- */
$( "#getStylesheeteEdit" ).change(function() {
var which = $(this).val();
var file = 'https://s8w.org/wp-content/plugins/IDCCST/css/generator/common/' + which;
$.get(file, function(data) {
//data.replace('\\','');
$('#showEditStyles').val(data);
});
});
When a css file was edited the edits would be saved and parsed through the minimizer php, but the above jQuery would not pick up the edits on the saved file when it was reselected. Have no idea as to why?
I was able to resolve the issue by changing the jQuery to:
$( "#getStylesheeteEdit" ).change(function() {
var which = $(this).val();
var url = 'https://s8w.org/wp-content/plugins/IDCCST/css/generator/get-stylsheet.php';
var postit = $.post( url, {which:which});
postit.done(function( data ) {$('#showEditStyles').val(data);});
});
and adding a php parse file with only one line of code to be able to make use of file_get_contents() instead using jQuery to get the contents of the desired css file:
<?php
$file = 'common/'.$_POST['which']; echo file_get_contents($file);

Related

How to remove a line from text file using php with specific structure [duplicate]

This question already has answers here:
How to delete a line from the file with php?
(10 answers)
Closed last year.
I have a css file with this content:
#firstdiv { width:100%; height:200px; }
#seconddiv { width:80%; height:70px; }
#thirddiv { width:80%; height:70px; }
#firstdiv { color:red; background:yellow; }
#seconddiv { color:red; background:green; }
#firstdiv { border:3px solid black; border-rdius:5px; }
How can I remove all #firstdiv css properties using php?
This is my desired output:
#seconddiv { width:80%; height:70px; }
#thirddiv { width:80%; height:70px; }
#seconddiv { color:red; background:green; }
The most easy way would to split the file based on newlines and then check for each row whether it starts with the string you don't want and finally save the file to the location.
$filelocation = "/path/to/file"; //please update for your situation
$csscontents = file_get_contents($filelocation);
$lines = explode(PHP_EOL,$csscontents);
$csscontents = '';
foreach($lines as $line) {
if (substr($line,0,9) !== "#firstdiv") $csscontents .= $line . PHP_EOL;
}
file_put_contents($filelocation,$csscontents);
In case there are multiple selectors on one line, you need to do this
$filelocation = "/path/to/file"; //please update for your situation
$csscontents = file_get_contents($filelocation);
$lines = explode('}',$csscontents);
$csscontents = '';
foreach($lines as $line) {
if (substr(preg_replace('/\s+/', '',$line),0,9) !== "#firstdiv" AND !empty($line) AND !ctype_space($line)) $csscontents .= $line . "}";
}
file_put_contents($filelocation,$csscontents);

Check if a string contains a url and get contents of url php

Suppose someone enters a string in a textarea like this
"The best search engine is www.google.com."
or maybe
"The best search engine is https://www.google.co.in/?gfe_rd=cr&ei=FLB1U4HHG6aJ8Qfc1YHIBA."
Then i want to highlight the link as stackoverflow does.
And also i want to file_get_contents to get one image , a short description and title of the page.
Most probably i wanna check if the string contains a url or not -> two times.
On keyup of textarea using jQuery and therefore using the
get_file_contents
When the string is recieved by php.
Possibly how can i do this?
UPDATE
function parseHyperlinks($text) {
// The Regular Expression filter
$reg_exUrl1 = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$reg_exUrl2 = "/[\w\d\.]+\.(com|org|ca|net|uk)/";
// The Text you want to filter for urls
// Check if there is a url in the text
if(preg_match($reg_exUrl1, $text, $url)) {
// make the urls hyper links
return preg_replace($reg_exUrl1, "<a class=\"content-link link\" href=\"{$url[0]}\">{$url[0]}</a> ", $text);
} else if(preg_match($reg_exUrl2, $text, $url)){
return preg_replace($reg_exUrl2, "<a class=\"content-link link\" href=\"{$url[0]}\">{$url[0]}</a> ", $text);
}else{
// if no urls in the text just return the text
return $text;
}
}
This works only if $str='www.google.com is the best' or $str='http://www.google.com is best' but not if $str='http://stackoverflow.com/ and www.google.com is the best'
First off you create the html then you need to an AJAX to request to the server. Consider this sample codes:
HTML/jQuery:
<!-- instead of textarea, you could use an editable div for styling highlights, or if you want, just use a plugin -->
<div id="textarea"
style="
font-family: monospace;
white-space: pre;
width: 300px;
height: 200px;
border: 1px solid #ccc;
padding: 5px;">For more tech stuff, check out http://www.tomshardware.com/ for news and updates.</div><br/>
<button type="button" id="scrape_site">Scrape</button><br/><br/>
<!-- i just used a button to hook up the scraping, you can just bind it on a keyup/keydown. -->
<div id="site_output" style="width: 500px;">
<label>Site: <p id="site" style="background-color: gray;"></p></label>
<label>Title: <p id="title" style="background-color: gray;"></p></label>
<label>Description: <p id="description" style="background-color: gray;"></p></label>
<label>Image: <div id="site_image"></div></label>
</div>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#scrape_site').on('click', function(){
var value = $.trim($('#textarea').text());
$('#site, #title, #description').text('');
$('#site_image').empty();
$.ajax({
url: 'index.php', // or you php that will process the text
type: 'POST',
data: {scrape: true, text: value},
dataType: 'JSON',
success: function(response) {
$('#site').text(response.url);
$('#title').text(response.title);
$('#description').text(response.description);
$('#site_image').html('<img src="'+response.src+'" id="site_image" />');
}
});
});
// you can use an editable div so that it can be styled,
// theres to much code already in the answer, you can just get a highlighter plugin to ease your pain
$('#textarea').each(function(){
this.contentEditable = true;
});
});
</script>
And on your php that will process, in this case (index.php):
if(isset($_POST['scrape'])) {
$text = $_POST['text'];
// EXTRACT URL
$reg_exurl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
preg_match_all($reg_exurl, $text, $matches);
$usedPatterns = array();
$url = '';
foreach($matches[0] as $pattern){
if(!array_key_exists($pattern, $usedPatterns)){
$usedPatterns[$pattern] = true;
$url = $pattern;
}
}
// EXTRACT VALUES (scraping of title and descriptions)
$doc = new DOMDocument();
$doc->loadHTMLFile($url);
$xpath = new DOMXPath($doc);
$title = $xpath->query('//title')->item(0)->nodeValue;
$description = $xpath->query('/html/head/meta[#name="description"]/#content');
if ($description->length == 0) {
$description = "No description meta tag :(";
// Found one or more descriptions, loop over them
} else {
foreach ($description as $info) {
$description = $info->value . PHP_EOL;
}
}
$data['description'] = $description;
$data['title'] = $title;
$data['url'] = $url;
// SCRAPING OF IMAGE (the weirdest part)
$image_found = false;
$data['src'] = '';
$images = array();
// get all possible images and this is a little BIT TOUGH
// check for og:image (facebook), some sites have this, so first lets take a look on this meta
$facebook_ogimage = $xpath->query("/html/head/meta[#property='og:image']/#content");
foreach($facebook_ogimage as $ogimage) {
$data['src'] = $ogimage->nodeValue;
$image_found = true;
}
// desperation search (get images)
if(!$image_found) {
$image_list = $xpath->query("//img[#src]");
for($i=0;$i<$image_list->length; $i++){
if(strpos($image_list->item($i)->getAttribute("src"), 'ad') === false) {
$images[] = $image_list->item($i)->getAttribute("src");
}
}
if(count($images) > 0) {
// if at least one, get it
$data['src'] = $images[0];
}
}
echo json_encode($data);
exit;
}
?>
Note: Although this is not perfect, you can just use this as a reference to just improved on it and make it more dynamic as you could.

insert echo into the specific html element like div which has an id or class

I have this code.
<html>
<head>
<style type="text/css">
body{background:#666666;}
div{border:1px solid red;}
</style>
</head>
<body>
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("juliver", $con);
$result = mysql_query("SELECT * FROM hi");
while($row = mysql_fetch_array($result))
{
echo '<img src="'.$row['name'].'" />';
echo "<div>".$row['name']."</div>";
echo "<div>".$row['title']."</div>";
echo "<div>".$row['description']."</div>";
echo "<div>".$row['link']."</div>";
echo "<br />";
}
mysql_close($con);
?>
</body>
</html>
the above code works.
now, I want to insert this
echo '<img src="'.$row['name'].'" />';
echo "<div>".$row['name']."</div>";
echo "<div>".$row['title']."</div>";
echo "<div>".$row['description']."</div>";
echo "<div>".$row['link']."</div>";
echo "<br />";
into the specified div or other element in the html, example, i will insert this
echo '<img src="'.$row['name'].'" />';
into the html element .
I dont know how to do this, please help me. Thanks
Juliver
if yo want to place in an div like
i have same work and i do it like
<div id="content>
<?php
while($row = mysql_fetch_array($result))
{
echo '<img src="'.$row['name'].'" />';
echo "<div>".$row['name']."</div>";
echo "<div>".$row['title']."</div>";
echo "<div>".$row['description']."</div>";
echo "<div>".$row['link']."</div>";
echo "<br />";
}
?>
</div>
The only things I can think of are
including files
replacing elements within files using preg_match_all
using assigned variables
I have recently been using str_replace and setting text in the HTML portion like so
{{TEXT_TO_REPLACE}}
using file_get_contents() you can grab html data and then organise it how you like.
here is a demo
myReplacementCodeFunction(){
$text = '<img src="'.$row['name'].'" />';
$text .= "<div>".$row['name']."</div>";
$text .= "<div>".$row['title']."</div>";
$text .= "<div>".$row['description']."</div>";
$text .= "<div>".$row['link']."</div>";
$text .= "<br />";
return $text;
}
$htmlContents = file_get_contents("myhtmlfile.html");
$htmlContents = str_replace("{{TEXT_TO_REPLACE}}", myReplacementCodeFunction(), $htmlContents);
echo $htmlContents;
and now a demo html file:
<html>
<head>
<style type="text/css">
body{background:#666666;}
div{border:1px solid red;}
</style>
</head>
<body>
{{TEXT_TO_REPLACE}}
</body>
</html>
You can write the php code in another file and include it in the proper place where you want it.
AJAX is also used to display HTML content that is formed by PHP into a specified HTML tag.
Using jQuery:
$.ajax({url: "test.php"}).done(function( html ) {
$("#results").append(html);
});
Above code will execute test.php and result will be displayed in the element with id results.
There is no way that you can do it in PHP when HTML is already generated. What you can do is to use JavaScript or jQuery:
document.getElementById('//ID//').innerHTML="HTML CODE";
If you have to do it when your URI changes you can get the URI and then split it and then insert the HTML in script dynamically:
var url = document.URL;
// to get url and then use split() to check the parameter
refer to the basic.
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
there is no way to specifically target an element with php, you can either embed the php code between a div tag or use jquery which would be longer.
You can repeat it by fetching again the data
while($row = mysql_fetch_assoc($result)){
//another html element
<div>$row['name']</div>
<div>$row['title']</div>
//and so on
}
or you need to put it on the variable and call display it again on other html element
$name = $row['name'];
$title = $row['title']
//and so on
then put it on the other element, but if you want to call all the data of each id, you need to do the first code
Have you tried this?:
$string = '';
while($row = mysql_fetch_array($result))
{
//this will combine all the results into one string
$string .= '<img src="'.$row['name'].'" />
<div>'.$row['name'].'</div>
<div>'.$row['title'].'</div>
<div>'.$row['description'].'</div>
<div>'.$row['link'].'</div><br />';
//or this will add the individual result in an array
/*
$yourHtml[] = $row;
*/
}
then you echo the $tring to the place you want it to be
<div id="place_here">
<?php echo $string; ?>
<?php
//or
/*
echo '<img src="'.$yourHtml[0]['name'].'" />;//change the index, or you just foreach loop it
*/
?>
</div>
Well from your code its clear that $row['name'] is the location of the image on the file, try including the div tag like this
echo '<div>' .$row['name']. '</div>' ;
and do the same for others, let me know if it works because you said that one snippet of your code is giving the desired result so try this and if the div has some class specifier then do this
echo '<div class="whatever_it_is">' . $row['name'] . '</div'> ;
You have to put div with single quotation around it. ' ' the Div must be in the middle of single quotation . i'm gonna clear it with one example :
<?php
echo '<div id="output">'."Identify".'<br>'.'<br>';
echo 'Welcome '."$name";
echo "<br>";
echo 'Web Mail: '."$email";
echo "<br>";
echo 'Department of '."$dep";
echo "<br>";
echo "$maj";
'</div>'
?>
hope be useful.
I use this or similar code to inject PHP messages into a fixed DIV positioned in front of other elements (z-index: 9999) just for convenience at the development stage.
Each PHP message passes into my 'custom_message()' function and is further conveyed into the innard of preformatted DIV created by echoed JS.
There can be as many as it gets, all put inside that fixed DIV, one under the other.
<style>
#php_messages {
position: fixed;
left: 0;
top: 0;
z-index: 9999;
}
.php_message {
background-color: #333;
border: red solid 1px;
color: white;
font-family: "Courier New", Courier, monospace;
margin: 1em;
padding: 1em;
}
</style>
<div id="php_messages"></div>
<?php
function custom_message($output) {
echo
'
<script>
var
el = document.createElement("DIV");
el.classList.add("php_message");
el.innerHTML = \''.$output.'\';
document.getElementById("php_messages").appendChild(el);
</script>
';
}
?>

Facebook like link parser

Is there any already done php class that could parse a link like Facebook, Google+ or Digg does? To get the title, some text and images from the page? :)
Thanks
Here is some code I pinched from sitepoint.com. I have used it a few times and it seems to work nicely...
<?php
define( 'LINK_LIMIT', 30 );
define( 'LINK_FORMAT', '%s' );
function parse_links ( $m ){
$href = $name = html_entity_decode($m[0]);
if ( strpos( $href, '://' ) === false ) {
$href = 'http://' . $href;
}
if( strlen($name) > LINK_LIMIT ) {
$k = ( LINK_LIMIT - 3 ) >> 1;
$name = substr( $name, 0, $k ) . '...' . substr( $name, -$k );
}
return sprintf( LINK_FORMAT, htmlentities($href), htmlentities($name) );
}
$s = 'Here is a text - www.ellehauge.net - it has some links with e.g. comma, www.one.com,in it. Some links look like this: http://mail.google.com - mostly they end with aspace or carriage return www.unis.no<br /> - but they may also end with a period: http://ellehauge.net. You may even putthe links in brackets (www.skred-svalbard.no) (http://one.com).From time to time, links use a secure protocol like https://gmail.com |This.one.is.a.trick. Sub-domaines: http://test.ellehauge.net |www.test.ellehauge.net | Files: www.unis.no/photo.jpg |Vars: www.unis.no?one=1&~two=2 | No.: www.unis2_check.no/doc_under_score.php |www3.one.com | another tricky one:http://ellehauge.net/cv_by_id.php?id%5B%5D=105&id%5B%5D=6&id%5B%5D=100';
$reg = '~((?:https?://|www\d*\.)\S+[-\w+&##/%=\~|])~';
print preg_replace_callback( $reg, 'parse_links', $s );
?>
This looks like something you could use:
http://www.redsunsoft.com/2011/01/parse-link-like-facebook-with-jquery-and-php/
index.php
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<style>body
{
font-family:Arial, Helvetica, sans-serif;
font-size:12px;
}
#contentbox
{
width:458px; height:50px;
border:solid 2px #dedede;
font-family:Arial, Helvetica, sans-serif;
font-size:14px;
margin-bottom:6px;
}
.img
{
float:left; width:150px; margin-right:10px;
text-align:center;
}
#linkbox
{
border:solid 2px #dedede; min-height:50px; padding:15px;
display:none;
}</style>
<script type="text/javascript">
$(document).ready(function()
{
$("#contentbox").keyup(function()
{
var content=$(this).val();
var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
// Filtering URL from the content using regular expressions
var url= content.match(urlRegex);
if(url.length>0)
{
$("#linkbox").slideDown('show');
$("#linkbox").html("<img src='link_loader.gif'>");
// Getting cross domain data
$.get("urlget.php?url="+url,function(response)
{
// Loading <title></title>data
var title=(/<title>(.*?)<\/title>/m).exec(response)[1];
// Loading first .png image src='' data
var logo=(/src='(.*?).png'/m).exec(response)[1];
$("#linkbox").html("<img src='"+logo+".png' class='img'/><div><b>"+title+"</b><br/>"+url)
});
}
return false;
});
});
//HTML Code
<textarea id="contentbox"></textarea>
<div id="linkbox"></div>
</script>
urlget.php
<?php
if($_GET['url'])
{
$url=$_GET['url'];
echo file_get_contents($url);
}
?>
source

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

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.')"/>

Categories