I have 10 image files in a folder ( images ) named from 1.jpg to 10.jpg
What I want to do is to change the background randomly every time the page is refreshed
This is what I have tried so far :
<body background='<?php echo 'images/'.rand(1,6).'.jpg' ?>'>
This doesn't work .
Can anybody tell me how to do this using php, please ?
<script>
$(function(){
var min = 1;
var max = 6;
var random = Math.floor(Math.random() * (max - min + 1)) + min;
$("body").css("background-image","url(images/"+random+".jpg")
}):
</script>
Try this:
First create an array of images:
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg', 'image5.jpg'];
Then, set a random image as the background image:
$('body').css({'background-image': 'url(images/' + images[Math.floor(Math.random() * images.length)] + ')'});
Related
I'll try to keep this simple and clear. I'm pretty new to using API's but I'm using the Flickr API to search for and display photos on my website based on a certain tag. For a simple, static web page this is quite simple and I've already got it working as intended. This is the jquery script I found to use:
$(function() {
var apiKey = 'MY_API_KEY_IS_IN_HERE';
var tag = '%23FFLIVE2014-09-03';
var perPage = '25';
var showOnPage = '6';
$.getJSON('http://api.flickr.com/services/rest/?format=json&method='+
'flickr.photos.search&api_key=' + apiKey +
'&tags=' + tag + '&per_page=' + perPage + '&jsoncallback=?',
function(data){
var classShown = 'class="lightbox"';
var classHidden = 'class="lightbox hidden"';
$.each(data.photos.photo, function(i, rPhoto){
var basePhotoURL = 'http://farm' + rPhoto.farm + '.static.flickr.com/'
+ rPhoto.server + '/' + rPhoto.id + '_' + rPhoto.secret;
var thumbPhotoURL = basePhotoURL + '_s.jpg';
var mediumPhotoURL = basePhotoURL + '.jpg';
var photoStringStart = '<a ';
var photoStringEnd = 'title="' + rPhoto.title + '" href="'+
mediumPhotoURL +'"><img src="' + thumbPhotoURL + '" alt="' +
rPhoto.title + '"/></a>;'
var photoString = (i < showOnPage) ?
photoStringStart + classShown + photoStringEnd :
photoStringStart + classHidden + photoStringEnd;
$(photoString).appendTo("#flickr");
});
$("a.lightbox").lightBox();
});
});
Create a #flickr div on a page and load that script, photos tagged #FFLIVE2014-09-03 would be displayed, if there are any. My problem is that the site/page I want to show the photos on is dynamic with data generated from a database. So website.com/page.php is the single page, in the database is data for a certain date and a performance that happened on it (For a band).
So what I'm struggling with is how to dynamically edit the tags searched for in the script. With the above script placed in my page.php obviously page.php?id=1 and page.php?id=261 will show the same photos, because the tags searched will be the same when in fact they should be different, based on the date for the data.
So, is there some way to do this? Generate the correct date tag to search for based on the database data? I can generate the correct tag inside the PHP file itself quite easily, just echo the first part of the tag then the date. But how would I do that in relation to the javascript? I gather it is possible to use PHP within Javascript but that would be outside the database, so it wouldn't know what it was generating.
I hope that makes sense!
I have the code to dynamically generate the textboxes. I want to multiply the values of quantity and rate textboxes and display the result in total textbox and post it to next page.
The fiddle http://jsfiddle.net/hEByw/ that shows how textboxes are dynamically generated.
I have tried the following part of code to multiply the two textbox values but its not working for me. please see the fiddle for complete code.
//To multiply two textbox values
$('#qty + counter + ').keyup(calculate);
$('#rates + counter + ').keyup(calculate);
function calculate(e)
{
$('#total + counter + ').val($('#qty + counter +').val() * $('#rates + counter+').val());
}
Can any one suggest where am I going wrong or the correct way of doing it. I am new to jquery. Any help is appreciated.Thanks in advance.
I think the problem is here
$('#rates + counter + ')
It should be made to
$('#rates' + counter)
EDIT :
I analysed it with jsfiddle but the problem is with your logic. How can you get the counter when you are pressing a key. Counter will be used and it will be undefined once the controls are added.
Edit 2 :
At last I came up with the answer.
I had to tweak around a bit but that i hope it will satisfy you
Check This JsFiddle Link
Sorry for editing your own link
I just added a title attribute and i used it instead of the counter variable.
e.target.title For the counter
title = '+ counter + ' in your HTml
Refer the link. Hope this helps you
As long as you are using jquery 1.4+:
$('#qty' + counter).live('keyup', function(){ calculate(counter); });
$('#rates' + counter).live('keyup', function(){ calculate(counter); });
function calculate(counter)
{
total = Number($('#qty' + counter).val())*Number($('#rates' + counter).val())'
$('#total' + counter).val(total);
}
You never know the value of counter when the event triggers.
$('#qty' + counter).on("blur", function() {
calculate($(this));
});
$('#rates' + counter).on("blur", function() {
calculate($(this));
});
function calculate(el) {
var counter = el.attr("id").indexOf("qty") != -1 ? el.attr("id").substring(3) : el.attr("id").substring(5);
var qty = isNaN(parseInt($('#qty' + counter).val())) ? 0 : parseInt($('#qty' + counter).val());
var rate = isNaN(parseInt($('#rates' + counter).val())) ? 0 : parseInt($('#rates' + counter).val());
$("#total" + counter).val(qty * rate);
}
I have a link, and every time it is clicked i need to add a random id to the url, these id's can't be the same, and ideally need to be saved somewhere.
I'm working in php, which i'm pretty new to, therefore I'm not sure how to go about this.
you can do something like that
link
and by using jquery
<script>
var alreadyUsed = ""
function AppendIDToURL(){
var id ;
var loop = true;
while(loop){
id = 1 + Math.floor(Math.random() * 100);
if (alreadyUsed.indexOf("," + id + ",") == -1){
alreadyUsed += "," + id + ",";
loop = false;
}
}
var url = "temp.php/" + id;
//use ajax or any other thing to save this id.
}
</script>
i have this script i'm using to display random images with hyperlinks. can anyone tell me how i might adapt it to display 5 random images at once, preferably without repeating the same image twice?
Thanks
<script language="JavaScript">
<!--
/*
Random Image Link Script- By JavaScript Kit(http://www.javascriptkit.com)
Over 200+ free JavaScripts here!
Updated: 00/04/25
*/
function random_imglink(){
var myimages=new Array()
//specify random images below. You can have as many as you wish
myimages[1]="data/adverts/ad1.png"
myimages[2]="data/adverts/ad2.png"
myimages[3]="data/adverts/ad3.png"
myimages[4]="data/adverts/ad4.png"
myimages[5]="data/adverts/ad5.png"
//specify corresponding links below
var imagelinks=new Array()
imagelinks[1]="http://www.javascriptkit.com"
imagelinks[2]="http://www.netscape.com"
imagelinks[3]="http://www.microsoft.com"
imagelinks[4]="http://www.dynamicdrive.com"
imagelinks[5]="http://www.freewarejava.com"
var ry=Math.floor(Math.random()*myimages.length)
if (ry==0)
ry=1
document.write('<a href='+'"'+imagelinks[ry]+'"'+'><img src="'+myimages[ry]+'" border=0></a>')
}
random_imglink()
//-->
</script>
function random_imglink(){
var myimages=new Array();
...
var imagelinks=new Array();
...
var used = [];
var ry;
var howmany = 5;
for (var i = 1; i <= howmany; i++) {
ry=Math.ceil(Math.random()*myimages.length);
while(used.indexOf(ry)!=-1){
ry=Math.ceil(Math.random()*myimages.length);
}
used.push[ry];
document.write('<a href='+'"'+imagelinks[ry]+'"'+'><img src="'+myimages[ry]+'" border=0></a>')
}
}
this assumes you're going to put more images in your array than 5.
Instead random and checking with while if you have already chosen an image you can move the choosen image to the end of the array and reduce the variable for the random by one. Example:
function random_imglink(select){
if (select > 5 ) {
// make it fail ...
}
//specify random images below. You can have as many as you wish
var myimages = new Array();
myimages[0]="data/adverts/ad1.png"
myimages[1]="data/adverts/ad2.png"
myimages[2]="data/adverts/ad3.png"
myimages[3]="data/adverts/ad4.png"
myimages[4]="data/adverts/ad5.png"
//specify corresponding links below
var imagelinks=new Array()
imagelinks[0]="http://www.javascriptkit.com"
imagelinks[1]="http://www.netscape.com"
imagelinks[2]="http://www.microsoft.com"
imagelinks[3]="http://www.dynamicdrive.com"
imagelinks[4]="http://www.freewarejava.com"
var size = myimages.length
for (var i=0;i<select;i++) {
var index = Math.floor(Math.random() * size);
document.write('<a href='+'"'+imagelinks[index]+'"'+'><img src="'+myimages[index]+'" border=0></a>');
var tmp = myimages[index];
myimages[index] = myimages[size - 1];
myimages[size - 1] = tmp;
tmp = imagelinks[index];
imagelinks[index] = imagelinks[size - 1];
imagelinks[size - 1] = tmp;
--size;
}
}
random_imglink(3);
It could be something like that in one line of code and without creating functions:
<img src="https://www.example.com/images/image-<?php echo rand(1,7); ?>.jpg">
In order to get this to work, you’ll want to name your images: image-1.jpg, image-2.jpg, image-3.jpg....image-7.jpg,
When the page loads, the PHP rand() will echo a random number (in this case, a number between 1 and 7), completing the URL and thus displaying the corresponding image. Source: https://jonbellah.com/load-random-images-with-php/
I'm working on a gallery that pulls up a full image inside a tooltip when hovering over thumbnails. The problem is, these full images commonly go outside the viewfinder. To remedy this, I'm moving the tooltip if the image will go outside the window boundaries, which requires immediately knowing the images dimensions (to avoid the tooltip jumping around).
However, the images take a bit to load (.gifs) so I can't wait on DOM in order to get the dimensions. So, I'm calling a PHP script to return the the image dimensions before they load.
The problem I'm having is that there's no response from my $.get call. I know the PHP script is working fine, but I'm not getting any data back from it through jquery. Any help would be greatly appreciated. Thanks!!
hover.js:
this.imagePreview = function(){
$("a.preview").hover(function(e){
var viewHeight = $(window).height() + $(window).scrollTop();
var viewWidth = $(window).width();
var xOffset=e.pageX+40;
var yOffset=e.pageY+40;
var url = 'http://mysite.com/i/' + this.href.slice(20);
var w = 0;
var h = 0;
$("body").append("<div id='preview'><img src=" + url +" id='img'/></div>");
$.get("getDimensions.php/?img=" + url, function(data){
w = data.w;
h = data.h;
$("body").append("INFO ABOUT IMAGE DIMENSIONS TRIGGERED: " + w + h);
});
$("#preview")
.css("top",yOffset + "px")
.css("left",xOffset + "px")
.fadeIn("fast");
$('#img').load(function() {
if((e.pageX+img.width)>viewWidth) { xOffset=e.pageX-img.width-70; }
if((e.pageY+img.height)>viewHeight) { yOffset=e.pageY-img.height-70; }
$("#preview")
.css("top",yOffset + "px")
.css("left",xOffset + "px")
.fadeIn("fast");
});
},
function(){
$("#preview").remove();
});
};
// starting the script on page load
$(document).ready(function(){
imagePreview();
});
getDimensions.php:
<?php
list($width, $height, $type, $attr) = getimagesize($img);
echo json_encode(array("w"=>$width,"h"=>$height));
?>
$("body").append("<div id='preview'><img src=" + url +" id='img'/></div>");
when u append the img which have src prop,that will not fire load event any more.That's the problem is.
Have you tried..
var rand = Math.floor(Math.random()*11);
$.get("getDimensions.php/?img=" + url + "&r=" + rand, function(data){
w = data.w;
h = data.h;
$("body").append("INFO ABOUT IMAGE DIMENSIONS TRIGGERED: " + w + h);
},"json");
( Also, I would strongly recommend .ajax over .get)
Can you view what you are getting back from getDimensions.php (in firebug)?
My guess is that jQuery has no way of knowing that the data returned from getDimensions.php is JSON (as opposed to plain old text), and it isn’t trying to parse it.
What's the value of data (if you print it out to the console)?
If this is the problem, you can solve it by adding this line to the PHP script, before echo:
header('Content-Type: application/json');