Carousel need to start from middle slide on page load - javascript

I have using Multi Carousel to display complete months dates in a slider. Each date some data be hide on click. When I browse to Multi Carousel clicked date is today,s date, Means active class for slides is current date.
But as slider have 30 days. so slider always start from day 1. I always need to slide it to current date by clicking next arrow.
Like today is sep-26. If you check following page you find a date slider there which is on sep-1 now. so to get sep-26 you need to slide next. http://prosport.guru/ps/game.php
I want that when page load slider should moves to current date auto. I have add auto class to current date slide but it did not work.
Following is my code for Multi Carousel.
<?php
$page2 = $_SERVER["PHP_SELF"];
$page2 = explode("/", $page2);
$page2 = $page2[count($page2) - 1];
$id_sport2 = $_GET["id_sport"];
$m = date("m");
$day = date("d");
$year = date("Y");
$dates = array();
$dates2 = array();
$tmp = array();
for ($i = 1; $i < 32; $i++) {
if ($i < 10) {
$ii = "0$i";
} else {
$ii = $i;
}
$date = "$year-$m-$ii";
//$date = date("Y-m-d", strtotime($date));
if ($i % 3 != 0) {
array_push($tmp, $date);
if ($i == 60) {
if (count($tmp != 0)) {
array_push($dates2, $tmp);
}
}
} else {
array_push($tmp, $date);
array_push($dates2, $tmp);
$tmp = array();
}
array_push($dates, $date);
}
///print_r($dates2);
?>
<div class="row" style="border:1px solid silver; background: #a0a0a0; color: white; ">
<div class="MultiCarousel" data-items="1,3,5,6" data-slide="3" id="MultiCarousel2" data-interval="1000" >
<div class="MultiCarousel-inner">
<?php
$cpt = 0;
for ($i = 0; $i < count($dates2); $i++) {
$line = $dates2[$i];
$today = date("Y-m-d");
if (empty($_GET["date"])) {
$goto = $today;
if (in_array($today, $line)) {
$active = "active";
} else {
$active = "";
}
} else {
$dt = $_GET["date"];
$goto = $dt;
if (in_array($dt, $line)) {
$active = "active";
} else {
$active = "";
}
}
for ($x = 0; $x < count($line); $x++) {
$el = $line[$x];
if (!empty($_GET["date"])) {
$dt = $_GET["date"];
if ($el == $dt) {
$color = "red";
} else {
$color = "white";
}
} else {
if ($el == $today) {
$color = "red";
} else {
$color = "white";
}
}
$href = "$page2?id_sport=$id_sport2&date=$el";
if ($x == 0) {
//echo "<div class='col-lg-1 col-xs-1'> </div>";
//echo "<div class='col-lg-10 col-xs-10'>";
}
/* echo ' <div class="col-md-4 col-xs-4 col-lg-4 ">
'.$el.'</div>';
*/
if ($x == 2) {
//echo "</div>";
}
?>
<div class="item " style="text-align:center">
<a href="<?php echo $href; ?>" >
<p class=" sportName mydate p-date" real="<?php echo $el; ?>" style="color:white; font-size: 12px; text-align: center;" >
<?php
$date = $el;
$month_name = ucfirst(strftime("%b", strtotime($date)));
$day_number = ucfirst(strftime("%d", strtotime($date)));
echo $month_name . ' ' . $day_number;
?>
</p>
</a>
</div>
<?php
}
}
echo "<input type='hidden' value='$goto' id='cd'>";
?>
</div>
<button class="btn btn-primary btn-sm leftLst" style="border-radius: 0px; top: calc(64% - 20px);"><</button>
<button class="btn btn-primary btn-sm rightLst fw" style="border-radius: 0px; top: calc(64% - 20px);">></button>
</div></div>
<script>
$(document).ready(function () {
var cd = $("#cd").val();
$(".mydate").each(function () {
var cd_tmp = $(this).attr("real");
if (cd_tmp != cd) {
//alert(cd_tmp+" is different from "+cd);
//$(".fw").click();
} else {
$(this).addClass("tag tag-danger active");
//break;
}
})
})
</script>

