This is my HTML code for an image where I can hover over and view another picture
<img class = "images" src = "images/menTop pic1.jpg" onmouseover = "src = 'images/menTop pic1 hover.jpg'" onmouseout = "src = 'images/menTop pic1.jpg'">
I tried to put it in my PHP and replace the IDs and picture with variables but I cannot seem to get it working due to the insane amount of " and '.
echo "<a href='ProductDetail.php?cat_id=".$itemid."'><img class = 'images' src = '".$imagefile."' onmouseover = 'src = '".$imagefile2."'' onmouseout = 'src = '".$imagefile."''></a>";
As of now it shows the first image but does not show the second image when I hover over the picture. Can anyone help me solve this problem? Appreciate the help, thanks!
EDIT:
$mysql = new mysqli("localhost", "root", null, "webdb");
$stmt = $mysql ->prepare("select itemid, itemname, imagefile, imagefile2, itemprice, itemcolor from webdb.item ORDER by itemid ASC");
$stmt->execute();
$stmt->bind_result($itemid, $itemname, $imagefile, $imagefile2, $itemprice, $itemcolor);
$column = 1;
echo "<div class = content>";
echo "<table align = 'center' style = 'width:80%'>";
while($stmt->fetch()) {
if ($column == 1) {
echo "<tr>";
}
echo "<th>";
echo "<a href='ProductDetail.php?cat_id=".$itemid."'><img class = 'images' src = '".$imagefile."' onmouseover = 'src = '".$imagefile2."'' onmouseout = 'src = '".$imagefile."''></a>";
echo "<a href='ProductDetail.php?cat_id=".$itemid."'><h4>".$itemname."</h4></a>";
echo "<p>".$itemcolor."</p>";
echo "<p>".$itemprice."</p>";
echo "</th>";
if ($column == 3) {
$column = 1;
echo "</tr>";
}
else {
$column++;
}
}
echo "</table>";
echo "</div>";
$stmt->close();
$mysql->close();
Currently, this is my block of codes where I am trying to extract every row of data from my item database and to place it nicely in columns of 3 in a webpage. Therefore, if there is a way of placing it in HTML instead of PHP, I'd love if you guys can teach me how to.
Instead of echoing html with PHP like that, it will be much more readable if you write the HTML outside of the PHP-block:
while($stmt->fetch()) {
if ($column == 1) {
echo "<tr>";
}
// Close the PHP block
?>
<th>
<img class="images" src="<?= $imagefile ?>" onmouseover="src='<?= $imagefile2 ?>'" onmouseout="src='<?= $imagefile ?>'">
<h4><?= $itemname ?></h4>
<p><?= $itemcolor ?></p>
<p><?= $itemprice ?></p>
</th>
<?php
// Start the PHP block again
if ($column == 3) {
$column = 1;
echo "</tr>";
}
else {
$column++;
}
}
This way, not only will it be more readable, but you won't you need to escape the quotes + any decent IDE will be able to syntax highlight the HTML as well, making it much easier to spot mistakes.
This part is the problem:
[...] onmouseover = 'src = '".$imagefile2."'' onmouseout = 'src = '".$imagefile."''></a>";
some single quotes that should be replaced by escaped double quotes:
[...] onmouseover = 'src = \"".$imagefile2."\"' onmouseout = 'src = \"".$imagefile."\"'></a>";
<?php echo'<a href ="ProductDetail.php?cat_id='.$itemid.'"><img class="images" src="'.$imagefile.'"
onmouseover="src=\''.$imagefile2.'\';"
onmouseout="src=\''.$imagefile.'\';"/></a>'; ?>
This should solve your problem
You should remove one ' at
onmouseover = 'src = '".$imagefile2."''.
It should be
onmouseover = 'src = '".$imagefile2."'.
Related
I would like put my code to javascript var like that :
function myFunction(){
var switch = document..(etc..)....style.backgroundcolour;
var somethink2 = 'red'; <----- I tell about it
switch = somethink2;
}
and after that my background colour will be switch after using function.
I can"t do that with PHP code (my code connection with sql database) becouse i have not got a " and '.
"dane" (in getElementByID()) in my code below is and i want put this PHP code inside this div.
Guys please help me :)
Regards!
function swap(){
var zawartosc =
<?php $a4="SELECT silnik FROM marki WHERE model = 'A4'";
$result2 = mysqli_query($connection,$a4);
echo "<br>";
echo "<table border='1'>"; // I WANT PUT THIS LIKE A TEXT
while ($row = mysqli_fetch_assoc($result2)) {
echo "<tr>";
foreach ($row as $field => $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>";
?>
document.getElementById("dane").innerHTML = zawartosc;
}
Something like this:
$a4="SELECT silnik FROM marki WHERE model = 'A4'";
$result2 = mysqli_query($connection,$a4);
$html = [];
$html[] = "<br>";
$html[] = "<table border='1'>"; // I WANT PUT THIS LIKE A TEXT
while ($row = mysqli_fetch_assoc($result2)) {
$html[] = "<tr>";
foreach ($row as $field => $value) {
$html[] = "<td>" . $value . "</td>";
}
$html[] = "</tr>";
}
$html[] = "</table>";
$html = json_encode($html); //'["<br>","<table border='1'>", ...]'
?>
document.getElementById("dane").innerHTML = <?php echo $html;?>.join("\n"); //no quotes needed
//document.getElementById("dane").innerHTML = ["<br>","<table border='1'>", ...].join("\n");
Or you can just handle it like a normal string, but it's not what I would prefer to do.
$html = implode($html);
?>
document.getElementById("dane").innerHTML = "<?php echo $html;?>"; //careful with quotes here
In other words, don't output from PHP directly, instead build an array. It's much cleaner as you can consolidate that into a single variable and then use it.
For example:
//timeout for demonstration purposes
setTimeout(function(){
document.getElementById("dane").innerHTML = [
"<br>",
"<table border='1'>",
"<tr>",
"<td>foo</td>",
"<td>bar</td>",
"</tr>",
"<tr>",
"<td>biz</td>",
"<td>baz</td>",
"</tr>",
"</table>"
].join("\n");
},500);
table{width:100px;}
<div id="dane"></div>
I like using join (it's like implode) for multi line strings in JS (even in my plugins). In this case it works well with json_encode.
Basically we convert that array of HTML into a JSON string, which becomes a real Array in JS, then we let JS do the imploding with join. Mainly because arrays don't require the use of a quote, so this avoids any issues if we have quotes in our html.
Consider this (using just strings):
<?php
//HEREDOC
$html = <<<HTML
<table border='1' style="color:red;" >
HTML;
?>
document.getElementById("dane").innerHTML = '<?php echo $html;?>';
document.getElementById("dane").innerHTML = "<?php echo $html;?>";
Which becomes this:
document.getElementById("dane").innerHTML = '<table border='1' style="color:red;">'; //syntax error
document.getElementById("dane").innerHTML = "<table border='1' style="color:red;">"; //syntax error
From what I see you can get away with " at the moment, but if you put them in your HTML, you'll probably be in trouble (if your just using strings). Using join avoids this
document.getElementById("dane").innerHTML = ["<table border='1' style=\"color:red;\">"].join("\n"); //json_encode knows how to escape " for json.
Hope it helps!
I have in my database 2 rows of information so my code create will create positivoNegativo.png twice and the number 10 twice. When I click on the FIRST positivoNegativo.png my number FIRST 10 is incremented (exacly as I wanted to). Now my issue, when I click on the SECOND positivoNegativo.png, the FIRST number is incremented again! I just can't increment the SECOND number by clicking on the SECOND positivoNegativo.png
<html>
<body>
<?php
include_once("./classe/conexao.php");
$busca = $pdo->prepare("select * from anuncios");
$busca->execute();
$linha = $busca->fetchAll(PDO::FETCH_OBJ);
$classe = 0;
foreach ($linha as $lista) {
echo "<p class='demo'>10</p>";
echo "<img src='imagens/positivoNegativo.png'usemap='#mapa'>";
echo "<map name='mapa'>";
echo "<area shape='rect' coords='1,1,73,59' onclick='aumenta($classe)'>";
echo "</map>";
echo "<span>$lista->titulo</span>";
$classe++;
}
?>
<script>
function aumenta(classe) {
var numero = document.getElementsByClassName('demo')[classe].innerHTML;
numero++;
document.getElementsByClassName('demo')[classe].innerHTML = numero;
}
</script>;
</body>
You need to use different map for each image.
foreach ($linha as $lista) {
echo "<p class='demo'>10</p>";
echo "<img src='imagens/positivoNegativo.png'usemap='#mapa$classe'>";
echo "<map name='mapa$classe'>";
echo "<area shape='rect' coords='1,1,73,59' onclick='aumenta($classe)'>";
echo "</map>";
echo "<span>$lista->titulo</span>";
$classe++;
}
Try this:
<?php
include_once("./classe/conexao.php");
$busca = $pdo->prepare("select * from anuncios");
$busca->execute();
$linha = $busca->fetchAll(PDO::FETCH_OBJ);
$classe = 0;
foreach ($linha as $lista) {
echo "<p class='demo".$classe."'>10</p>";
echo "<img src='imagens/positivoNegativo.png' onclick='aumenta($classe)'>";
echo "<span>$lista->titulo</span>";
$classe++;
}
?>
<script>
function aumenta(classe) {
var numero = document.getElementsByClassName('demo'+classe).innerHTML;
numero++;
document.getElementsByClassName('demo'+classe).innerHTML = numero;
}
</script>;
I didn't test the code, but it might give you some hints.
I left out the whole <map> thing because it doesn't make sense in your code. There's only an up?
I have a data set of items coming from a SQL database. Those items are displayed in multiple divs like:
<?php
$url = 'DataBase';
$json_response = file_get_contents ( $url );
$json_arr = json_decode ( $json_response, true );
for($i = count ( $json_arr )-1; $i > 0; $i--) {
$json_obj = $json_arr [$i];
echo '<div id="MyDIV">';
echo $json_obj ['id'] ;
echo $json_obj ['title'];
echo $json_obj ['article'];
echo '<button id="read_more_btn">Read more</button>';
echo '</div>'
}
?>
My problem is that I cannot handle click events for EACH div, so I cannot identify which item has been clicked. I’ve been searching for a solution for quite a while, but haven’t found anything. So my question is – how can I identify the clicked item?
EDIT
I have no idea how I can dynamically assign an ID to a button
You could use a data attributes (HTML5 assumed) to attach the Id as meta data to your divs. Your PHP (note I am adding data-id attributes):
<?php
$url = 'DataBase';
$json_response = file_get_contents ( $url );
$json_arr = json_decode ( $json_response, true );
for($i = count ( $json_arr )-1; $i > 0; $i--) {
$json_obj = $json_arr [$i];
echo '<div data-id="' . $json_obj['id'] . '">';
echo $json_obj ['id'] ;
echo $json_obj ['title'];
echo $json_obj ['article'];
echo '<button id="read_more_btn">Read more</button>';
echo '</div>'
}
?>
JS - simple click handler attachment, using jQuery .data() [docs] to get data attribute:
$('div').click(function(e) {
var id = $(this).data("id");
alert(id);
});
JSFiddle Demo
How about when creating the html in the php, you echo the id inside the class.
echo '<div id="mydiv-' . $json_obj['id'] . '">';
So now in the html, it's going to look like
<div id="mydiv-1"> ... </div>
<div id="mydiv-2"> ... </div>
<div id="mydiv-3"> ... </div>
etc.
And then in Javascript, you could access them the same way you access any tag.
$('#mydiv-1').click(function(e){
console.log('a div was clicked');
console.log($(this))
});
So in order to assign listeners to each div, you could do a loop
for(var i = 1;$('#mydiv-container').children().length >= i,i++)
{
$('#mydiv-' + i).click(function(){
}
Make sure to add a container for all the divs.
Give each div a unique numeric class, so your jquery will be
$('div').click(function() {
var item_id = $(this).attr("class");
//do stuff here
});
or
$('div').click(function() {
var item_id = this.className;
//do stuff here
});
I'm working with PHP, Javascript and MySQL. My goal is to have a button on each row. The button should call the onclick fucntion and href to another page.
My problem with my code -- > only the button from the first row is clickable...
I'm assuming the Button ID needs to be unique for each button.. What are my options to make all buttons clickable ?
// printing table rows
while($row = mysqli_fetch_row($result))
{
echo "<tr>";
echo "<td><button id='greenbutton' class='small pill green'>$row[0]</button></td>";
echo "<td><img src='/iframe/$row[7]'> $row[5]</td>";
echo "<td>$row[4] min(s)</td>";
echo "<td><img src='/iframe/$row[6]'> $row[2]</td>";
if ($row[3] == 0) {
echo "<td>Unknown</td>";
}
else {echo "<td>$row[3]</td>";}
echo "</tr>\n";
// FOR ONCLICK
echo "<script type='text/javascript'>";
echo "document.getElementById('greenbutton').onclick = function () {";
echo "location.href = '/user';";
echo "};";
echo "</script>";
}
echo "</table></center>";
You're id's of your dom elements should be unique at all time. To achieve this you can add a counter in your while so that all of your button have an id like 'greenbutton1', 'greenbutton2', 'greenbutton3', etc.
$cnt = 1;
// printing table rows
while($row = mysqli_fetch_row($result))
{
echo "<tr>";
echo "<td><button id='greenbutton$cnt' class='small pill green'>$row[0]</button></td>";
echo "<td><img src='/iframe/$row[7]'> $row[5]</td>";
echo "<td>$row[4] min(s)</td>";
echo "<td><img src='/iframe/$row[6]'> $row[2]</td>";
if ($row[3] == 0) {
echo "<td>Unknown</td>";
}
else {echo "<td>$row[3]</td>";}
echo "</tr>\n";
$cnt++;
}
echo "</table></center>";
In that exemple I didnt add your javascript function into your while loop because it look like the same function for all your buttons. I suggest you add the function only once but bound it with the class selector instead of the id selector like this.
// FOR ONCLICK
echo "<script type='text/javascript'>";
echo "document.getElementsByClassName('myGreenButtons').onclick = function () {";
echo "location.href = '/user';";
echo "};";
echo "</script>";
And then add the myGreenButtons class to your buttons in the while loop. You can also use attributes or types selector to gather your dom elements in a more flexible way. Check out theses links for more info:
http://www.w3schools.com/cssref/css_selectors.asp
http://www.htmlgoodies.com/beyond/javascript/using-javascripts-css3-selectors.html#fbid=FhIuAA6GqpH
hope this helps!
echo "<td><a href='/user'><button class='small pill green'>$row[0]</button></a></td>";
...will do the trick.
I made a gallery with images fetched from DB and using Fancybox for displaying it. I have some articles that are the same, just diferent color and I display just one and underneath color boxes for changing the color.
The problem is that when I click on the button to change the color, picture changes, Fancybox on click displays first picture, not the Current one
Part of the code:
JS:
function changeImage(element,id){
var img=document.getElementById(id).src=element;
return false;
}
PHP:
while($row = mysql_fetch_array($sql)){
$prikaz =$row['prikaz'];
$id = $row['id'];
$ime = $row['ime'];
$thumb = $row['thumbs'];
$boja = $row['boja_id'];
$slicka = $row['slika'];
$spec = $row['tekst'];
if ($prikaz == 1){
echo "<table style ='display: inline' align='center'>";
echo "<tr>";
echo "<td><a class='fancybox-effects-a' href='$slicka' ><img id='$id' src='$thumb' alt='' /></a></td>";
echo "</tr>";
echo "<tr><td>";
echo "Boja: ";
$bsql = mysql_query ("SELECT muski.tekst, muski.id,muski.thumbs,boja.bslika FROM boja INNER JOIN muski ON muski.boja_id = boja.id WHERE muski.ime = '$ime' " );
while($res = mysql_fetch_array($bsql)){
$slicica = $res['thumbs'];
$muid = $res['id'];
$kockica = $res['bslika'];
echo "<button id = 'boja' onclick =changeImage('$slicica','$id')><img src= $kockica ></button>";
}
echo "</br>";
echo nl2br($spec);
}
echo "</td>";
echo "</tr>";
echo "</table>";
I found the solution.... I modified js script to change the parent href of img... It works...
function changeImage(element,id,staza) {
var img = document.getElementById(id);
img.src= element;
img.parentNode.href=staza;
return false;
}
Firebug your Fancy Box pop-up and inside the you have to change back ground image as well