How to display multiple images on random? - php

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/

Related

Redefine ID with ampersand

Working with Sly's scrolling codes (http://darsa.in/sly/).
Having multiple Sly carousels on a page, I need to fix the ID of the frame
I generate them with '#=basic-XXX', where XXX is the record of the album.
the standard code is this:
var $frame = $('#basic');
var $slidee = $frame.children('ul').eq(0);
var $wrap = $frame.parent();
I try to read the ID, including the attached record number from the database.
var $frame = $("[id^=basic-]"); // start with...
// trying these two lines, but they FAIL
var num = $frame.slice(7);
var $frame = $("#basic-"+num);
//from here $frame should be redefined as #basic-THENUMBER
var $slidee = $frame.children('ul').eq(0);
var $wrap = $frame.parent();
Any idea how I can update var $frame with the ID so it works for the rest of the script?
$("[id^=basic-]") will return the elements that match the selector and you can then use .attr('id') to get the first element's id value. If there is only one element with an id starting with basic- then this will work:
$frame = $("[id^=basic-]").attr('id');
Note that when you use String.slice, character positions start at 0, so I think you probably want:
var num = $frame.slice(6);
See this demo:
var $frame = $("[id^=basic-]").attr('id');
console.log($frame);
var num = $frame.slice(6);
console.log(num);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<span id="basic-355">hello world!</span>
</div>
If you have multiple elements that have matching id's you will need to iterate them using .each or similar:
var $frames = $("[id^=basic-]");
$frames.each(function () {
let id = $(this).attr('id');
console.log(id);
let num = id.slice(6);
console.log(num);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<span id="basic-355">hello world!</span>
<span id="basic-562">hello world!</span>
</div>

Fixing jQuery plugin to handle duplicating nested fields with unique ID's

I have a quick question for you guys here. I was handed a set of lead generation pages and asked to get them up and running. The forms are great, expect for one small issue... they use the jQuery below to allow users to submit multiple instances of a data set by clicking an "Add another item" button. The problem is that the duplicated items are duplicated EXACTLY. Same name, id, etc. Obviously, this doesn't work when attempting to process the data via PHP, as only the first set is used.
I'm still learning jQuery, so I was hoping that someone could point me in the right direction for how to modify the plugin below to assign each duplicated field an incremental integer on the end of the ID and name assigned. So, the fields in each dataset are Role, Description, Age. Each additional dataset will use the ID & name syntax of fieldname#, where # represents numbers increasing by 1.
Thanks in advance for any advice!
/** https://github.com/ReallyGood/jQuery.duplicate */
$.duplicate = function(){
var body = $('body');
body.off('duplicate');
var templates = {};
var settings = {};
var init = function(){
$('[data-duplicate]').each(function(){
var name = $(this).data('duplicate');
var template = $('<div>').html( $(this).clone(true) ).html();
var options = {};
var min = +$(this).data('duplicate-min');
options.minimum = isNaN(min) ? 1 : min;
options.maximum = +$(this).data('duplicate-max') || Infinity;
options.parent = $(this).parent();
settings[name] = options;
templates[name] = template;
});
body.on('click.duplicate', '[data-duplicate-add]', add);
body.on('click.duplicate', '[data-duplicate-remove]', remove);
};
function add(){
var targetName = $(this).data('duplicate-add');
var selector = $('[data-duplicate=' + targetName + ']');
var target = $(selector).last();
if(!target.length) target = $(settings[targetName].parent);
var newElement = $(templates[targetName]).clone(true);
if($(selector).length >= settings[targetName].maximum) {
$(this).trigger('duplicate.error');
return;
}
target.after(newElement);
$(this).trigger('duplicate.add');
}
function remove(){
var targetName = $(this).data('duplicate-remove');
var selector = '[data-duplicate=' + targetName + ']';
var target = $(this).closest(selector);
if(!target.length) target = $(this).siblings(selector).eq(0);
if(!target.length) target = $(selector).last();
if($(selector).length <= settings[targetName].minimum) {
$(this).trigger('duplicate.error');
return;
}
target.remove();
$(this).trigger('duplicate.remove');
}
$(init);
};
$.duplicate();
Add [] to the end of the NAME attribute of the input field so for example:
<input type ="text" name="name[]"
This way your $POST['name'] will hold an array of strings. For that element. It will be an array with keys that are numbers from 0 to however many items it holds.

Change background randomly when the page is refreshed

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)] + ')'});