This jquery script will move it to the current date on page load.
$(function() {
// Get month and day, ex. "Sep 21"
var monthAndDay = new Date().toLocaleString("en-us", { month: "short" }) + ' ' + new Date().getDate();
// Locate the carousel item using month and day string
var $list = $('#MultiCarousel2 > div .item');
var $carouselToday = $('#MultiCarousel2 > div .item a p:contains('+monthAndDay+')');
var $parent = $carouselToday.closest('.item');
var index = $list.index( $parent );
var itemWidth = $list.eq(0).width();
var position = (index * itemWidth) * -1;
$('#MultiCarousel2 > div').css({"transition": "0s", "transform": "translate("+ position +"px)"});
$('#MultiCarousel2 > div').one("webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend", function() {
$(this).css({"transition": "1s ease all"})
});
});

Related

How to asynchronously preload images

I have a set of videos that I exported to frames and show current frame based on scroll position (something like this but using image frames instead of video)
And using this in <head> casues lots of initial delay but afterwards the frame transition is very smooth.
<?php for ($i = 0; $i <= 99; $i++) {
$number = $i < 10 ? '0'.$i : $i; ?>
<link rel="preload" href="<?php echo get_stylesheet_directory_uri()?>/media/frames/01/optim/_scene-1-00<?php echo $number; ?>.jpg" as="image">
<?php } ?>
<?php for ($i = 0; $i <= 99; $i++) {
$number = $i < 10 ? '0'.$i : $i; ?>
<link rel="preload" href="<?php echo get_stylesheet_directory_uri()?>/media/frames/01/optim/_scene-2-00<?php echo $number; ?>.jpg" as="image">
<?php } ?>
<?php for ($i = 0; $i <= 99; $i++) {
$number = $i < 10 ? '0'.$i : $i; ?>
<link rel="preload" href="<?php echo get_stylesheet_directory_uri()?>/media/frames/01/optim/_scene-3-00<?php echo $number; ?>.jpg" as="image">
<?php } ?>
...
Any thought on how can I only preload the first scene and the rest to be preloaded after window.onload ?
I ended up Doing it like so:
function preloadRestOfScenes() {
/* Scene 2 */
let html = "";
for (let i = 0; i <= 249; i++) {
let number;
if (i < 10) {
number = "00" + i;
} else if (i >= 10 && i < 100) {
number = "0" + i;
} else {
number = i;
}
html += `<link rel="preload" href="${stylesheet_directory_uri}/media/frames/02/optim/scene-2-${number}.jpg" as="image">`;
}
document.querySelector("head").insertAdjacentHTML("beforeend", html);
/* Scene 3 */
html = "";
for (let i = 0; i <= 549; i++) {
let number;
if (i < 10) {
number = "00" + i;
} else if (i >= 10 && i < 100) {
number = "0" + i;
} else {
number = i;
}
html += `<link rel="preload" href="${stylesheet_directory_uri}/media/frames/03/optim/scene-3-${number}.jpg" as="image">`;
}
document.querySelector("head").insertAdjacentHTML("beforeend", html);
/* Scene 4 */
html = "";
for (let i = 0; i <= 299; i++) {
let number;
if (i < 10) {
number = "00" + i;
} else if (i >= 10 && i < 100) {
number = "0" + i;
} else {
number = i;
}
html += `<link rel="preload" href="${stylesheet_directory_uri}/media/frames/04/optim/scene-4-${number}.jpg" as="image">`;
}
document.querySelector("head").insertAdjacentHTML("beforeend", html);
}
And
window.onload = () => {
preloadRestOfScenes();
};

How to enable disable option value in select based on condition PHP

