Reputation: 137
I'm trying to write a photo gallery page where there are small icons of photo's below and when you click on them they enlarge into the main photo screen. only I'm having trouble trying to get the javascript to do what I want. Can anyone help me please?
here's my code so far:
<?php
$host = "localhost";
$user = "root";
$pwd = "";
$db_name = "gallery";
mysql_connect($host, $user, $pwd)or die("cannot connect");
mysql_select_db($db_name)or die("cannot select DB");
$sql = mysql_query("SELECT * FROM foto ORDER BY id DESC LIMIT 10");
$id = 'id';
$foto = 'foto';
while ($rows = mysql_fetch_assoc($sql))
{
echo "<img class='littleshow'"."id='foto".$rows[$id]."'src='".$rows[$foto]."' onclick='Bigscreen(foto".$rows[$id].")'></img>";
} //the onclick generates onclick="bigscreen(foto1)" and does this again 4 times on the other objects generating foto1,foto2,foto3,foto4
?>
<div id='bigshowcase'></div>
and my Javascript so far:
function Bigscreen () {
var div0 = document.getElementById('bigshowcase');
var images = new array();
images[0] = div0.style.backgroundImage = "url(pic/camera.jpg)";
images[1] = div0.style.backgroundImage = "url(pic/dsc_4255.jpg)";
images[2] = div0.style.backgroundImage = "url(pic/dsc_4373.jpg)";
images[3] = div0.style.backgroundImage = "url(pic/dsc01209.jpg)";
foto1 = images[0]
foto2 = images[1]
foto3 = images[2]
foto4 = images[3]
}
I know very little about javascript so most of this is probably wrong. thanks for helping :)
Upvotes: 2
Views: 111
Reputation: 5461
replace this line:
echo "<img class='littleshow'"."id='foto".$rows[$id]."'src='".$rows[$foto]."' onclick='Bigscreen(foto".$rows[$id].")'></img>";
with this:
echo "<img class='littleshow'"."id='foto".$rows[$id]."'src='".$rows[$foto]."' onclick='Bigscreen(this)'></img>";
and change Bigscreen
function to:
function Bigscreen(img) {
document.getElementById('bigshowcase').innerHTML ='<img src="' + img.src + '" />';
}
CSS:
<style type="text/css">
#bigshowcase img{max-width:600px;max-height:600px;}
</style>
hope that helps.
EDIT:
note that jQuery is always nicer:
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$(document).on('click', 'img.littleshow', function(){
$('#bigshowcase').html('<img src="' + $(this).attr('src') + '" />');
});
});
</script>
will do the job.
Upvotes: 2
Reputation: 583
You can put the element you clicked on as a variable of a function:
<img id="mainPic"> <img id="thumbImage" src="<url>" onclick="SetPic(this)"> var mainPic = document.getElementById("mainPic"); function SetPic(thumbPic) { mainPic.src = thumbPic.src; }
Upvotes: 0