change position depending on DB value - javascript

I let people fill in a form, and insert distances etc. They get stored in a db.
Then I lead them to a page, where I show the number of axles (12 in this case) and make a circle of them (in css)
Then it looks like this:
The code for this:
<?php
$show_axle = $database->axles($_GET['train_id']);
?>
<div id="axle_bogie_border">
<div id="axle_position">
<?php
foreach($show_axle as $axlefigure){ ?>
<div id='number_of_axles'> <?php echo $axlefigure['axle'] ?></div>
<?php
}
?>
</div>
</div>
The axle_border make the Train image (The black rectangle)
The axle_position take care that the axles (Numbers actually) Don't go in the image but slightly below it (So it looks like wheels/axles).
The Number_of_axles make the numbers look like a circle (Like wheels/axles).
Now the function:
function axles($id){
$sql = "SELECT * FROM axle WHERE train_id = :id2";
$sth = $this->pdo->prepare($sql);
$sth->bindParam(":id2", $id, PDO::PARAM_STR);
$sth->execute();
return $sth->fetchAll();
}
The function selects everything from the table axle (See first image).
Now, I actually want the axles to take a position. And I'm thinking about doing that via the Distance row.
So:
Axle 1 has the number 5 for distance. So it goes 5px from the far left
Axle 2 has the number 10. So i want it 10 pixels next to the axle 1.
Axle 3 has the number 5. So i want it 5 pixels next to the axle 2.
Etc.
Eventually it needs to look like this:
My question: Is this posible. If yes, how?
EDIT:
it is working now :)
I did the following:
<?php
$show_axle = $database->axles($_GET['train_id']);
?>
<div id="axle_bogie_border">
<div id="axle_position2">
<?php
foreach($show_axle as $axlefigure){ ?>
<div style="margin-left:<?php echo $axlefigure['distance'];?>px;">
<?php echo $axlefigure['axle'] ?>
</div>
<?php
}
?>
</div>
</div>
And the css:
#axle_position2 {
margin-top: 9%;
position: relative;
float: left;
}
#axle_position2 div {
background: green;
float: left;
position: inline-block;
width: 40px;
height: 40px;
border-radius: 50px;
}

Related

How can I get the full height parallax images to stick to the top of the screen shrunk into stripes underneath each other?

I'm working on an animation. According to the plans, I should implement the following: 4 parallax images that fill the entire screen width and screen height (100vh, 100vw) are positioned one below the other (their number may change, since these images are preview images of galleries, and the user can add new galleries through the WordPress back end. I use ACF and CPT UI plugins, and I go through the posts' fields in PHP with a foreach loop). So the point would be that as you scroll down, the first parallax image sticks to the top, the next parallax image sticks 124px lower, and at the end, when you have already scrolled down completely, only 4 pieces of 124 px narrow strips remain from the full screen height images (100vh).
I wrote some JavaScript code, I looped through the image containers and I got the top position of each iteration with the getBoundingClientRect() method. The header is sticky and it's height is 62px, so I'm not checking if the top of the div has reached 0, but 62px. So when the first div with the image reaches 62px, it has to stop and stick, the second div has to stop at 62px + 124px (height of the strip that should remain of the full height image) and so on. I do not know what am I doing wrong, but now when the first image reaches the top, every image container disappears from the screen. I hope I have put it clearly and if someone can help, I would be very grateful.
HTML:
<?php
$posts = get_posts(array(
'posts_per_page' => -1,
'order' => 'ASC',
'post_type' => 'galleries'
));
if ($posts) :
?>
<?php foreach ($posts as $post) :
setup_postdata($post);
?>
<div class="gallery-preview-card" style="height: 100vh; background-image: url('<?php echo get_the_post_thumbnail_url(); ?>'); background-attachment: fixed; background-position: center; background-repeat: no-repeat; background-size: cover;" data-target="<?php the_permalink(); ?>" id="gallery-preview-card-id-<?php echo get_post_thumbnail_id($post); ?>">
<h3 class="gallery-title">
<?php echo the_title(); ?>
</h3>
</div>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
JS:
let galleryPrevs = document.querySelectorAll('.gallery-preview-card');
document.addEventListener('scroll', scroll, false);
function scroll(n) {
for (let i = 0; i < galleryPrevs.length; i++) {
let divTop = galleryPrevs[i].getBoundingClientRect().top;
if (divTop < 62 + 124 * i) {
galleryPrevs[i].style.position = 'fixed';
galleryPrevs[i].style.top = 62 + 124 * i;
}
}
}