After user select location,in the next select option which is select car, will show list of car in selected location..The list of car retrieved direct from database..So i need to display all the car list in that area and need to disable enable the car list according the condition which is if the car id is not available the option value will disabled..and the option value become enable if car id is available..
<?php
$car = "SELECT *,location_master.location_id , location_master.location_name,
appcarinfo.loc_id_ext, appcarinfo.location ,appcarinfo.model ,appcarinfo.noplat FROM location_master
INNER JOIN appcarinfo ON
appcarinfo.lat = location_master.gmaplat
AND
appcarinfo.lon = location_master.gmaplng
where appcarinfo.model='".$fetchres['idmodel']."' ";
$qcar = mysqli_query($conn, $car);
?>
<option disabled value="" selected hidden>Please Select Car</option>
<?php
while ($showcar= mysqli_fetch_array($qcar))
{
if ($showcar['car_id']=="Available")
{
?>
<option class="<?php echo $showcar['lon']; ?>" value="<?php echo $showcar['car_id']; ?>" enabled> <?php echo $fetchres['maker'].' '.$fetchres['model_name'].'-'.$showcar['noplat'].' ' .$showcar['location_name']; ?></option>
<?php
}
else
?> <option class="<?php echo $showcar['lon']; ?>" value="<?php echo $showcar['car_id']; ?>" disabled> <?php echo $fetchres['maker'].' '.$fetchres['model_name'].'-'.$showcar['noplat'].' ' .$showcar['location_name']; ?></option>
<?php
}
?>
</select>
SELECT OPTION
I'm also new to AJAX..how to pass data and retrieve it back to select option
//check availability car
function check_availability()
{
//id from form
var reservation1 = document.getElementById("reservation");
var pickup_date = document.getElementById("pickup_date").value;
var return_date = document.getElementById("return_date").value;
var pickup_time = document.getElementById("pickup_time").value;
var return_time = document.getElementById("return_time").value;
var carID= document.getElementById("carID").value;
$.ajax({
type : "POST",
url : "function/check_car_availability.php",
data : {
pickup_date : pickup_date,
return_date : return_date,
pickup_time : pickup_time,
return_time : return_time,
carID : carID,
},
dataType : "JSON",
success : function(data) {
$('#edt_pickup').val(data.edt_pickup);
$('#edt_return').val(data.edt_return);
$('#msgCheck').html(data.msgCheck);
$('#btn_proceed').html(data.btn_proceed);
}
});
}
check_car_availability.php
<?php
if ($_POST['pickup_date'])
{
$pickup_date = $_POST['pickup_date'];
$return_date = $_POST['return_date'];
$pickup_time = $_POST['pickup_time'];
$return_time = $_POST['return_time'];
$car_id = $_POST['car_id'];
$owner_id = $_POST['owner_id'];
//convert normal date to epoch
$pickup_date1 = explode("/",$pickup_date);
$return_date1 = explode("/",$return_date);
$pickup_time1 = explode(":",$pickup_time);
$return_time1 = explode(":",$return_time);
//hour, minute, second, month, day, year
$edt_pickup = mktime($pickup_time1[0],$pickup_time1[1],0,$pickup_date1[1],$pickup_date1[0],$pickup_date1[2]);
$edt_return = mktime($return_time1[0],$return_time1[1],0,$return_date1[1],$return_date1[0],$return_date1[2]);
//convert from d/m/Y to Y-m-d
$pickup_date_2 = $pickup_date1[2]."-".$pickup_date1[1]."-".$pickup_date1[0];
$return_date_2 = $return_date1[2]."-".$return_date1[1]."-".$return_date1[0];
//keluarkan tarikh yg customer pilih ada tak dlm booking master
$chkBooked = mysqli_query($conn, "SELECT count(car_id) AS countid FROM appbooking WHERE
((start_rent >= '$edt_pickup' AND end_rent <= '$edt_return')
OR (((start_rent <= '$edt_pickup' AND end_rent >= '$edt_return')))
OR (((end_rent >= '$edt_pickup' AND end_rent <= '$edt_return')))
OR (((start_rent >= '$edt_pickup' AND start_rent <= '$edt_return')))) AND car_id = '$car_id' AND status !='0'");
$fetchBooked = mysqli_fetch_array($chkBooked);
if($fetchBooked['countid'] != 0) //kalau ada show not available
{
$availability = "Not Available";
$available_count = 0;
} else //kalau tak de show available
{
$availability = "Available";
$available_count = 1;
}
//keluarkan car details
$carDetails = mysqli_query($conn, "SELECT * FROM appcarinfo WHERE car_id = '$car_id'");
$fetchchkowner = mysqli_fetch_array($carDetails);
//kalau manual availability check ada tak date dlm range yg owner dah set
$sql = mysqli_query($conn, "SELECT count(car_availability.availability_id) AS cntAvail FROM appcarinfo INNER JOIN car_availability ON car_availability.car_id = appcarinfo.car_id WHERE appcarinfo.car_id = '$car_id' AND car_availability.start_available <= '$edt_pickup' AND car_availability.end_available >= '$edt_return'");
$fetch = mysqli_fetch_array($sql);
if ($fetchchkowner['custom_availability'] == 1) //if owner set manual availability
{
if ($fetch['cntAvail'] > 0) //kalau ada
{
$avail = 1;
} else //kalau tak de
{
$avail = 0;
}
} else //if owner set auto availability
{
$avail = 1;
}
//check if this is klezcar car
if($fetchchkowner["owner_id"] == "0")
{
$klezcar_loc_id = $fetchchkowner["loc_id_ext"];
//check availability for blocked date klezcar
$sqlBlock = "SELECT * FROM `blocked_date_klezcar` where (
('".$pickup_date_2."' > startdate and '".$pickup_date_2."' < enddate)
or ('".$return_date_2."' > startdate and '".$return_date_2."' < enddate)
or ('".$pickup_date_2."' = startdate)
or ('".$return_date_2."' = enddate)
or ('".$return_date_2."' = startdate)
or ('".$return_date_2."' = enddate)
) and (location=0 or location=".$klezcar_loc_id.") order by location desc limit 1";
$queryBlock = mysqli_query($conn,$sqlBlock);
if(mysqli_num_rows($queryBlock) > 0)
{
$resBlock = mysqli_fetch_object($queryBlock);
$avail = 0;
$klezcar_blocked = 1;
$klezcar_blocked_reason = $resBlock->reason;
}
else
{
$klezcar_blocked = 0;
}
}
//calculation price rate
include 'calculation_price/calculationprice.php';
$encry = md5($edt_pickup.$edt_return.$total_pay.$total_rate.floor($day).$bhourplus.$car_id.$owner_id.$secretAuth);
//combine appbooking & car availability variable
if ($avail == 1 && $available_count == 1)
{
$availStatus = "<div class='alert alert-success'>You are good, car available.<br>Rental Price : Total <span style='font-size:20px; font-weight: bold;'>".number_format($total_pay,2)."</span> for ".floor($day)." day(s) ".$bhourplus." hour(s)</div>";
$btn_proceed = "<a href='confirmbooking.php?pickupdate=".$edt_pickup."&returndate=".$edt_return."&totalpay=".$total_pay."&totalrate=".$total_rate."&bookday=".floor($day)."&bookhour=".$bhourplus."&carid=".$car_id."&ownerid=".$owner_id."&encry=".$encry."' class='btn btn-primary'>Proceed</a>";
} else
{
$availStatus = "<div class='alert alert-danger'>We are sorry, car not available. Please refer Available & Not available date table.</div>";
$btn_proceed = "";
if($klezcar_blocked === 1)
{
$availStatus = "<div class='alert alert-danger'>".$klezcar_blocked_reason."</div>";
$btn_proceed = "";
}
}
/* *** SPECIAL FOR RAYA 2019 *** */
$start_blocked_date = "2019-06-04";
$end_blocked_date = "2019-06-09";
if( ($pickup_date_2 >= $start_blocked_date && $pickup_date_2 <= $end_blocked_date)
|| ($return_date_2 >= $start_blocked_date && $return_date_2 <= $end_blocked_date)
|| ($pickup_date_2 == $start_blocked_date)
|| ($return_date_2 == $end_blocked_date)
|| ($return_date_2 == $start_blocked_date)
|| ($return_date_2 == $end_blocked_date))
{
$availStatus = "<div class='alert alert-danger'>The date has been marked as Hari Raya Aidlifitri holiday session. We accept minimum rental of 7 days and above only. Please re-select date at least 3/6/2019 - 10/6/2019.</div>";
$btn_proceed = "";
}
/* *** SPECIAL FOR RAYA 2019 *** */
//return value
$data['edt_pickup'] = $edt_pickup;
$data['edt_return'] = $edt_return;
$data['msgCheck'] = $availStatus;
$data['btn_proceed'] = $btn_proceed;
$data['total_rate'] = $total_rate;
$data['total_pay'] = $total_pay;
$data['no_day_booking'] = floor($day);
$data['no_hour_booking'] = $bhourplus;
echo json_encode($data);
}
?>