how to load php array into javascript variable on runtime

i have a website/(mobile, app created with phone gap build), in this site i load some arrays with php into javascript to show some ads. on website it's work very well, but on the mobile apps (iOS and android) i got an empty space. if i fill the array variables in js directly, it works in all versions of the site web and mobile.
the problem is i have about 460 different ads to show. i like to load about 20 ads into js when users start or load the site/app in php i read the mysql db and load these ads witch shown less. after showing the ads, ads-couter +1 .(didn't show it here)
the reason why i'm doing this so, is, because i did'n find something to monetize my html5 css3 query web app, compiled with phone gap build.
now can someone show me or explain me why it works on web but not on app, or why it works both when i fill the variable in js direct??
my php works fine -> to js
in js i have this:
// werbung
function werbung_fill(){
id = new Array;
comment_start = new Array;
bannerLinks = new Array;
adBanners = new Array;
bannerTargets = new Array;
dimension = new Array;
comment_end = new Array;
aktiv = new Array;
angezeigt = new Array;
lasttime = new Array;
$.getJSON('inc/werbung_call.php', function(data) {
/* data will hold the php array as a javascript object */
$.each(data, function(key, val) {
id.push(val.id);
comment_start.push(val.comment_start);
bannerLinks.push(val.bannerLinks);
adBanners.push(val.adBanners);
bannerTargets.push(val.bannerTargets);
dimension.push(val.dimension);
comment_end.push(val.comment_end);
aktiv.push(val.aktiv);
angezeigt.push(val.angezeigt);
lasttime.push(val.lasttime);
});
});
}
function werbung(){
var randNum = Math.floor(Math.random() * (19 - 0 + 1)) + 0;
var topAdBanner = $('#topad > a > img');
var newcomment_start = comment_start[randNum];
var newBannerImg = adBanners[randNum];
var newBannerLink = bannerLinks[randNum];
var newBannerTarget = bannerTargets[randNum];
var newdimension = dimension[randNum];
var newcomment_end = comment_end[randNum];
// update new img src and link HREF value
$(topAdBanner).attr('src',newBannerImg);
$('#topad > a').attr('href',newBannerLink);
$('#topad > a').attr('target',newBannerTarget);
$('#topad > a').attr('alt',newdimension);
var deinTimer = window.setTimeout(werbung, 5000);
//$('#topad1').html(id[randNum]);
}
in
$(document).ready(function() {
// werbungs banner
$('<div id="topad"><img src="" width="320" height="50" alt="" border="0"></div><!-- #end #topad -->').prependTo( $( "#hauptheader" ) );
// werbung
werbung_fill();
werbung();
// werbung
}
with this, i can inject a div without compiling the apps again. (it works fine)
the js, php, index.html are on the same server and the compiled apps use the js css images from server too.
You have a few syntax errors in your JavaScript. You should validate your JavaScript here: http://www.jshint.com/
I suspect Android isn't parsing this correctly:
id = new Array;
Suggest using this syntax instead:
var id = [];

Using JavaScript to show and hide PHP echoed XML data

I'm using PHP to echo out 50 video id's from an XML file. I use the video id's to embed 50 YouTube videos into my website. This works fine but I need to isolate the videos two at a time. I don't want the user to see all fifty videos at once. I want them to see two, then click next, see another two, then maybe click back, etc. etc.
Here's what I have so far:
$url = "http://www.theURLofmyXML.blah";
$xml = simplexml_load_file($url);
$i = 0;
while ($i < 49) {
$title = (string) $xml->query->results->item[$i]->title;
$videoid = (string) $xml->query->results->item[$i]->id;
$explanation = (string) $xml->query->results->item[$i]->explanation;
$i = $i + 1;
echo $title."<br />";
echo '<iframe width="400" height="225" src="http://www.youtube.com/embed/'.$videoid.'?rel=0&autohide=1&showinfo=0" frameborder="0" allowfullscreen></iframe><br/>';
echo $explanation."<br /><br />";
}
So I think the best thing to do is echo all fifty items to the page inside divs labeled 0 to 49...then use JavaScript to hide all divs except 0 and 1 until you click a next button and it switches to hiding everything except 2 and 3...and so on...
But I'm not sure how to do that in JavaScript/jQuery. I think using .show() and .hide() would work but I'm not sure of the syntax.
You can use the following HTML structure:
Previous videos
<div class="video-row active">
<!-- First couple videos -->
</div>
<!-- Loop through all videos, writing the other rows -->
<div class="video-row">
<!-- Last couple videos -->
</div>
Next videos
Note: Use the active class only in the first video row to show them by default on the page load.
With CSS, hide all .video-row (using: display:none;) and show only .video-row.active (using: display:block;).
Finally, use the following Javascript (jQuery needed) to navigate between video rows:
jQuery('.prev-video-row').click(function (event)
{
event.preventDefault();
var prev = jQuery('.video-row.active').prev();
if (prev.length)
{
jQuery('.video-row').removeClass('active');
prev.addClass('active');
}
});
jQuery('.next-video-row').click(function (event)
{
event.preventDefault();
var next = jQuery('.video-row.active').next();
if (next.length)
{
jQuery('.video-row').removeClass('active');
next.addClass('active');
}
});
Honestly speaking, I don't think it's great to have 50 videos embedding in a page - regardless of visibility or not; simply because they will be processed by the browser despite not being visible. (Feel free to correct me if I'm wrong, but the browser is going to see, and process, the whole DOM - and just apply the styles to the "hidden" bits.)
Gustavo Straube has given a really good answer on how to do this if you want to have 50 elements in the DOM despite the effects it may have on both browser and bandwith.
I'd probably go for something more along the lines of parsing the XML, storing all the data as JSON then dynamically updating the DOM with jQuery from HTML supplied with a templating framework like Mustache.js.
/* Generate JSON */
$url = "http://www.theURLofmyXML.blah";
$xml = simplexml_load_file($url);
$i = 0;
$json = array();
while ($i < 49) {
$arr['title'] = (string) $xml->query->results->item[$i]->title;
$arr['videoid'] = (string) $xml->query->results->item[$i]->id;
$arr['explanation'] = (string) $xml->query->results->item[$i]->explanation;
$json[] = $arr;
}
echo json_encode($json);
Then, in your markup have something like the below, just to initialise your first x videos - in this example 10..
$(document).ready(function(){
var template = '{{$title}}<br /><iframe width="400" height="225"'
+ 'src="http://www.youtube.com/embed/{{$videoid}}?rel=0&autohide=1&showinfo=0" frameborder="0" allowfullscreen></iframe><br/>'
+ '{{explanation}}<br /><br />';
var html = '';
var i=0;
for(; i<10; i++){
var item = json[i];
html += Mustache.to_html(template, item);
}
$('#videos').html(html); //where #videos is a div to contain your videos
Next up have an anchor (in this example #next) to get the next 10 videos..
$('#next').click(function(){
/* template, i and json are still in scope! */
var j = i+10;
for(; i<j; i++){
var item = json[i];
html += Mustache.to_html(template, item);
}
$('#videos').html(html); //where #videos is a div to contain your videos
});
The advantage of this is it's also easy to do a previous anchor...
$('#prev').click(function(){
/* template, i and json are still in scope! */
var j = i -10;
i -= 20; //10 for the current page, 10 for the start of the previous page
for(; i<j; i++){ //rebuild div content of previous page
var item = json[i];
html += Mustache.to_html(template, item);
}
$('#videos').html(html);
});
Just to re-iterate, this is an alternative solution - I've suggested it as using JSON is a little bit more lightweight and more flexible than XML, and it also removes the requirement for having 50 DOM elements that aren't in use at one time. There may be a reason you've chosen the implementation that you have, but it's not the implementation I would take if I was given this problem!
For html like:
<div id="section0"></div>
Your jquery would look like:
$(document).ready(function() {
$('#section0').show();
$('#section1').show();
$('#nextButton').click(function(e){
e.preventDefault();
$('#section0').hide();
$('#section1').hide();
$('#section2').show();
$('#section3').show();
return false;
}
});
And so on...

Categories