Retrieving and Formatting Data Properly From MYSQL

Okay so I'm trying to create a replica of the Billboard Hot 100. I have already a database and the page with the proper format I want. But when I tried to retrieve the data from the database, the format I used became a huge mess and a lot of errors appeared.
Here's my code:
<div class="chartsList">
<ul class="charts" style="list-style: none;">
<?php
$songQuery = mysqli_query($con, "SELECT * FROM songs ORDER BY sales DESC LIMIT 100");
while($row = mysqli_fetch_array($songQuery)) {
$i = 2;
foreach($songQuery as $songId)
echo "<li class='chartsRow'>
<div style='width:10%;height:100%;float:left; text-align: center;color:black;font-size: 40px;line-height: 150px;font-weight: 600;'>$i</div>
<img style='height: 30%; float: right; position: relative; top: 50; right: 89%;'src='" . $row['movement'] . "'>
<img type='button' style='float: right;width: 25px;position: relative;top: 60;'onclick='myFunction()'src='assets/icons/expand.png'>
<div style='width:90%; height:100%; display: block;''>
<div style='width:15%;height:100%;float:left'>
<img style='height: 90%;margin-top: 8;'src='". $row['coverArt'] . "'>
</div>
<div style='width:85%; height: 100%;margin-left: 26%;''>
<a style='font-size: 30px; font-weight: 600; position: relative; top: 30;'>" . $row['title'] . "</a>
<p style='position: relative;top: 10;''>" . $row['artist'] . "</p>
</div>
</div>
<div id='moreinfo'>
<div class='lefty'>
<a>" . $row['lastWeek'] . "</a>
<p>LAST WEEK</p>
</div>
<div class='lefty' style='border-left-style: solid;border-left-width: 1px;border-right-style: solid;border-right-width: 1px;border-right-color: #b7b7b7; border-left-color: #b7b7b7;'>
<a>" . $row['peak'] . "</a>
<p>PEAK POSITION</p>
</div>
<div class='lefty'>
<a>" . $row['woc'] . "</a>
<p>WEEKS ON CHART</p>
</div>
</div>
</li>";
$i = $i + 2;
}
?>
</ul>
</div>
Current Issue:
"Warning: mysqli_fetch_array() expects parameter 1 to be
mysqli_result, boolean given in C:\xampp\htdocs\billboard\hot-100.php
on line 52"
What I'm trying to achieve is something that looks like this: https://www.billboard.com/charts/hot-100 but with the rows from 2-100 taking up 60% of the screen and a lower portion that can appear/disappear when clicking the extend icon.
Not sure what all the errors are but the main issue here is that you need to turn on error reporting and check for connection errors before trying to use the query and then also check for errors after running the query but before accessing the result set.
I have removed the inner foreach loop because it is redundant. You can create a counter by simply incrementing a variable. See comments in code.
<?php
// Turn on error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Turn MySQL errors into PHP exceptions
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// I assume you have a procedural-style connection setup here.
$con = mysqli_connect("localhost", "xxx", "xxx", "xxx");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
<div class="chartsList">
<ul class="charts" style="list-style: none;">
<?php
$counter = 0;
$songQuery = mysqli_query($con, "SELECT * FROM songs ORDER BY sales DESC LIMIT 100");
// Now, check if your query has an error
if ($songQuery === false){
die('Error in query: ' . mysqli_error($con));
}
while ($row = mysqli_fetch_array($songQuery)) {
// Your HTML appears to be malformed. I'm getting all sorts of errors in my IDE.
// Removing the HTML here but you should be able to merge that back in without issues.
// If you need a counter to display row numbers, you can just create one.
// Notice I created a $counter variable above.
// increment it by:
// $counter++; to increment by 1 OR
// $counter = $counter + 2; to increment by 2
// Now, use $row['column_name'] where you need it.
} ?>
</ul>
</div>
EDIT
Sounds like you're also having CSS/styling issues. Get the DB query going first and then ask a new, specific question with more details including screen shots.

