I'm using php and jquery to print out articles on my webpage. And I want to be able to use show/hide jquery on one article at the time. As it is right now, when I press hide or show all <article> elements in my foreach loop is effected.
HTML and PHP code
<section class='col-md-8'> <!-- Div for content, images etc. -->
<?php
$page = new CMS();
$gp = $page->getPage();
foreach ($gp as $sp) {
//var_dump($sp);
echo "<div id='pub'>";
echo "<h4>" . $sp['title'] . "</h4>";
echo "<article id='pub_art'>" . $sp['content'] . "</article>";
echo "<p>" . $sp['created'] . "</p>";
echo "<p>". $sp['writer'] ."</p>";
echo "<button id='hide'>Hide</button>";
echo "<button id='show'>Show</button>";
echo "</div>";
}
?>
</section>
Jquery code
$(document).ready(function(){
$("#hide").click(function(){
$("article").hide();
});
$("#show").click(function(){
$("article").show();
});
});
CSS
#pub_art {
width: 100%;
height: 100%;
background-color: blue;
display: none;
}
So, first of all, you're using the same id multiple times, changes these to class instead (as id's can only be used once, and classes can be used multiple times). like this:
$output = '';
foreach($gp as $sp){
$output .= "<div class='pub'>";
$output .= "<h4>" . $sp['title'] . "</h4>";
$output .= "<article class='pub_art'>" . $sp['content'] . "</article>";
$output .= "<p>" . $sp['created'] . "</p>";
$output .= "<p>". $sp['writer'] ."</p>";
$output .= "<button class='hide'>Hide</button>";
$output .= "<button class='show'>Show</button>";
$output .= "</div>";
}
echo $output;
As you can see i've concatenated every single echo into one variable and echo it all at once, which is a better aproach (performance wise)
now for the javascript, you're selecting every single article tag, instead of this we're gonna look for the sibling article which is inside the same div as the hide or show class.
$(document).ready(function(){
$(".hide").click(function(){
$(this).siblings('article').hide();
});
$(".show").click(function(){
$(this).siblings('article').show();
});
});
And your CSS (now also with the class selector)
.pub_art {
width: 100%;
height: 100%;
background-color: blue;
display: none;
}
As you are producing invalid markup with php with having same ids for multiple instances of elements, so change the attribute id to class:
<?php
$page = new CMS();
$gp = $page->getPage();
foreach ($gp as $sp) {
//var_dump($sp);
echo "<div class='pub'>"; // <-----here
echo "<h4>" . $sp['title'] . "</h4>";
echo "<article class='pub_art'>" . $sp['content'] . "</article>"; //<---here
echo "<p>" . $sp['created'] . "</p>";
echo "<p>". $sp['writer'] ."</p>";
echo "<button class='hide'>Hide</button>"; // <------here
echo "<button class='show'>Show</button>"; // <------here
echo "</div>";
}
?>
css:
.pub article.pub_art {
width: 100%;
height: 100%;
background-color: blue;
display: none;
}
Now you can use this script to work:
$(document).ready(function(){
$(".hide, .show").click(function(){
$(this).siblings("article").toggle(this.className === 'show');
});
});
The .hide and .show buttons are siblings of the element then you just need to use .siblings() to access the its sibling article as they all are been wrapped inside a div .pub.
You can ask Jquery to hide the first article above the element clicked by doing so :
$(document).ready(function(){
$("#hide").click(function(){
$(this).prev("article").hide();
});
$("#show").click(function(){
$(this).prev("article").show();
});
});
However i suggest you to change your PHP so that it generate unique IDs in order to create valid HTML.
Related
I have an html form that takes input from a user and php code that takes the input from a specified folder. It then retrieves every image in that folder and displays it in a slideshow.
The problem is that the width of the image stretches and makes it look terrible. I tried the object-fit tactic among other tactics I found online but none of them seem to work.
How do I maintain the aspect ratio of the images inside the cycle-slideshow?
<html>
<head>
<style = "text/css">
</style>
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://malsup.github.com/jquery.cycle2.js"></script>
<?php
$images = array();
$directory = 'images '.$_POST["name"];
if ($handle = opendir($directory)) {
while (false !== ($file = readdir($handle))) {
if (preg_match("/\.png$/", $file)) $images[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $images[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $images[] = $file;
elseif (preg_match("/\.gif$/", $file)) $images[] = $file;
}
shuffle($images);
closedir($handle);
}
?>
<div class="cycle-slideshow">
<?php
for($i= 0; $i < 3; $i++) {
foreach ( new DirectoryIterator($directory) as $item ) {
if ($item->isFile()) {
$path = $directory . '/' . $item;
echo '<img src="' . $path . '" class="displayed"
height= "512px"
object-fit= "contain"
width = "75%"
display: "block"
margin: "auto"
border= "3px solid #73AD21" />';
}
}
}
?>
</div>
</body>
</html>
You should remove width = "75% because you already have height initialized. You can also add padding to the images in your CSS file. Note: For using padding you should actually use box-sizing: border-box. By using border-box you actually add that padding within dimensions of of your box and preventing it to change widht or height of it.
I didn't test it but hope i understood you question.
This question already has answers here:
Is there ever any reason to use padding-top and padding-bottom for inline elements?
(1 answer)
Padding for Inline Elements
(3 answers)
Closed 4 years ago.
This is my code
ul li{
display:inline;
}
li {
padding: 10px;
border: 1px solid brown;
margin-right: 5px;
position: relative;
background-color: Bisque ;
}
<div class="fr_station">
<span id="route">
<?php
// print_r($route);
$pLine = 0;
$cLine = 0;
echo "<ul>";
foreach ($route as $value) {
$result = mysqli_query($conn,'select station,line,stnCode from stn_name where stnCode='.$value.' LIMIT 1') or die(mysqli_error());
$res = mysqli_fetch_array($result);
echo "<li>".$res['station']."</li>";
//echo str_repeat(" ", 3);
if (!isset($previous)) {
$previous = $source;
$present = $source;
} else {
$current = $value;
$d_result = mysqli_query($conn,'SELECT * FROM alt_station_data WHERE stnCode ='.$previous.' AND nei='.$current.' LIMIT 1');
$d_res = mysqli_fetch_array($d_result);
$tot_dist += $d_res['dis'];
$previous = $value;
echo "</tr>";
$floored = floor($tot_dist);
}
}
echo "</ul>";
echo "</span>";
echo "<br>";
echo "</div>";
When I am printing the elements then the elements from 2nd line is overlapping with the ones on the first line and so on at the end of the line it is printing half content on one line and remaining content on next line.
Try this:
li {
display: inline-block;
}
By using inline each li behaves like a word so doesn’t have it’s own ‘box’. inline-block lets them sit side-by-side but gives each one it’s own ‘box’.
If you need even more control then start looking at flex-box: https://css-tricks.com/snippets/css/a-guide-to-flexbox/ and https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout but don’t forget you will need flex-wrap: wrap
On a side note, with your example it would be easier if you just provide the outputted HTML without the php code as that’s not required. :)
Im having an issue where i can't seem to assign an ID from a column in the database to each DIV respectively.
The Scenario: I have a page full of clients and next to each one is a vote up and vote down button. When i click one of them it simply adds +1 to either the positive or negative column.
What is the Issue? The issue is no matter which client i vote for it only updates the ClientID '1'
What have i done so far?
I am using a while loop to retrieve all the clients from the
database. I have given each div that comes through a data-clientid
for $_POST['ClientID'].
I have classes called voteup and votedown so i can reference them in
my JS script.
In my script i assign the clientid from data-clientid to variables
using the classes voteup and votedown
In the voteup/down php files i then use this clientid to use the
update sql to update the column.
What is my code?
My main page that displays the clients and the voting buttons (Shortened to the bit you need to see, connection to the database is included and all of that works fine)
<?php
$clientInfo = "SELECT * FROM Clients ORDER BY Client ASC";
$stmt = sqlsrv_query($conn, $clientInfo);
echo "<div style='width: 100%; display: inline-block;'>";
while ($client = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
echo "<div class='clientid' style='height: 50px; font-size: 18px; vertical-align: middle; display: inline-block; width: 100%'>" .
"
<div style='width: 35%;'></div>
<div onclick=\"voteUp()\" style='display: inline-block; width: 5%;'>
<span style='font-size: 20px;' class='hover-cursor fa fa-chevron-up vote-up'></span>
</div>" .
"<div class='hover-cursor hvr-underline-reveal voteup votedown' data-clientid='{$client['ClientID']}' style='width: 20%; display: inline-block;'>" . $client['Client'] . "</div>" .
"<div onclick=\"voteDown()\" style='display: inline-block; width: 5%;'>
<span style='font-size: 20px; text-align: right;' class='hover-cursor fa fa-chevron-down vote-down'></span>
</div>
<div style='width: 35%;'></div>
</div>
<br />";
}
echo "</div>";
?>
This then links to my scripts file with my JQuery (I set it up to print the ID in the console so i can see which ID it is hitting. Im just going to take Vote Up as an example)
window.voteUp = function() {
var clientid = $(".voteup").data("clientid");
$.post("voteup.php", {clientid: clientid}, function(data) {
console.log("Data:" + clientid)
});
return false;
}
and then there is the voteup.php that i am referring to in my $.post
<?php
if (isset($_POST['clientid'])) {
$voteup = "UPDATE Clients SET Pos = (SELECT MAX(Pos) FROM Clients) + 1 WHERE ClientID = " . $_POST['clientid'];
$stmt = sqlsrv_query($conn, $voteup);
} else {
echo "Failed";
}
?>
Javascript issue
As stated in comments, your Javascript code is getting only the first voteup element in the DOM Tree.
you need to use a dynamic way to find the specific voteup div for the client that you are voting up (or down), try this:
while ($client = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
echo "<div class='clientid' style='height: 50px; font-size: 18px; vertical-align: middle; display: inline-block; width: 100%'>" .
"
<div style='width: 35%;'></div>
<div style='display: inline-block; width: 5%;'>
<span style='font-size: 20px;' class='hover-cursor fa fa-chevron-up vote-up'></span>
</div>" .
"<div class='hover-cursor hvr-underline-reveal voteup votedown' data-clientid='{$client['ClientID']}' style='width: 20%; display: inline-block;'>" . $client['Client'] . "</div>" .
"<div style='display: inline-block; width: 5%;'>
<span style='font-size: 20px; text-align: right;' class='hover-cursor fa fa-chevron-down vote-down'></span>
</div>
<div style='width: 35%;'></div>
</div>
<br />";
}
I've just removed the onclick event of your vote-up and vote-down buttons.
Now you need only one script:
<script>
$(".vote-up").click(function(){
var clientId = $(this).parents(".clientid").find(".voteup").data("clientid");
$.post("voteup.php", {clientid: clientid}, function(data) {
console.log("Data:" + clientid)
});
return false;
});
$(".vote-down").click(function(){
var clientId = $(this).parents(".clientid").find(".votedown").data("clientid");
$.post("votedown.php", {clientid: clientid}, function(data) {
console.log("Data:" + clientid)
});
return false;
});
</script>
Basically we are getting the top parent of vote-up button, the div.clientid, and with it, we search for the div.voteup that contains the clientid data
PHP Issue
Also, your UPDATE query is wrong, you are selecting the MAX(pox) from Clients through a subquery without the where clause, try this:
$voteup = "UPDATE Clients SET Pos = (SELECT MAX(Pos) FROM Clients WHERE ClientID = " . $_POST['clientid']. ") + 1 WHERE ClientID = " . $_POST['clientid'];
Later, try to transform your queries into parametrized queries, to avoid sql injection issues.
I want to add some transition like slidedown, fadein using jquery. when someone clicks on a title city. it opens with effect. I am trying it with jquery but it won't work. Any solution that where i am wrong or solution with css ?
Java Script Code :
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
//------------------- Jq used to show/open single div when click on title link -----------
function showDiv(obj)
{
$('.CityDivInner').css('display','block');
var div = $(obj).find('.CityDivInner').css('display','none');
}
</script>
<script>
$(document).ready(function(){
$(".CityDivOuter").click(function(){
$(".CityDivInner").slideDown("slow");
});
});
</script>
Css Code :
<style>
.CityDivInner
{
display:none;
}
</style>
</head>
Php Code :
<?php
$link = mysqli_connect("localhost", "root", "", "test");
// Check connection
if($link === false)
{
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution
$sql = "SELECT * FROM sample";
if($result = mysqli_query($link, $sql))
{
if(mysqli_num_rows($result) > 0)
{
echo "<div class='cityContainer'>";
while($row = mysqli_fetch_array($result))
{
echo "<div class='cityContainerInner' style='border: 2px solid black;' >
<p class='CityDivOuter' onclick='showDiv(this);'>City</p>
<div class='CityDivInner' style='border: 1px solid black;'>
<p class='CityTitle'>". $row['UserCity'] ."</p>
</div>
</div></br>";
}
echo "</div>";
// Close result set
mysqli_free_result($result);
}
else
{
echo "No records matching your query were found.";
}
}
else
{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
</body>
Check this code, This might help you!
$(document).ready(function(){
$('.expand').hide();
$(".expand, .collapse").click(function(){
$(".CityDivInner").slideToggle("slow");
$('.expand').toggle();
$('.collapse').toggle();
});
});
.CityDivInner{
width:300px;
height:100px;
background:#888;
}
.expand, .collapse{
margin:5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="CityDivInner"></div>
<button class="expand">Expand</button>
<button class="collapse">Collpase</button>
I have the following code which change simple text to textarea field:
$('.field').live({
mouseenter:
function()
{
title='<?php echo $user_title; ?>';
old_value=$(this).text();
item_id=$(this).attr('id');
item=$(this).parent('td');
height=event.target.offsetHeight;
width=event.target.parentNode.offsetWidth;
new_value=(old_value=='Not translated') ? '' : old_value;
$(this).empty();
var field=(title=='Login') ? "<textarea style='vertical-align: middle; font-family: Helvetica; font-size: 12pt; width: 212px;' id='new_value' name='term'>" + new_value + "</textarea>"
: "<textarea style='vertical-align: middle; font-family: Helvetica; font-size: 12pt; width: 212px;' id='new_value' name='term'>" + new_value + "</textarea><div id='save_button' class='btn btn-primary' href='#'>>></div>";
$(this).html(field);
$("#new_value").height(height);
button_id=item_id.split('/')[0];
button_id=button_id.replace(/([!"#$%&'()*+,./:;<=>?#\[\\\]^`{|}~])/g, "\\$1");
$("#"+button_id).show();
$("#new_value").click(function()
{
if (title=='Login')
window.location.replace('<?php echo $fb_url?>');
});
},
mouseleave:
function()
{
$(this).empty();
$(this).html(old_value);
$("#"+button_id).hide();
alert($(this).html());
}
}
);
div block for text:
echo "<td width='250'><div class='field' id='".$record['translate']['label_value']."/".$record['language_id']."'>".
strip_tags($record['translate']['coalesce(loc.language_value)'])."</div>";
It works correcly, but I need to add additional div block:
echo "<td width='250'><div class='field' id='".$record['translate']['label_value']."/".$record['language_id']."'><div style='width: 200px;'>".
strip_tags($record['translate']['coalesce(loc.language_value)'])."</div></div>";
After this action my code doesn't work! It changes text to textarea field, but in "mouseleave" event it doesn't work $(this).empty() construction! Please, tell me, how can I fix it?
Try closing the tag
echo "<td width='250'><div class='field' id='".$record['translate']['label_value']."/".$record['language_id']."'><div style='width: 200px;'>".strip_tags($record['translate']['coalesce(loc.language_value)'])."</div></div></td>";
I added at the end
you must close TD tag just after closing DIV tag.
echo "<td width='250'><div class='field' id='".$record['translate']['label_value']."/".$record['language_id']."'>".
strip_tags($record['translate']['coalesce(loc.language_value)'])."</div>";
You have just forgotten to close TD tag and also id attribute's single quote.
echo "<td width='250'><div class='field' id='".$record['translate']['label_value']."/".$record['language_id']."'>".strip_tags($record['translate']['coalesce(loc.language_value)'])."'</div></td>";
it should works like this. be sure all your html tags and attributes are valid.