How to asynchronously preload images - javascript

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();
};

Related

Carousel need to start from middle slide on page load

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"})
});
});

Ordered list with random numbers between 1 and 49

I have some problems to Code an simple PHP ordered list that print out a random number list between 1 and 49.
The Main Code
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<title>AJAX</title>
<meta name="viewport" content=
"width=device-width; initial-scale=1.0">
<link rel="stylesheet" type="text/css"
href="lib/css/stil.css" />
<script type="text/javascript"
src="lib/js/script.js"></script>
</head>
<body>
<h1>Ziehung der Lottozahlen</h1>
<button id="frage">Starte die Ziehung</button>
<div id="antwort">
</div>
</body>
</html>
Here the external PHP Code to randomize the numbers
<?php
$zahlen = range (1, 49);
shuffle($zahlen);
for ($i = 0; $i < 6; $i++) {
echo $zahlen[$i] . " ";
}
?>
And here the Java script
var resOb = new XMLHttpRequest();
window.onload = function() {
document.getElementById("frage").onclick =
function () {
resOb.open('get', 'lottozahlen1.php', true);
resOb.onreadystatechange = function () {
if (resOb.readyState == 4) {
document.getElementById("antwort").innerHTML =
resOb.responseText;
}
};
resOb.send(null);
};
};
T
Now my question...how i can let Show the numbers in a ordered list?
use PHP code below way
$zahlen = range (1, 49);
shuffle($zahlen);
$arr = array();
for ($i = 0; $i < 6; $i++) {
$arr[$i] =$zahlen[$i] . " ";
}
sort($arr,1);
echo implode(' ',$arr);
You could split the string, map the values as number and sort the array. Then generate the wanted list items and put it to the wanted unordered list.
var lotto = '22 34 14 10 99',
list = lotto
.split(' ')
// .map(Number)
// .sort(function (a, b) {
// return a - b;
// })
.reduce(function (list, a) {
var li = document.createElement('li');
li.innerHTML = a;
list.appendChild(li);
return list;
}, document.createElement('ol'));
document.body.appendChild(list);
Extending Kool-Mind's answer:
$zahlen = range (1, 49);
shuffle($zahlen);
$arr = array();
for ($i = 0; $i < 6; $i++) {
$arr[$i] =$zahlen[$i] . " ";
}
sort($arr,1);
echo implode(' ',$arr);
Try adding the code below(to generate the list):
<script>
$('#button').click(function(){
$('#newDiv').append('<ol>');
$('#newDiv').append('<?php foreach($arr as $a){echo"<li>".$a."";}?>');
$('#newDiv').append('</ol>');
})
</script>
Hope it helps =)
EDIT
This should be working fine now, hope it helps =)
<button id="button">Button</button>
<div id="newDiv"></div>
<script>
var clicked = false;
$('#button').click(function(){
if (!clicked){
<?php
$arr = array();
for ($i = 0; $i < 6; $i++) {
$arr[$i] = rand(1,49);
}
sort($arr,1);
?>
$('#newDiv').append('<ol>');
$('#newDiv').append('<?php foreach($arr as $a){echo"<li>".$a."";}?>');
$('#newDiv').append('</ol>');
clicked = true;
}
})
</script>

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);
});

Why i'm getting error: "SyntaxError: Unexpected token <"?

This is the code i'm using:
<?php
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$) |(\.Gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($"http://newsxpressmedia.com/files/radar-simulation-files")) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
$files[] = $file;
$curimage++;
}
}
closedir($handle);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>change picture</title>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style type='text/css'>
#Timer_Countdown{
background:black;
color:yellow;
font-weight:bold;
text-align:center;
}
</style>
<script type = "text/javascript">
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("img").src = images[x];
}
function displayPreviousImage() {
x = (x <= 0) ? images.length - 1 : x - 1;
document.getElementById("img").src = images[x];
}
var images = <?=json_encode($files)?>;
//var images = [];
var x = -1;
var swap_hours = 0;
var swap_minutes = 0;
var swap_seconds = 5;
var down_counter_hours;
var down_counter_minutes;
var down_counter_seconds;
function initTimer() {
down_counter_hours = swap_hours;
down_counter_minutes = swap_minutes;
down_counter_seconds = swap_seconds;
counter = setInterval(switcher, 1000);
}
function restartCounter() {
down_counter_hours = swap_hours;
down_counter_minutes = swap_minutes;
down_counter_seconds = swap_seconds;
}
function switcher() {
down_counter_seconds--;
if (down_counter_hours <= 0 && down_counter_minutes <= 0 && down_counter_seconds <= 0) {
swapColor();
restartCounter();
}
if (down_counter_seconds <= 0 && down_counter_minutes > 0) {
down_counter_seconds = 60;
down_counter_minutes--;
}
if (down_counter_minutes <= 0 && down_counter_hours > 0) {
down_counter_minutes = 60;
down_counter_hours--;
}
document.getElementById("Timer_Countdown").innerText = down_counter_hours+":"+down_counter_minutes+":"+down_counter_seconds;
}
function swapColor() {
displayNextImage();
}
</script>
<div id="div_hours" class="div_box"></div>
<div id="div_minutes" class="div_box"></div>
<div id="div_seconds" class="div_box"></div>
<div id="div_switcher" class="div_box"></div>
</head>
<body onload = "initTimer()">
<div id="Timer_Countdown"> </div>
<img id="img" src="http://newsxpressmedia.com/files/theme/radar000005.Gif">
<button onclick="displayPreviousImage(); restartCounter()">Previous</button>
<button onclick="displayNextImage(); restartCounter()">Next</button>
</body>
</html>
The error is on the line:
var images = <?=json_encode($files)?>;
If i change this line to this line:
var images = [];
Then the code is working fine but without using the php files variable.
Something is wrong with the line: var images = <?=json_encode($files)?>;
I tried to change this line to: echo json_encode($images); or to var images = echo json_encode($files); but same error.
I'm using weebly to build my site and my site server is on ipage.com
How can i fix the error ?
It looks like you don't have short tags enabled(and are using a pre 5.4 php version), thus the line <?=json_encode($files)?> is not parsed by php and is just send straight through. var images = <... is not a valid javascript expression. Here's some information about php's short_open_tag parameter: http://php.net/manual/en/ini.core.php#ini.short-open-tag
A couple of changes. Change
$pattern ="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$) |(\.Gif$)";
to
$pattern = '/\.(png|jpg|jpeg|gif)$/i';
and
eregi($pattern, $file)
to
preg_match($pattern, $file)
and see what happens. eregi deprecated as PHP 5.3.0.
You are using '=' inside the PHP tags. Try this:
var images = <?json_encode($files)?>;

PHP and Javascript getelementbyid, how to pass on parameters

I have a Javascript function that is called many time within a while loop with <div id='c$value'>.
When calling countdown() I would need to pass on some parameters. In this case $m and $s.
How can this be done ?
window.onload = function() {
<?php
$nbcounters = 5;
for ($i = 0; $i < $nbcounters; $i++) {
echo "countdown('c$i', 0, 7);";
}
?>
}
the php code
<?php
$value = 0;
while ($value < $nbcounters) {
$m = rand(1, 3);
$s = rand(10, 20);
echo "<div id='c$value'></div><br>";
$value++;
}
?>
Thanks!

Categories

Resources