Change Height of Div After Ajax Call

PROBLEM:
I have a dynamic form that is using JQuery steps to make it a wizard. Right now, there is a step where a drop down box selection triggers an AJAX call that then adds form fields to the form. I need the height of the div that this field is in to become longer based off of the amount of fields added.
IMAGES:
The form starts with two drop downs:
Once something is selected for the second dropdown, the AJAX call is made and the form appends fields.
The grey box should resize to accomodate the appended fields.
CODE:
The CSS for the div is as follows:
.wizard > .content
{
background: #eee;
display: table-cell;
margin: 0.5em;
min-height: 35em;
position: relative;
width: auto;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
I can add a permanent height here, but it's not dynamic.
The form is a Zend Form, so the HTML is as follows:
<div class="container-fluid">
<?php if ($this->error) : ?>
<div class="row-fluid">
<?php echo $this->error; ?>
</div>
<?php else : ?>
<?php echo $this->form()->openTag($form); ?>
<h3>Details</h3>
<section>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_PROJECT_NAME, false, true); ?>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_PROJECT_DUE_DTTM, !($this->uberAdmin)); ?>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_PROJECT_DESCRIPTION); ?>
</section>
<h3>Options</h3>
<section>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_REVIEW_PROJECT); ?>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_WTL_PROJECT); ?>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_JOB_TABLE); ?>
</section>
<h3>Project Configuration</h3>
<section>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_PROJECT_TYPES, !($this->uberAdmin), true); ?>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_PROJECT_SUBTYPES, !($this->uberAdmin)); ?>
<?php
echo $this->partial('project/project/dynamicFormElements.phtml', array('form' => $this->projectForm, 'div' => 'project-config-elts'));
?>
</section>
<h3>Workflow Configuration</h3>
<section>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_WORKFLOW_TYPES, !($this->uberAdmin)); ?>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_WORKFLOW_SUBTYPES, !($this->uberAdmin), true); ?>
<?php echo FormElementFactory::create($this, ProjectForm::KEY_PROJECT_WORKFLOW_CONFIG, !($this->uberAdmin)); ?>
</section>
This generates HTML with the structure below:
The highlighted div is the div in question.
My AJAX call is done here:
// Handle AJAX dynamic form creation results
function updateProjectForm(resp) {
$('div#project-config-elts').html(resp.html);
}
// Handle ajax error
function projectFormError(req, status, err) {
var errorString = '<div class="row-fluid alert alert-error">' +
'Error retrieving project form.' +
'</div>';
$('div#project-config-elts').html(errorString);
}
// AJAX request to get dynamic Project config form
function requestProjConfigForm() {
var request = {project_type: $('select[name=project_types]').val(),
project_subtype: $('select[name=project_subtypes]').val()
};
var ajaxOptions = {
url: 'projectform',
type:'POST',
dataType: 'json',
success: updateProjectForm,
error: projectFormError,
data: request
};
// Initiate the request!
$.ajax(ajaxOptions);
}
$('select[name=project_types]').change(function(){
updateProjectSubtypes();
});
// Handle a change in the selection of the particular project
$('select[name=project_subtypes]').change(function(){
requestProjConfigForm();
});
$('select[name=workflow_types]').change(function(){
updateWorkflowSubtypes();
});
$.validator.addMethod("validJSON", function(val, el) {
try {
JSON.parse(val);
return true;
} catch(e) {
return false;
}
}, "*Not valid JSON");
form.validate({
errorPlacement: function(error, element) {
$( element )
.closest( "form" )
.find( "label[for='" + element.attr( "id" ) + "']" )
.append( error );
},
rules: {
project_config: { validJSON: true }
}
});
I'm thinking that here I can dynamically change the height, but I'm not quite sure how to do so.
It looks like you're running into an issue that has been discussed on the jQuery Steps plugin github page: https://github.com/rstaib/jquery-steps/issues/147
basically, since the body of the step content is positioned absolutely with a percent height, it's height is no longer based on the content within it. A few things people used to try to fix this are:
By waqashsn:
.content > .body{
/*position: absolute*/
float:left;
width:95%;
height:95%;
padding:2.5%
}
Here's another alternative by AneeshRS that instead causes overflowing content to scroll:
.wizard.clearfix > .content.clearfix{
min-height: 500px;
overflow-y: auto;
}
Checkout the link to the issues page for a better explanation of either of these. Note however that any solution that involves removing the absolute positioning will likely cause transitions to no longer work.

