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
});
Related
This is the current code which is displaying the images on the frontend gallery.
What i need is a link or button to delete a single image when pressed.
It should show a confirmation javascript alert before deleting and then delete
Don't need ajax just plain javascript page refreshes is no issue.
I have looked out over the internet but can't really find a good solution.
function Closify_Translate_Images_to_Photoswipe_HTML($galleries, $effect,
$random_id, $itemPerPage = 10, $disable_caption = "off", $imgWidth = '',
$titleEnabled = 'off', $isMultiPage)
{
// Update caption flag
$caption = ($disable_caption!="on")?true:false;
$itemWidth = '';
// Update title flag
$title = ($titleEnabled!="on")?true:false;
// Update item's width
if($imgWidth != '') $itemWidth = ';width:'.$imgWidth.'px;';
// Update option range
$options = '';
for($i=10;$i<35;$i=$i+5)
{
if($i==$itemPerPage){
$options = $options . '<option selected>'.$i.'</option>';
}else{
$options = $options . '<option>'.$i.'</option>';
}
}
$numPages = '';
if($isMultiPage){
$itemWidth = $itemWidth.'opacity:0;';
$numPages = '<form class="closify-jpages-form">
<label>items per page: </label>
<select id="closify-select-'.$random_id.'">
'.$options.'
</select>
</form>';
}
$holder = '<div class="closify-holder closify-holder-'.$random_id.'">
</div>';
$htmlStart = '<div id="itemContainer-'.$random_id.'" class="closify-gallery"
itemscope itemtype="http://schema.org/ImageGallery">';
$htmlEnd = '</div>';
$htmlBody = '';
$titleText = "";
$captionText = "";
$titleCopyright = "";
foreach($galleries as $gallery)
{
if($caption && $gallery['img_desc']!='')
$captionText = '<br>Description <small>'.$gallery['img_desc'].'</small>';
else
$captionText = "";
if($title)
$titleText = 'Title <small>'.$gallery['img_title'].'</small>';
$htmlBody = $htmlBody.'<figure class="closify-figure-gallery-item" style="'.$itemWidth.'" itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
<a href="'.$gallery['full'][0].'" itemprop="contentUrl" data-size="'.$gallery['full'][1].'x'.$gallery['full'][2].'">
<img class="closify-animated '.$effect.'" src="'.$gallery['thumb'][0].'" itemprop="thumbnail" alt="'.$gallery['img_alt'].'" />
</a>
<figcaption itemprop="caption description">'.$titleText.$captionText.'</figcaption>
</figure>';
}
return $numPages.$holder.$htmlStart.$htmlBody.$htmlEnd;
}
From the server side there will be only one PHP file that should process the images that have been uploaded from the client side, and this single processing file is represented by the "processupload.php" file. This file is responsible of generating proper photos/thumbnails, where the resized photos are sent back to the client side using AJAX to be shown to the user seamlessly.
Referance link :
http://preview.codecanyon.net/item/closify-powerful-flexible-image-uploader/full_screen_preview/8292742
############ Put your custom code here ##############
This means that you can harness this space to add your own logic.
Other specific places to look:
1.
/****************************************************/
/****************************************************/
/*
// Insert info into database table!
mysql_query("INSERT INTO myImageTable (ImageName, ThumbName, ImgPath)
VALUES ($DestRandImageName, $thumb_DestRandImageName, 'uploads/')");
/****************************************************/
/****************************************************/
2.
// Handling position save command
if(isset($_POST["top"]) || isset($_POST["left"]))
{
// When somebody saves a picture you can read "top" and "left" and save them, so it become stored
// play with "left / top" image position
echo "Success";
}
// Handling image delete command
// POST
// command: delete
// id: The ID name of the specific image container that has been deleted
if(isset($_POST["command"]) && isset($_POST["id"]))
{
// When somebody delete a picture, the corresponding action should be put here
echo "Deleted";
}
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.
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 want to set the value/text of a div using javascript/jquery inside a loop but I don't know how to implement it. I need help with this one guys.
Objectives:
Retrieve data from database.
Set the value of an element using javascript/jquery (inside a loop) from the database.
Make the value a link
I have this a_link column from links table with the ff. values:
- www.google.com
- https://www.google.com
- www.stackoverflow.com
And here is my code:
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$thelink = $rowlink['a_link'];
?>
<div class = "row">
<span id = "linkhere"></span>
</div>
<script>
var link = "<?php echo $thelink; ?>";
$("#linkhere").html(urlify(link));
function urlify(text) {
var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
//var urlRegex = /(https?:\/\/[^\s]+)/g;
return text.replace(urlRegex, function(url,b,c) {
var url2 = (c == 'www.') ? 'http://' +url : url;
// return '<span style = "color:blue;text-decoration:underline">' + url + '</span>';
return '' + url + '';
})
}
</script>
<?php
}
?>
Any help would be highly appreciated. Thanks.
#aimme is technically not wrong about using a different database library. Please read "Why shouldn't I use mysql_* functions in PHP?" for reasons why not to use mysql_ and for some neat alternatives, some tutorials, and some good reads. (yes, all in the same page! just scroll down)
I think you're trying to:
display a <div> of class 'row'
with an <a> tag inside that uses the 'a_link' column of the 'links' table as the href and the label.
The href for the tag must always have a scheme (http://).
Just PHP and HTML
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$theLink= $rowlink['a_link'];
$regexMatches = array();
// removed (what seemed to be) needless groups in regex
$urlFound = preg_match("#((https?:\/\/|www\.)[^\s]+)#",$theLink,$regexMatches);
if($urlFound === 1) {
// only add http:// if http:// was not detected
$href = ($regexMatches[2] === "www." ? "http://" : "") . $theLink;
?>
<div class="row">
<?php echo $theLink; ?>
</div>
<?php }
}
?>
This code won't echo a row if a_link doesn't contain either 'http://' or 'www.' in it. so google.com will not be displayed.
Of note, as written, the regex will work on "urls" like 'applewww.google.com'. Don't know if that matters. Adding a '^' to the beginning of the regex may solve the problem (like so:preg_match("#^((https?:\/\/|www\.)[^\s]+)#",$theLink,$regexMatches);)
A (better|different) solution could use parse_url($url)
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$theLink= $rowlink['a_link'];
$href = (parse_url($theLink,PHP_URL_SCHEME) === NULL ? "http://" : "") . $theLink;
?>
<div class="row">
<?php echo $theLink; ?>
</div>
<?php
}
?>
However, using parse_url() would mean any old string would be displayed (while the first solution would not display any links that didn't have either http:// or www.) but since your pulling from a table called 'links' it's probably safe to assume everything is a valid path.
That's not how it works, that's not how any of this works
Now let's assume that you really need to use Javascript to process your generated links (which is not).
You first need to separate your Javascript code from your PHP code. You will only use Javascript once you have fetched your data and generated some output.
I guess you just want some kind of working code
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink)) :
$link = $rowlink['a_link'];
?>
<div class="row">
</div>
<?php
endwhile;
?>
<script type="text/javascript">
$(function() {
$('.row a').each(function() {
var urlified = urlify($(this).data('url'));
$(this).attr('href', urlified.url)
.text(urlified.label);
});
});
function urlify(text) {
var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
return text.replace(urlRegex, function(url,b,c) {
var label = (c == 'www.') ? 'http://' +url : url;
return {url: url, label: label};
});
}
</script>
First i want to advice that use PDO or mysqli instead of mysql. as it
is vulnerable to sql injection and its depreciated.
"I want to set the value/text of a div using javascript/jquery inside a loop but I don't know how to implement it. I need help with this one guys."
for that i would say Php is a server side language whereas javascript is a client side language. and Ajax is the way to manipulate client side from server vice versa, without refreshing the whole page.
below is just a demonstration that i edited little bit from your code to show the separation of server side and client side code and to just give an idea how it works.I don't know whether the code will work or not. haven't tested. php code (server side) will be executed first but could control the display of it using javascript(client side) functions inside document.ready() or window.load() to apply the affects as soon as possible.Through this we could bring changes to the links that we want before its being shown to the client . For each of the link retrieved and displayed you could use a specific class and jquery .each() function to apply certain fix to the selected link as Lyes BEN mentioned above or all the elements with a specific class could be manipulated as a whole without using .each.
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$thelink = $rowlink['a_link'];
echo '<div class = "row">
<span id = "linkhere">
</span>
</div>';
}
?>
<script>
$("#linkhere a").html(urlify(link));
function urlify(text) {
var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
//var urlRegex = /(https?:\/\/[^\s]+)/g;
return text.replace(urlRegex, function(url,b,c) {
var url2 = (c == 'www.') ? 'http://' +url : url;
// return '<span style = "color:blue;text-decoration:underline">' + url + '</span>';
return '' + url + '';
})
}
</script>
You can implement this using php with parse_url function (http://php.net/manual/en/function.parse-url.php) to get different components.
In parse_url, there is 'scheme' key for http or https.
Then to do this with php, just call formatUrl function to make the url
<?php
function formatUrl($url)
{
$urlData = parse_url($url);
if(!isset($urlData['scheme'])) {
$url = 'http://' . $url;
}
return '' . $url . '';
}
?>
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$thelink = $rowlink['a_link'];
?>
<div class = "row">
<span id="linkhere"><?php echo formatUrl($thelink)?></span>
</div>
<?php
}
?>
I am working on a site that generates notation for a random musical rhythm based on some user-selected parameters. It does this by using an ajax call, which returns a random set of <img> elements that represent different notes. I have a function that is designed to scale the rhythm to fit in the screen, regardless of it's actual size.
The function is triggered after a successful ajax call, which is triggered by a click event on a button.
My problem is that the function does not work as desired when running the first time the page is loaded.
After the function runs for the first time, the height attribute of all of the <img> elements is somehow set to 0.
However, the function works great if I run the it again (by clicking the button). It also works fine after a page refresh.
Also, I do not have this issue in IE11, only Chrome (I haven't tested other browsers yet).
I have tried wrapping the code in both $(window).load() and $(document).ready() event handlers, but this didn't help.
The site in action can be found at http://www.rhythmrandomizer.com
Any help would be greatly appreciated!
Below is the relevant code:
Event handler for the button:
$("#randomize").click(function(){
//get general options from form
var timeSignature = $("#timeSignature").val();
var phraseLength = $("#phraseLength").val();
//get note options from form
var checked = [];
$("#noteOptions :checked").each(function() {
checked.push($(this).val());
});
//alert user and exit function if nothing is selected
if (checked.length < 1) {
alert("Please select at least one note value");
return;
}
//format note option ids into a delimited string
var noteOptions = "";
for (var i=0; i < checked.length; i++) {
noteOptions += checked[i] + "a";
}
//remove the final comma and space
noteOptions = noteOptions.substr(0, noteOptions.length - 1);
//ajax call
$.ajax("randomize.php", {
data : {
timeSignature : timeSignature,
phraseLength : phraseLength,
noteOptions : noteOptions
},
type : "GET",
success : function(response) {
$("#rhythm").html(response);
scaleRhythm();
},
error : function(xhr, status, errorThrown) {
console.log(status + " | " + errorThrown);
}
});
});
The php file that returns the rhythm notation:
<?php
//MySQL connection variables
$hostname = 'localhost';
$user = ini_get('mysqli.default_user');
$pw = ini_get('mysqli.default_pw');
$database = 'rhytxfpd_rhythmrandomizer';
//Connect to database
try {
$db = new PDO('mysql:host=' . $hostname . ';dbname=' . $database,$user,$pw);
} catch(PDOException $e) {
echo $e->getMessage();
die();
}
//Get values from GET
$timeSignature = $_GET['timeSignature'];
$phraseLength = $_GET['phraseLength'];
$noteOptString = $_GET['noteOptions'];
//Split up note options string
$noteOptions = explode('a', $noteOptString);
//Create sql query
$sql = 'SELECT
noteName,
noteValue,
noteGraphic
FROM
notes
WHERE';
//append noteOptions as WHERE clauses
foreach ($noteOptions as $opt) {
$sql = $sql . ' noteGroupID = ' . $opt . ' OR';
}
//remove final " OR"
$sql = substr($sql, 0, strlen($sql) - 3);
//query the database and get all results as an array
/* This will return a table with the name, graphic, and value of
* the notes that the user selected prior to submitting the form
*/
$stmt = $db->query($sql);
$result = $stmt->fetchAll();
//Get the total number of options selected
$numOpts = count($result);
/***************************/
/** BEGIN PRINTING RHYTHM **/
/***************************/
//div to begin the first measure
echo '<div class="measure" id="m1' . $measure . '">';
//Print time signature
echo '<img class="note" src="notes/' . $timeSignature . '.png" title="time signature ' .
$timeSignature . '/4" alt="time signature ' . $timeSignature . '/4"/>';
//Prints as many measures as indicated by the phrase length selection
$measure = 1;
while ($measure <= $phraseLength) {
//begin a new div for other measures.
if ($measure != 1) {
echo '<div class="measure" id="m' . $measure . '">';
}
//Prints random measure according to time signature
$beats = 0;
while ($beats < $timeSignature) {
//Generate a random number
$random = rand(0, $numOpts - 1);
//Get the random note from results
$note = $result[$random];
//Continues if chosen note will not fit in the measure
if ($beats + $note['noteValue'] > $timeSignature) {
continue;
}
//Prints random note
echo '<img class="note" src="notes/' . $note['noteGraphic'] . '.png" title="' .
$note['noteName'] . '" alt="' . $note['noteName'] . '"/>';
//Adds random note's value to total number of beats
$beats += $note['noteValue'];
//$beats++;
}
//If last measure
if ($measure == $phraseLength) {
echo '<img class="note" src="notes/1.png" title="double barline" alt="double barline"/>';
echo '</div>';
} else {
echo '<img class="note" src=notes/b.png title="barline" alt="barline"/>';
echo '</div>';
}
//Increment to next measure
$measure++;
}
The scaleRhythm() function:
function scaleRhythm() {
//Get width of rhythm at full resolution
var rhythmWidth = $("#rhythm").width();
//Get current screen/window width
var screenWidth = window.innerWidth;
//Compute ratio between curren screen and window widths
var ratio = screenWidth / rhythmWidth;
//Multiply img note height by ratio, then by 90% to provide some
//breathing room on either side of the rhythm
var newHeight = (400 * ratio) * .9;
//Set img note height to new height or 300px, whichever is smaller
if (newHeight < 300) {
$(".note").css("height",newHeight);
//code to center rhythm horizontally
$("#rhythm").css("margin-top",(300-newHeight)/2);
} else {
$(".note").css("height",300);
$("#rhythm").css("margin-top",0);
}
}
Add this javascript to your <script></script>:
$(function(){ $("#randomize").click(); });
This will cause your page to run the function that populates your random elements then (at the end of that function) run the scale function.
I tested it by running it on your page in the chrome console and it worked.
If you put a breakpoint in the scaleRhythm function you'll notice on page load it's not being run. You've defined the function but it is not being called on page load. In fact none of the code you want run (ie: the ajax call) gets called until the first click happens. So what you need to do is trigger the click event on the button like JRulle said.
$("#randomize").click();
Okay so here is your issue.
The first time you click the button, var rhythmWidth = $("#rhythm").width(); evaluates to "0" because it is empty.
Which causes these subsequent functions to be "0" as well:
var ratio = screenWidth / rhythmWidth;
var newHeight = (400 * ratio) * .9;
I would edit your function to be like so:
var rhythmWidth = $("#rhythm").width();
if (rhythmWidth == 0) { rhythmWidth = 10; } //assign some reasonable value here
since your function does not support a rhythmWidth of "0"