I've created a element populator, which takes certain elements, wraps them in HTML tags and appends them to a container. The problem I have, which is more of nuisance if anything, is for every image to be loaded it has to be input automatically. Is there a way to retrieve all images from a folder and load them into an array?
I have this code, which works, but with manual input:
$(window).on('load', function () {
var gallery = document.getElementById("grid");
var images = [
"./imgs/galeria/0.jpg",
"./imgs/galeria/1.jpg",
"./imgs/galeria/2.jpg",
"./imgs/galeria/3.jpg",
"./imgs/galeria/4.jpg",
"./imgs/galeria/7.jpg",
"./imgs/galeria/6.jpg",
"./imgs/galeria/5.jpg",
"./imgs/galeria/8.jpg",
"./imgs/galeria/9.jpg",
"./imgs/galeria/10.jpg",
"./imgs/galeria/11.jpg",
"./imgs/galeria/12.jpg",
"./imgs/galeria/13.jpg",
"./imgs/galeria/14.jpg",
"./imgs/galeria/15.jpg",
"./imgs/galeria/16.jpg",
"./imgs/galeria/17.jpg",
"./imgs/galeria/18.jpg",
"./imgs/galeria/19.jpg",
"./imgs/galeria/20.jpg"
];
for (var i = 0; i < images.length; i++) {
var thumbnailWrapper = document.createElement("div");
thumbnailWrapper.className = "thumbnail-wrapper";
var thumbnail = document.createElement("div");
thumbnail.className = "thumbnail";
thumbnail.dataset.source = "./imgs/galeria/" + i + ".jpg";
thumbnailWrapper.appendChild(thumbnail);
gallery.appendChild(thumbnailWrapper);
}
var thumb = document.getElementsByClassName('thumbnail');
// console.log(thumb);
for (j = 0; j < images.length; j++) {
// $(thumb[j]).attr('src', images[j]);
$(thumb[j]).css('background-image', 'url(./imgs/galeria/thumbs/' + j + 'tbm.jpg)');
// console.log(j);
// console.log(images[j]);
}
You can see the script in action in this website I made in the "galeria" section.
EDIT: maybe something with ajax? I wanted to keep php out of the equation
EDIT2: I would like to make it with ajax, and this is now the correct code
You can't use client-side JavaScript to scan a folder on a server. If you don't know what files the folder contains, then AJAX alone doesn't even work.
You have to use server-side code, such as PHP, to find all the files in the folder, and them deliver them somehow to the client. That is the only way I see.
This approach could work:
$images = glob('imgs/galeria/*.jpg');
echo '<div id="grid">';
foreach ($images as $key => $image) {
echo '<div class="thumbnail-wrapper">';
echo '<div
class="thumbnail"
data-source="' . $image . '"
style="background-image: url(imgs/galeria/thumbs/' . $key . 'tbm.jpg)"
></div>';
echo '</div>';
}
echo '</div>';
I hope this works like your JavaScript code does.
Related
I'm trying to show random images/video in product category pages. Every category page will display their own set of images.
I did it in the typical rookie way by adding in every product category page with their own respective set of images. Is there a way that I can use hooks to do it at functions.php for ease of maintenance?
var total_images = 7;
var image1 = document.getElementById('banner1');
var image2 = document.getElementById('banner2');
var image3 = document.getElementById('banner3');
var random_numbers = [];
var random_number;
var random_img = [];
random_img[0] = '<img src="banner1.jpeg">';
random_img[1] = '<img src="banner2.jpeg">';
random_img[2] = '<img src="banner3.jpeg">';
random_img[3] = '<img src="banner4.jpeg">';
random_img[4] = '<img src="banner5.jpeg">';
random_img[5] = '<img src="banner6.jpeg">';
random_img[6] = '<img src="banner7.jpeg">';
while(random_numbers.length < 3){
random_number = Math.floor((Math.random() * total_images));
if(random_numbers.indexOf(random_number) < 0){
random_numbers.push(random_number);
}
}
image1.innerHTML = random_img[random_numbers[0]];
image2.innerHTML = random_img[random_numbers[1]];
image3.innerHTML = random_img[random_numbers[2]];
The easy way - Install ACF plugin and create your fields - https://prnt.sc/1yek9zy .
For image field select image url. Duplucate Banner 1 as many banners you want and setup Location rules to taxonomy product category - https://prnt.sc/1yekgys
Then go to a product category and add your images and urls - https://prnt.sc/1yeklpf
If you have ACF pro go with repeater field instead. Its more dynamic and you can add as many banners you want per product category.
Use this visual hook guide to change where you want the banners to be showed - https://www.businessbloomer.com/woocommerce-visual-hook-guide-archiveshopcat-page/
function woo_category_banners() {
$term = get_queried_object();
$banners = get_field('banners', $term->taxonomy . '_' . $term->term_id);
if($banners):
echo '<div class="banners">';
foreach($banners as $k => $banner):
$banner_data = $banners[$k];
echo '<div class="banner"><img src="'.$banner_data['banner_image'].'"></div>';
endforeach;
echo '</div>';
endif;
}
add_action('woocommerce_before_shop_loop','woo_category_banners',40);
I have developed something similar in the past, but not in javascript, it was all php code.
I had added a new banner field in the categories with ACF (only one, you would have many), and then on the category page I would show that banner or, recursively, the father's banner, until I found one.
You would have multiple image fields, and you would extract one at random, maybe it can be useful to you.
In any case, the hook to use is: woocommerce_before_main_content action.
add_action('woocommerce_before_main_content','bannertop');
function bannertop() {recursebanner('banner_top','bannertop');}
function recursebanner($type,$class) {
if ( is_tax( 'product_cat' ) ) {
$term = get_queried_object();
$banner = get_field('banner_top', $term);
if ($banner) {
echo '<div class="'.$class.'">';
echo $banner;
echo '</div>';
} else {
// no banner defined, parse ancestors
$cat_ancestors = get_ancestors( $term->term_id, 'product_cat' );
foreach ($cat_ancestors as $cat_ancestor) {
$termancestor = get_term($cat_ancestor);
$banner = get_field($type, $termancestor);
if ($banner) {
echo '<div class="'.$class.'">';
echo $banner;
echo '</div>';
break;
}
}
}
}
}
If you want to use javascript instead, you have to add it in your js file in the child theme, and call the script for example like this:
$ (function () {
// your code
});
I'm trying to read a .dat file (it's a CSV with delimiter';') and convert it into a table and is done in PHP and is as follows:
<table id='sol'>
<?php
echo "<html><body>";
$f = fopen("/var/www/html/uploads/data_old.dat", "r");
$var = 0;
/* Writes the CSV to table in the page*/
while (($line = fgetcsv($f, 0, ';')) !== false) {
echo "<tr>";
foreach ($line as $cell) {
if ($var < 36) {
echo "<th>" . htmlspecialchars($cell) . "</th>";
$var = $var + 1;
}
else {
echo "<td><div contenteditable>" . htmlspecialchars($cell) . "</div></td>";
}
}
echo "</tr>";
}
fclose($f);
echo "</body></html>";
?>
</table>
Now after editing the values in the table, I need to save this table on the server. Currently, I can download the table in .dat using a script written in JS as below:
// Quick and simple export target #table_id into a csv
function download_table_as_csv(table_id, separator = ';') {
// Select rows from table_id
var rows = document.querySelectorAll('table#' + table_id + ' tr');
// Construct csv
var csv = [];
for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll('td, th');
for (var j = 0; j < cols.length; j++) {
// Clean innertext to remove multiple spaces and jumpline (break csv)
var data = cols[j].innerText.replace(/(\r\n|\n|\r)/gm, '').replace(/(\s\s)/gm, ' ')
// Escape double-quote with double-double-quote
data = data.replace(/"/g, '""');
// Push escaped string
row.push('"' + data + '"');
}
csv.push(row.join(separator));
}
var csv_string = csv.join('\n');
// Download it
var filename = 'data_new' + '.dat';
var link = document.createElement('a');
link.style.display = 'none';
link.setAttribute('target', '_blank');
link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv_string));
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
I'm fairly new to this and any help is highly appreciated.
I might not understand the question here, but I think its something like "I get a csv file from a user - how to display file's fields as an HTML table, and then setup a download link for newly editted file"
If that sounds correct, this is probably what you want.
You are correctly displaying the CSV as an HTML table (as far as I can tell).
if htmlspecialchars(..) changes the characters emitted from data_old.dat then we start writing a new CVS file where we'll place the changes emitted by htmlspacechars(..) - and you write in the delimiter yourself by adding ; (as you noted).
$f_ = fopen("/var/www/html/uploads/data_new.dat", "w");
And which ever file we wish the user to download, just place it inside an <a href='...'> tag.
<?php echo "<a href='uploads/data_new.data'>download</a>" ?>
Furthermore (Getting user edits):
While the example above tells us how to setup the backend for the user downloading the file, - it doesn't outline a way for the user to commit edits, and the backend to know about it.
To do allow the server to know about user edits, as mentioned in the comments AJAX is the way to go for php.
AJAX is Javascript sending XML (body) notation to the backend as an http request. The way it works is described in the image below.
AJAX is accessed by javascript in the browser (hey the where the user is!)
var xhttp = new XMLHttpRequest(); // setup object
// hook function
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// this is ran after we get an OK from the server.
// after they've committed a change
}
};
// setup request
xhttp.open("GET", "link/to/your/website", true)
xhttp.send(); // send it
AJAX playground
So far this is pretty vague outlining of what it is, now lets see how we can use it.
So the idea being that when a user changes a field in the table, we run some javascript to send an AJAX request. Specifying what they changed.
The server gets the request, updates the changes on the backend, and then sends OK back to the client.
Hope this helps.
I have 5 PHP variables, $menu1 to $menu5, that each evaluate to a keyword. I'm trying to populate these 5 PHP variables in JavaScript, and display them. The below code doesn't work. What is wrong with my processing of the PHP variables?
var menu_populator = "";
for (var x = 1; x <= count; x++) {
menu_populator += '<li><a class="myclass" href="#link">' + '<?php echo $menu' + x + '?>' + '</a></li>';
}
$('#nav_menu').html(menu_populator);
Depending on how you are getting the menu data server-side you can try both methods below. One is for set $menu variables but if you are getting data from a database or the $menu variable are created within a loop you might find the second method better.
Method one- PasteBin
Echo your php variables into a javascript array.
var myarray=["<?php echo $menu1;?>","<?php echo $menu2;?>","<?php echo $menu3;?>","<?php echo $menu4;?>","<?php echo $menu5;?>"];
Method Two- PasteBin
Create this array server-side, this will be better if you are creating the current $menu variable in a loop, with this you can just use array_push() to push the values into the array.
<?php
// PHP Array
$menu = array('Home', 'Gallery', 'About');
// How to push new item into array
array_push($menu, 'Contact');
?>
Then just simply echo this array into your javascript myarray variable.
var myarray=<?php echo json_encode($menu);?>;
I have used the following javascript to test both methods and both seem to function just fine. I prefer the second method but I have decided to offer both as I don't know what your PHP looks like or how your $menu variables are being defined so this should cover both.
window.onload=function(){
for(var i=0; i<myarray.length; i++){
var link= document.createElement('a');
link.href="#";
link.innerHTML=myarray[i];
document.body.appendChild(link);
document.body.appendChild(document.createElement('br'));
}
}
If you have any questions about the source code above please leave a comment below and I will get back to you as soon as possible.
I hope this help. Happy coding!
Something like this would do the trick
<?php
$menu = "menu";
echo '
<script>
var count = 10;
var menu_populator="";
for(var x=1;x<=count;x++)
{
menu_populator += \'<li><a class="myclass" href="#link">'.$menu.' \'+x+\'</a></li>\';
}
$(\'#nav_menu\').html(menu_populator);
</script>
';
?>
So, I need to display 2 or 3 different images in a website, as simple parallax dividers for content.
I have an array of 4 images, so I'll be able to randomize without repeat them in the same page, althoug the random won't be that noticeable.
I've been lurking this for a while, and found these
Random Image Display, Without Repeat, with Javascript
<script language="javascript">
var imagesArray = [
'images/img-1.jpg',
'images/img-2.jpg',
'images/img-3.jpg',
'images/img-4.jpg',
'images/img-5.jpg',
];
var usedImages = {};
var usedImagesCount = 0;
function displayImage() {
var num = Math.floor(Math.random() * (imagesArray.length));
if (!usedImages[num]) {
document.canvas.src = imagesArray[num];
usedImages[num] = true;
usedImagesCount++;
if (usedImagesCount === imagesArray.length) {
usedImagesCount = 0;
usedImages = {};
}
} else {
displayImage();
}
}
</script>
(this was created to exhibit the image upon a click on a button, as it follows
<input onclick="displayImage();" type=button value="Click Here">
I tried to adapt it to my need, but the call on my page din't produce any results)
https://www.daniweb.com/programming/web-development/threads/266181/random-imageslinks-without-repeating
(this one, I couldn't quite understand why, but I wasn't able to apply the solution. not sure if it's the code or the way of calling the image that's wrong...)
http://www.utopiamechanicus.com/article/not-so-random-image-rotation-in-php-for-html-the-sequel/
<?php
// rotate images randomly but w/o dups on same page - format:
// <img src='rotate.php?i=0'> - rotate image #0 - use 'i=1'
// for second, etc
// (c) 2004 David Pankhurst - use freely, but please leave in my credit
$images = array(// list of files to rotate - add as needed
"img1.gif",
"img2.gif",
"img3.gif",
"img4.gif",
"img5.gif");
$total = count($images);
$secondsFixed = 10; // seconds to keep list the same
$seedValue = (int) (time() / $secondsFixed);
srand($seedValue);
for ($i = 0; $i < $total; ++$i) { // shuffle list 'randomly'
$r = rand(0, $total - 1);
$temp = $images[$i];
$images[$i] = $images[$r];
$images[$r] = $temp;
}
$index = (int) ($_GET['i']); // image index passed in
$i = $index % $total; // make sure index always in bounds
$file = $images[$i];
header("Location: $file"); // and pass file reference back
?>
(this one was supposed to work calling through:
<img src='mysite.com/rotate.php?i=0'>
but the images are still repeating themselves sometimes)
They didn't work for me, so I decided to start a new topic, because I'm really newbie (actually, I don't know writing nothing at all) at javascript, and can't figure out what's the best approach. I understood it would be something like randomize the items, assign each of them a position (a number, a character, a [i], etc), and then call for it in my php page. Could you guys please help me?
Not sure is that you want but this will give you randomized images (without repeat) on a page, every time different ones:
<?php
$img = array('img1.png', 'img2.png', 'img3.png', 'img4.png', 'img5.png', 'img6.png');
shuffle($img);
for($i=0; $i<3; $i++){
print '<img src="'.$img[$i].'"><br>';
}
?>
If you want to receive one image per call, one of the possible solutions is to use session:
image.php:
<?php
session_start();
function getImage() {
$img = array('img1.png', 'img2.png', 'img3.png', 'img4.png', 'img5.png');
shuffle($img);
foreach($img as $key => $val) {
if (!is_array($_SESSION['img'])) {
return $val;
} elseif (count($_SESSION['img']) >= count($img)) {
$_SESSION['img'] = array();
}
if (is_array($_SESSION['img']) && !in_array($val, $_SESSION['img'])) {
return $val;
}
}
}
?>
page.php:
<?php
include 'image.php';
for ($i = 0; $i < 3; $i++) {
$currImg = getImage();
$_SESSION['img'][] = $currImg;
echo $currImg . '<br>';
}
?>
All displayed images are stored into SESSION variable. When all images are displayed, this SESSION var is reset and will start a new cycle.
I'm trying to build a simple auto suggest input bar that connects to a MySql database and retrieves data. The issue that I'm running into is that when I type in the name of an object that I know exists in the databse, the text bar doesn't return any results, instead it just provides me with an empty dropdown box.
The best I can tell, the issue has to do with the javascript that is used within the PHP portion of the code. Unfortunately, I can't seem to figure out why it's causing an issue.
<?php
mysql_connect("host", "user", "passsword") OR DIE ('Unable to connect to database! Please try again later.');
mysql_select_db('DBName');
$query = 'SELECT Device_type FROM Device';
$result = mysql_query($query);
$counter = 0;
echo"<script type='text/javascript'>";
echo"this.nameArray = new Array()";
if($result) {
while($row = mysql_fetch_array($result)) {
echo("this.nameArray" .$row ['Device_type'] . "';");
$counter += 1;
}
}
echo("</script>");
?>
When I take out the echo"<script type='text/javascript'>"; and echo"this.nameArray = new Array()"; then It displays the Device_type content on the top of the page when the page is loaded. This obviously isn't what I want, but it does prove that the database connection is at least set up correctly. Since this chunk of PHP is referring to some javascript, I will also prove the function in which it's referring to.
function doSuggestions(text) {
var input = text;
//window.alert(text);
var inputLength = input.toString().length;
var code = "";
var counter = 0;
while(counter < this.nameArray.length) {
var x = this.nameArray[counter]; // avoids retyping this code a bunch of times
if(x.substr(0, inputLength).toLowerCase() == input.toLowerCase()) {
code += "<div id='" + x + "'onmouseover='changeBG(this.id);' onMouseOut='changeBG(this.id);' onclick='doSelection(this.innerHTML)'>" + x + "</div>";
}
counter += 1;
}
if(code == "") {
outClick();
}
document.getElementById('divSuggestions').innerHTML = code;
document.getElementById('divSuggestions').style.overflow='auto';
}
Any suggestions as to why the suggestion box isn't providing suggestions when I start typing? If I type A into the text box, the suggestion box should appear showing me all items in the database that start with A.
there are some errors in your js strings
`echo"var nameArray = new Array()";`
`echo("nameArray.push('" .$row ['Device_type'] . "');");`
that way you'll push device types into the nameArray var.