Run Jquery Slide Toggle on while elements

I have a problem in running jquery . Here the table sample:
table database
id | name | value
1 data1 10
2 data2 20
3 data3 30
4 data4 40
5 data5 50
Here is my code:
<?php
$sql = "SELECT * FROM database ORDER BY id"
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{?>
<div id="flip">
<?php echo $row['name']?>
</div>
<div id="panel">
<?php echo $row['value']?>
</div>
<?php
}
?>
But the slide toogle jquery only execute once, on the first element. How to make slide toggle execute every row in while looping?
Here is my slidetoggle()Jquery:
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideToggle("slow");
});
});
</script>
And the CSS :
<style>
#panel, #flip {
padding: 5px;
text-align: center;
background-color: #e5eecc;
border: solid 1px #c3c3c3;
}
#panel {
padding: 50px;
display: none;
}
</style>
Based on Jack A. answer, build first your HTML with classes instead of multiples IDs. Then, in your script, use jQuery.next() to find the next panel element and toggle it:
$(document).ready(function(){
$(".flip").click(function(){
$(this).next('.panel').slideToggle("slow");
});
});
Here is a jsfiddle illustrating this.
You are using the same id in multiple elements. Build a unique id for every element. E.g. flip1, flip2, etc. and panel1, panel2, etc.
You are creating multiple HTML elements with the same ID ("flip" and "panel"), which is not correct; IDs should be unique.
An alternative is to use a class instead of an ID:
while($row = $result->fetch_assoc())
{?>
<div class="flip">
<?php echo $row['name']?>
</div>
<div class="panel">
<?php echo $row['value']?>
</div>
<?php
}
JavaScript:
$(document).ready(function(){
$(".flip").click(function(){
$(".panel").slideToggle("slow");
});
});
This will act on all of the elements simultaneously.

Why is JavaScript styling working with all browsers except Internet Explorer?