Add Active Link Class

I have a dynamic navigation bar that stores the pages/URLs in a database. The nav.php is the script that handles displaying and running through the SQL queries to display the links. I'm having a difficult time adding a script that adds an active class to the links.
My page URLs are as follows:
/page/2/full-service-fleet
/rate-request
/employment
/page/5/links
/page/6/contact
PHP:
<nav>
<?php
while ($row = $result->fetch_assoc())
{
$navid = $row['id'];
$navname = $row['nav'];
$navslug = $row['slug'];
$navurl = $row['url'];
$navnum = $row['num'];
if ($navurl != ''){
$navlink = $navurl;
}
else{
$navlink = "page.php?id=".$navid."&title=".$navslug;
}
if (substr($navlink,0,4) != "http"){
if ($server_name <> "") {
$navlink = "http://".$server_name."/".$navlink;
}
}
if ($navurl == '#'){
$navlink = $navurl;
}
if ($navnum ==0){
?>
<?php echo $navname; ?>
<?php
}else{
?>
<!-- the rest isn't necessary -->
......
</nav>
Browser Rendered Output
The actual links that are being displayed is this line:
<?php echo $navname; ?>
JS Script:
jQuery(document).ready(function($){
// Get current path and find target link
var path = window.location.pathname.split("/").pop();
// Account for home page with empty path
if ( path == '' ) {
path = 'index.php';
}
var target = $('nav a[href="'+path+'"]');
// Add active class to target link
target.addClass('active');
});
You can use this code as it is or you can grab some idea from this one
:
<div class="w3-top" style="z-index: 999;">
<div class="navcontainer">
<div class="w3-hide-small">
<img src="/images/-logo.png" alt="U.S. Transportation" title="" style="">
<div class="abovenav w3-right">
<button class="w3-button w3-round-large" onclick="">Customer Login</button>
<button class="w3-button w3-round-large" onclick="">Carrier Login</button>
</div>
</div>
<div class="w3-bar nav w3-card-2 w3-left-align w3-large" style="text-overflow: auto;" id="nav">
<div class="w3-hide-large w3-hide-medium">
<a class="w3-hide-medium w3-hide-large w3-right w3-margin-right w3-text-white buttons" href="javascript:void(0);" onclick="myFunction()" title="Toggle Navigation Menu"><span class="fa fa-bars"></span></a>
<a href="<?php
if ($server_name <> "") {
echo "http://" . $server_name . "/";
}
?>/index.php" title="Home" class="w3-left w3-margin-left w3-text-white buttons"><span class="fa fa-home w3-xlarge"></span></a>
</div>
<div style="margin-right: 10%;">
<nav>
<?php
include 'yortal\db.php';
$sql = "SELECT *,(select count(*) from pages where parent = p.id) as num from pages p where parent = 0 and status = 'ON' order by sort DESC";
$result = $mysqli->query($sql);
while ($row = $result->fetch_assoc()) {
$navid = $row['id'];
$navname = $row['nav'];
$navslug = $row['slug'];
$navurl = $row['url'];
$navnum = $row['num'];
if ($navurl != '') {
$navlink = $navurl;
} else {
$navlink = "page.php?id=" . $navid . "&title=" . $navslug;
}
if (substr($navlink, 0, 4) != "http") {
if ($server_name <> "") {
$navlink = "http://" . $server_name . "/" . $navlink;
}
}
if ($navurl == '#') {
$navlink = $navurl;
}
if ($navnum == 0) {
$current_link = $_SERVER[REQUEST_URI];
$active_class = ($navlink==$current_link)?'active':'';
?>
<?php echo $navname; ?>
<?php
} else {
?>
<div class="w3-dropdown-hover w3-hide-small w3-right" onclick="javascript:window.location.href = '<?php echo $navlink; ?>'">
<button class="w3-button"><?php echo $navname; ?></button>
<div class="w3-dropdown-content w3-white w3-card-4">
<?php
//Subpages
$sql2 = "SELECT *,(select count(*) from pages where parent = p.id) as num from pages p where parent = " . $navid . " and status = 'ON' order by sort";
$result2 = $mysqli->query($sql2);
while ($row2 = $result2->fetch_assoc()) {
$dropid = $row2['id'];
$dropname = $row2['nav'];
$dropurl = $row2['url'];
$dropslug = $row2['slug'];
$dropnum = $row2['num'];
if ($dropurl != '') {
$droplink = $dropurl;
} else {
$droplink = "page.php?id=" . $dropid . "&title=" . $dropslug;
}
if (substr($droplink, 0, 4) != "http") {
if ($server_name <> "") {
$droplink = "http://" . $server_name . "/" . $droplink;
}
}
if ($dropurl == '#') {
$droplink = $dropurl;
}
?>
<?php
$actual_link = "http://".$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI];
$active_class = ($actual_link==$droplink || $_SERVER[REQUEST_URI] == $droplink)?'active':'';
?>
<?php echo $dropname; ?>
<?php
}
?>
</div>
</div><?php
}
}
?>
</nav>
</div>
</div>
</div>
First of all I'm pretty sure that you may have got wrong path. I suggest the following implementation which will depend on each():
$(document).ready(function(){
loc = window.location.pathname;
$("nav a").each(function(){
if ($(this).attr("href") == loc){
$(this).addClass("active");
$(this).attr("href") = "#"; // to prevent link to the same page
return true;
}
});
});

how to pass php array on change of select in jQuery?

Let me tell you in brief what I am doing ..
I am doing pagination using a library where the pagination is just showing the 3 <li> at a time.
and What I am doing on that <li> is I have a php array with me and I am creating a table in that <li> that each <li> will have table with 8 rows so the 8 elements of the array has been displayed with the help of php code.
This is the code.
<?php
$data = array();
$no_of_Items = 8;
$k = 1;
for ($i = 1; $i <= 100; $i++) {
$data[$i - 1] = "striker" . $i;
}
?>
<select id="view" >
<option value="1">Midfielder</option>
<option value="2">Striker</option>
<option value="3">Defender</option>
<option value="4">Goal-Keeper</option>
</select>
<div id="pagination">
<ul id="demo">
<?php
$lis = ceil(count($data) / $no_of_Items);
for ($i = 1; $i <= $lis; $i++) {
?>
<li>
<table id="tbl-li">
<?php
for ($j = 1; $j <= $no_of_Items; $j++) {
if (empty($data[$k - 1])) {
break;
}
?>
<tr style="padding: 0; margin: 0;">
<td><?php echo $data[$k - 1]; ?></td>
<td>CHE</td>
<td>11.5</td>
<td>142</td>
</tr ><?php $k++; } ?>
</table>
</li>
<?php } ?>
</ul>
</div>
so what I am doing now is just passing the one array to the pagination div but i have 4 arrays for defender as well as for all the item contains in the select tag .
So my final question is how to provide to my code the php when I select the appropriate option from the select?
I have tried this but I know this will not going to work so any suggestion or any other way?
My js
var selectval;
$('#view').on('change', function () {
selectval = $(this).val();
});
if (selectval === 1)
{
<?php
for ($i = 1; $i <= 100; $i++) {
$data[$i - 1] = "midfielder" . $i;
}
?>
}
else if (selectval === 2) {
<?php
for ($i = 1; $i <= 100; $i++) {
$data[$i - 1] = "striker" . $i;
}
?>
}
else if (selectval === 3) {
<?php
for ($i = 1; $i <= 100; $i++) {
$data[$i - 1] = "defender" . $i;
}
?>
}
else if (selectval === 3) {
<?php
for ($i = 1; $i <= 100; $i++) {
$data[$i - 1] = "goalkeeper" . $i;
}
?>
}
Try This it will work..
$('#view').select(function(){
var valselect = $('#view').val();
console.log(valselect);
var data = [];
var i, j, k = 1;
var code = '';
var no_item = 8;
if (valselect === "1")
{
for (i = 1; i <= 50; i++) {
data[i - 1] = "Midfielder" + i;
}
console.log(data);
}
else if (valselect === "2")
{
for (i = 1; i <= 50; i++) {
data[i - 1] = "Striker" + i;
}
console.log(data);
}
else if (valselect === "3")
{
for (i = 1; i <= 50; i++) {
data[i - 1] = "Defender" + i;
}
console.log(data);
}
else if (valselect === "4") {
for (i = 1; i <= 50; i++) {
data[i - 1] = "Goal-keeper" + i;
}
console.log(data);
}
var lis = Math.ceil(data.length / no_item);
console.log(lis);
for (i = 1; i <= lis; i++)
{
console.log("outerloop="+i);
code += "<li><table id='tbl-li'>";
for (j = 1; j <= no_item; j++) {
console.log("j=" + j);
if (data[k - 1])
{
// console.log("k=" + k);
code += "<tr><td><img src='/img/info.png'>" + data[k - 1] + "</td><td>CHE</td><td>11.5</td><td>142</td></tr>";
k++;
}
else {
// console.log("val k=="+k);
break;
}
}
code += "</table></li>";
}
// console.log(code);
// $('#demo').append();
$('#demo').html(code);
});

Opencart customization: server-side script for rating

I've added a custom table into the Opencart database, where I have a field/column, called average_rating (value = null to 5).
In my (custom) template (.tpl file) I've added a code to get and show the rating of current record from database.
Here is the code within .tpl file:
<div class="form-group">
<label class="col-sm-2 control-label" for="input-average_rating"><?php echo $entry_average_rating; ?></label>
<div class="col-sm-10">
<input type="hidden" name="average_rating" value="<?php echo $average_rating; ?>" id="input-average_rating" />
<?php for ($i = 0; $i < $average_rating; $i++) { ?>
<div class="rating_hover" id="<?php echo 'r' . ($i+1) ?>" title="<?php echo $i+1 ?>" data-toggle="tooltip"><i class="fa fa-star"></i></div>
<?php } ?>
<?php for ($i = $average_rating; $i <= 4; $i++) { ?>
<div class="rating_normal" id="<?php echo 'r' . ($i+1) ?>" title="<?php echo $i+1 ?>" data-toggle="tooltip"><i class="fa fa-star"></i></div>
<?php } ?>
</div>
</div>
For the blue-stars, I use .rating_hover class, for the grey-ones: .rating_normal class (see the picture below).
All this stuff works fine. But now I want to do something I have no experience with and I would appreciate any tip concerning my question.
Question: When a mouse pointer is over a grey star, it must become blue, like the ones before it. And when clicked on a star, my hidden input must get the value of title attribute of the clicked div-element. I wouldn't like to write a client-side Javascript to do this. Could somebody give a tip on how to do this with JSON or AJAX... or somehow please?
I mean: something like this:
$('div[id=\'r*\']').onmouseover({
// for (i=$average_rating; i<=[current_id]; i++) {
// ??? document.getElementById('r[i]').style.ClassName = 'someclass';
});
Javascript-alternative works fine, but I still have problems with JSON-script:
This is how javascript works:
Inside every div-element I added following commands:
<div ... onclick="rOnClick(<?php echo ($i+1) ?>);" onmouseover="rOnMouseOver(<?php echo ($i+1) ?>);" onmouseout="rOnMouseOut(<?php echo ($i+1) ?>);" ... >
And my Javascript functions are now, as follows:
<script type="text/javascript">
function rOnMouseOver(id) {
var ar = parseInt(document.getElementById('input-average_rating').value);
if (isNaN(ar)) {
ar = 0;
}
for(i = (ar+1); i <= id; i++) {
document.getElementById('r' + i).className = 'rating_hover';
}
}
function rOnMouseOut(id) {
var ar = parseInt(document.getElementById('input-average_rating').value);
if (isNaN(ar)) {
ar = 0;
}
for(i = 1; i <= ar; i++) {
document.getElementById('r' + i).className = 'rating_hover';
}
for(i = (ar+1); i <= id; i++) {
document.getElementById('r' + i).className = 'rating_normal';
}
}
function rOnClick(id) {
document.getElementById('input-average_rating').value = id;
for(i = 1; i <= id; i++) {
document.getElementById('r' + i).className = 'rating_hover';
}
for(i = (id+1); i <= 5; i++) {
document.getElementById('r' + i).className = 'rating_normal';
}
}
</script>
Please add another css class 'rating' in all rating divs. Also you will be needed to add a different class 'rated' for existing/clicked rated value. Then add following script:
$('.rating').hover(
// Handles the mouseover
function() {
$(this).prevAll().andSelf().addClass('rating_over');
$(this).nextAll().removeClass('rating_normal');
},
// Handles the mouseout
function() {
$(this).prevAll().andSelf().removeClass('ratings_over');
$('.rated').addClass('ratings_over'); // back to rated one
}
);
$('.rating').bind('click', function() {
$('.rating').removeClass('rated');
$(this).addClass('rated');
$('#input-average_rating').val($(this).attr('title'));
});

Categories

Resources