I'm using video JS HTML5 player to play some videos and I want to add a visual representation of the chapters underneath the video player.
I'm basically grabbing how many chapters there are from the database and create that number of the divs with PHP.
<div class="chapter-progress">
<div class="chapter-breaker"></div>
<? $tableName = 'sourceChapters';
$mysqlQuery = "SELECT * FROM " . $tableName . " WHERE recSourceId = "
.$sourceVideo['recId']. " ORDER BY recOrdering ASC;";
$sourceChapters = mysql_query($mysqlQuery); ?>
<? $chapterBreakerNo = 0; ?>
<? while($chapterBreakers = mysql_fetch_array($sourceChapters)){ ?>
<div class="chapter-breaker-title" id="chapter-breaker-title<?=$chapterBreakerNo?>">
<p><?=$sourceChapters['recContent']?></p></div>
<div class="chapter-breaker" id="chapter-breaker<?=$chapterBreakerNo?>"></div>
<? $chapterBreakerNo++ ?>
<? } ?>
<div class="chapter-breaker-title" id="last-title"></div>
<div class="chapter-breaker" style="float:right"</div>
</div>
So there is chapter-breaker-title divs that are going to be styled to be the actual size of the chapters and there are chapter breaker which are just a line, 1% thick to split the chapters.
I then use a JavaScript onload function to style these divs.
/* -----------------------------------------------function for styling the chapter progress bar ---------------------------------------*/
function styleChapters(){
//also run the chapter system on load
chapterSys();
// total video duration
var duration = myPlayer.duration();
//find the time difference for the first chapter , this is just the chapter time
var timeDif = (<?=$chapterPlayOffsets[0]?>);
// work out the percentage width for the div width
var percentageMargin = ((timeDif/duration) * 100 -1);
//get the first chapter breaker title and style the width
document.getElementById("chapter-breaker-title0").style.width = percentageMargin + "%";
document.getElementById("chapter-breaker-title0").innerHTML="00";
// for the rest of the chapters
<? for($i=1;$i<count($chapterPlayOffsets);$i++) { ?>
//total video duration
var duration = myPlayer.duration();
// find the difference between the chapter and the previous chapter
var timeDif = (<?=$chapterPlayOffsets[$i]?>) - (<?=$chapterPlayOffsets[$i-1]?>);
// get the percentage for div length minus 1% for the width of the chapter breakers
var percentageMargin = ((timeDif/duration) * 100) -1;
//style each of the divs width
document.getElementById("chapter-breaker-title<?=$i?>").style.width = percentageMargin + "%";
//put the chapter title in
document.getElementById("chapter-breaker-title<?=$i?>").innerHTML="<?= $chapterTitles[$i-1] ?>";
<? } ?>
//put the last title in
<? $lastTitle = count($chapterPlayOffsets)-1 ?>
document.getElementById("last-title").innerHTML="<?=$chapterTitles[$lastTitle] ?>";
}
So this is what it should look like:
The problem is that this works on all browsers apart from Internet Explorer.
It's as if the divs are not having their width styled at all.
So it looks like this:
If anyone can see or explain why this may not be working, it would be very helpful
.chapter-progress{
width:100%;
height:20px;
background: rgb(255,204,0)
url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAYAAAAGCAYAAADgzO9IAAAAP0lEQVQIHWWMAQoAIAgDR/QJ/Ub//04+w7ZICBwcOg5FZi5iBB82AGzixEglJrd4TVK5XUJpskSTEvpdFzX9AB2pGziSQcvAAAAAAElFTkSuQmCC)
-50% 0 repeat;
margin:auto;
float:left;
}
.chapter-breaker{
height:100%;
width:1%;
background-color: rgb(0, 51, 153);
float:left;
}
.chapter-breaker-title{
height:100%;
float:left;
}
HTML output :
div class="chapter-progress">
<div class="chapter-breaker"></div>
<div class="chapter-breaker-title" id="chapter-breaker-title0">
00
</div>
<div class="chapter-breaker" id="chapter-breaker0"></div>
<div class="chapter-breaker-title" id="chapter-breaker-title1">
01
</div>
<div class="chapter-breaker" id="chapter-breaker1"></div>
<div class="chapter-breaker-title" id="chapter-breaker-title2">
02
</div>
<div class="chapter-breaker" id="chapter-breaker2"></div>
<div class="chapter-breaker-title" id="chapter-breaker-title3">
03
</div>
<div class="chapter-breaker" id="chapter-breaker3"></div>
<div class="chapter-breaker-title" id="chapter-breaker-title4">
04
</div>
<div class="chapter-breaker" id="chapter-breaker4"></div>
<div class="chapter-breaker-title" id="last-title">
05
</div>
<div class="chapter-breaker" style="float: right;">
</div>
</div>
The ouput of the divs all seem fine to me but the javascript has not styled the width of the chapter-breaker-title divs
Just in case anyone gets a similar problem I had to put a time delay on my javascript to make it work , so before the page must not have loaded fully when my script was firing .

Categories