I have an HTML page with 5 images (48px × 48px each) on it. I want to appear the images at random locations on the webpage everytime the page is loaded.
I don't know how to implement this, I just know I'm going to need CSS and JavaScript (for randomization) for this. Any ideas or suggesions?
Here is sample HTML code:
<img alt="Twitter" src="/images/twitter-48.png" />
<a href="http://facebook.com/><img alt="Facebook" src="/images/facebook-48.png" /></a>
<img alt="Google Plus" src="/images/plus-48.png" />
<img alt="GitHub" src="/images/github-48.png" />
Here's a rather simple implementation: http://jsfiddle.net/Eu8wT/
$('div.randomizeme').css({
top: Math.random() * 100+'%',
left: Math.random() * 100+'%'
});
To apply this over several elements:
$('div.randomizeme').each(function(){
$(this).css({
top: Math.random() * 100+'%',
left: Math.random() * 100+'%'
});
});
Here's the same thing without jQuery:
var elements = document.querySelectorAll('.randomizeme');
for (var i in elements) {
elements[i].style.top = Math.random() * 100 + '%';
elements[i].style.left = Math.random() * 100 + '%';
}
A solution that uses pure JavaScript (no library)
var imgs = document.querySelectorAll('.rand'),
len = imgs.length,
/* subtract the width/ height of images */
w = document.body.clientWidth - 48,
h = document.body.clientHeight - 48;
for(var i = 0; i < len; i++) {
imgs[i].style.top = Math.floor(Math.random() * h) + 'px';
imgs[i].style.left = Math.floor(Math.random() * w) + 'px';
}
working demo
Lets assume that you already have the images hardcoded on to your html document. What you would need to do (if you want to accomplish this with PHP) is add a style attribute to each element. In your case, your images are held within <a> tags, so you'll want to position the <a> tag randomly and not the images...
function generateRandomPositions(){
// define maximum and minimum 'top' values
$maxTop = 1000;
$minTop = 0;
// define maximum and minimum 'left' values
$maxLeft = 1000;
$minLeft = 0;
$styleProperties = array(
'position:absolute',
'top:'.rand($minTop,$maxTop) . 'px',
'left:'.rand($minLeft,$maxLeft) . 'px'
);
return ' style="'.implode(';',$styleProperties).'" ';
}
The function will return a string similar to this -
style="position:absolute;top:10px; left:45px;"
Now all you have to do is call this function for each image on your page -
<a <?php echo generateRandomPositions();?> ><img src="...
<a <?php echo generateRandomPositions();?> ><img src="...
<a <?php echo generateRandomPositions();?> ><img src="...
<a <?php echo generateRandomPositions();?> ><img src="...
Your <a> tags will now contain random CSS positioning parameters and their images will move with them.
As I'm sure you can see, this method of using PHP to generate inline CSS properties is kind of a backwards way to do this. JavaScript would probably be the best way to get what you are looking for and there are other answers that cover it. You could initially hide your elements with CSS and then display them with the JavaScript after you have set the random positioning.
References -
rand()
implode()
<?php
$images= array(
'twitter-48.png',
'facebook-48.png',
'plus-48.png',
'github-48.png'
);
$keys= range(0, count($images)- 1);
shuffle($keys);
foreach($keys as $key) {
print "<div>{$images[$key]}</div>";
}
EDIT:
<?php
$images= array(
array('href'=> 'http://twitter.com/', 'alt'=> 'Twitter', 'src'=> '/images/twitter-48.png'),
array('href'=> 'http://facebook.com/', 'alt'=> 'Facebook', 'src'=> '/images/facebook-48.png'),
array('href'=> 'https://plus.google.com/', 'alt'=> 'Google Plus', 'src'=> '/images/plus-48.png'),
array('href'=> 'https://github.com/', 'alt'=> 'GitHub', 'src'=> '/images/github-48.png')
);
$keys= range(0, count($images)- 1);
shuffle($keys);
?>
<div class='location1'>
<a href='<?php print $images[$keys[0]]['href']; ?>'><img alt='<?php print $images[$keys[0]]['alt']; ?>' src='<?php print $images[$keys[0]]['src']; ?>'></img></a>
</div>
<div class='location2'>
<a href='<?php print $images[$keys[1]]['href']; ?>'><img alt='<?php print $images[$keys[1]]['alt']; ?>' src='<?php print $images[$keys[1]]['src']; ?>'></img></a>
</div>
<div class='location3'>
<a href='<?php print $images[$keys[2]]['href']; ?>'><img alt='<?php print $images[$keys[2]]['alt']; ?>' src='<?php print $images[$keys[2]]['src']; ?>'></img></a>
</div>
<div class='location4'>
<a href='<?php print $images[$keys[3]]['href']; ?>'><img alt='<?php print $images[$keys[3]]['alt']; ?>' src='<?php print $images[$keys[3]]['src']; ?>'></img></a>
</div>
Try this:
$images = array('1.gif', '2.gif', '3.gif');
$images = array_shaffle($images);
foreach ($images as $image) {
echo "<img src='{$image}' />;
}
Related
I'm pretty new to Jquery and writing a gallery with multiple pages and I have a problem with the Jquery selector.
I'm trying to select a img tag and a a tag, both tags have different class names and are in a .portfolio-item class.
What I've tried is
var countImages = $(".portfolio-item a img").length;
console.log(countImages);
var perPage = 8;
$('.image, .edit-post-link').css('display', 'none');
//$('.post-edit-link').css('display', 'none');
//$('.slider').children().slice(0, perPage).css('display', 'block');
$('.image, .edit-post-link').slice(0, perPage).fadeIn("fast");
//$('.post-edit-link').slice(0, perPage).fadeIn("fast");
function goTo(pageNumb){
var startFrom = pageNumb * perPage;
var endOn = startFrom + perPage;
//$('.post-edit-link').fadeOut("fast").delay( 200 ).slice(startFrom, endOn).fadeIn("fast");
$('.image, .edit-post-link').fadeOut("fast").delay( 200 ).slice(startFrom, endOn).fadeIn("fast");
}
var buttons = countImages/perPage;
console.log(buttons);
for (var i = 0; i < buttons; i++) {
var number = i + 1;
$(".pagination").append("<li><a class='navigation-number'>"+number+"</a></li>");
//console.log(number);
};
$('.navigation-number').on('click', function() {
var pageNumber = $(this).text();
goTo(pageNumber -1);
});
this only results in 4 images on each page, but I wanted 8 on one page
<?php if (have_posts()): while (have_posts()) : the_post(); ?>
<div class="portfolio-item">
<!-- post thumbnail -->
<?php if ( has_post_thumbnail()) : // Check if thumbnail exists ?>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
<?php the_post_thumbnail('medium', array('class' => 'img-responsive image')); // Declare pixel size you need inside the array ?>
</a>
<?php endif; ?>
<!-- /post thumbnail -->
<div class="edit-post-link">
<?php edit_post_link(); ?>
</div>
</div>
Edit 3:
<div class="col-md-3 portfolio-item">
<!-- post thumbnail -->
<a href="http://www.q-mediaspot.nl/blog/cinema-4d/cinema-4d-vaas/" title="Cinema 4d Vaas" style="display: none;">
<img src="http://www.q-mediaspot.nl/blog/wp-content/uploads/2016/03/placeholder1-250x150.jpg" class="img-responsive image wp-post-image" alt="placeholder1"> </a>
<!-- /post thumbnail -->
<div class="edit-post-link">
<a class="post-edit-link" href="http://www.mywebsite.nl/blog/wp-admin/post.php?post=4&action=edit">Edit This</a>
</div>
This
$('.portfolio-item').children('a, img')
var $els = $("img.className, a.otherClassName");
This:
$(".portfolio-item a img")
Will select img elements which are inside of a elements which are inside of any element with the portfolio-item class.
It sounds like you want to select a and img elements which themselves have that class. Which would be something like this:
$("a.portfolio-item, img.portfolio-item")
Or, to break it down descriptively (not an actual selector in this case):
$("[tag].[class of that tag], [another tag].[class of that tag]")
Any tag, any class, however you want to define it. Specifically note that there is no space between the tag and the class in this selector. That's because with a space it means "the second part as a child of the first part" whereas without a space it means "the second part as a modifier of the first part".
Edit: Or, perhaps I misunderstood. Do you mean that the a and img tags are themselves descendants of some other element of the portfolio-item class? In that case, it would be more like this:
$(".portfolio-item a, .portfolio-item img")
That is, "all a elements which are inside any .portfolio-item element, and all img elements which are inside any .portfolio-item element".
This code at the moment picks 6 random images from my images directory and places them in a sidebar for display. The problem is that I don't want the sidebar to display just 6 images, I want the sidebar to generate images to match the height of my main content div.
for($i = 0 ; $i < $imagesCount ; $i++) {
$randomIndex = array_rand($images);
$file_title = $randomImage = $images[$randomIndex];
unset($images[$randomIndex]);
?>
<a href="<?php echo $randomImage ?>"><img src="<?php echo $randomImage ?>"
width="100%" height="150%"; alt="" /> <br /><br /></a>
<?php
}
?>
Right now my idea was using jquery to find the height of the div and generating images until the value of the height is reached using something like this pseudo code:
for($i = 0 ; $i < $("#content").height(); ; $i++) {
random images stuff here;
}
The problem here (besides the fact that I am mixing JQuery and PHP which I would fix later) is that .height() is going to return me a value in pixels thus randomly generating 800-1200 random images. Does anyone have any ideas on how to approach this problem? Here is a link to the page so you can see what I mean if there is any confusion. Link
There's really a lot of ways you can approach this but...
Use php to create your dom elements like so and pass them off to jQuery as a variable:
<?php
$images = howeverYourGettingYourSixImages();
for($i=0; $i<count($images); $i++){
$image_array[]='<img class="images" src="'.$images[$i].'"/>';
}
echo('<script type="text/javascript">var images='.json_encode($image_array).'</script>');
?>
somewhere in your body declare your container
<div id="content"></div>
and before the body close execute the jQuery
<script type="text/javascript">
var container = jQuery('#content');
var container_height = container.height();
var image_height = container_height / images.length;
jQuery.each(images,function(k,v){
container.append(v);
});
jQuery(".images").height(image_height);;
</script>
and to ensure your content container has a height and that the elements stack add some css to your head
<style type="text/css">
#content{
height: 600px;
}
.images{
float:left;
clear:both;
}
</style>
I'm working on a project in which I want to display randomly any given number of results suppose, I have six <html> tags of image and I only want to display three randomly so that every time we refresh the page it show randomly any three image out of any six
I'm using html code for an example
<html>
<body>
<div class=1>
<a href="http://example1.com">
<div>
<img src="image1.jpg">
</div>
</a>
</div>
<div class=1>
<a href="http://example2.com">
<div>
<img src="image2.jpg">
</div>
</a>
</div>
<div class=1>
<a href="http://example3.com">
<div>
<img src="image3.jpg">
</div>
</a>
</div>
<div class=1>
<a href="http://example4.com">
<div>
<img src="image4.jpg">
</div>
</a>
</div>
<div class=1>
<a href="http://example5.com">
<div>
<img src="image5.jpg">
</div>
</a>
</div>
<div class=1>
<a href="http://example6.com">
<div>
<img src="image6.jpg">
</div>
</a>
</div>
</body>
</html>
Out of this Six Images I only want to show any three Images Each time through php. Is it possible and how can I do that?
Hope you may find any better solution.
Also i want to display Other tags like link inthe image and some more tags so that i can display images in a better way through css so I think it can be done by switch statement more easily
Let's say you have a array with all the images. From that list, we randomly get the keys for 3 of the images. We then through a loop echo out the img tag:
<html>
<body>
<?php
$images = [
'image1.jpg',
'image2.jpg',
'image3.jpg',
'image4.jpg',
'image5.jpg',
'image6.jpg'
];
// Selects 3 random array values and returns the key for each value
$randomkeys = array_rand($images, 3);
// Here we loop through the given index keys from the $images array.
// For each key we will then get the value from $images with the index $key
foreach ($randomkeys as $key) {
// I end with PHP_EOL (End of line) so the source code will look a bit prettier.
echo "<div class=\"image\"><img src=\"{$images[$key]}\"></div>".PHP_EOL;
}
?>
</body>
</html>
If something was unclear, let me know
Edit 1: Added more tags
It's not hard to add more tags to the output. If you know how to echo string and variables you should be able to easy add more tags or change them the way you want.
As you can see in the update I have added the class image to the , and made the link to the same path as the image so when you click it it will just open the image in the same window.
<?php
$images=array('image1.jpg','image2.jpg','image3.jpg','image4.jpg','image5.jpg','image6.jpg');
shuffle($images);
for($i=0;$i<=2;$i++){
echo '<img src="'.$images[$i].'" />';
}
?>
Just expanded Morten's code:
<html>
<body>
<?php
$images = array(
array('img' => 'image1.jpg', 'url' => 'http://example1.com', 'div' => 'class="d1"'),
array('img' => 'image2.jpg', 'url' => 'http://example2.com', 'div' => 'class="d2"'),
array('img' => 'image3.jpg', 'url' => 'http://example3.com', 'div' => 'class="d3"'),
array('img' => 'image4.jpg', 'url' => 'http://example4.com', 'div' => 'class="d4"'),
array('img' => 'image5.jpg', 'url' => 'http://example5.com', 'div' => 'class="d5"'),
array('img' => 'image6.jpg', 'url' => 'http://example6.com', 'div' => 'class="d6"')
);
// Selects 3 random array values and returns the key for each value
$randomkeys = array_rand($images, 3);
// Here we loop through the given index keys from the $images array.
// For each key we will then get the value from $images with the index $key
foreach ($randomkeys as $key) {
// I end with PHP_EOL (End of line) so the source code will look a bit prettier.
echo '<div class="1">' . PHP_EOL . '' . PHP_EOL . '<div ' . $images[$key]['div'] . '>' . PHP_EOL . '<img src="' . $images[$key]['img'] . '">' . PHP_EOL . '</div>' . PHP_EOL . '</div>' . PHP_EOL;
}
?>
</body>
</html>
Result:
https://3v4l.org/OAc6l
Like #AbraCadaver said.
<?php
// vim: set ts=4 sw=4 et:
$myImages = array_map(function($i) { return "/foo$i.jpg"; }, range(1, 6));
foreach (array_map('htmlspecialchars', array_map(function ($i) { global $myImages; return $myImages[$i]; }, array_rand($myImages, 3))) as $image)
echo "<img src=\"$image\"/>\n";
You can keep your src paths in an array. Then you can use array_rand() function to get random array index.
For example:
<?php
$allImages = ["images1.jpg","images2.jpg","images3.jpg","images4.jpg","images5.jpg","images6.jpg"];
//this will return random keys of $allImages array
$randomKeys = array_rand($allImages, 3);
foreach($randomKeys as $key){ ?>
<div><img src="<?php echo $allImages[$key] ?> " ></div>
<?php
}
?>
This is how you can do this using php
In this case, you mean if the page is already prepared ( may be the page is external webpage, or another page which is being already designed) i would use Simple Html Dom. Download and include the folder to the project.
example.html
<html>
<style>
img{
width:100px;
height:100px;
}
</style>
<body>
<div class=1>
<a href="http://example1.com">
<div>
<img src="image (1).jpg" >
</div>
</a></div>
<div class=1>
<a href="http://example2.com">
<div>
<img src="image (2).jpg" >
</div>
</a></div> <div class=1>
<a href="http://example3.com">
<div>
<img src="image (3).jpg" >
</div>
</a></div>
<div class=1>
<a href="http://example4.com">
<div>
<img src="image (4).jpg" >
</div>
</a></div>
<div class=1>
<a href="http://example5.com">
<div>
<img src="image (5).jpg" >
</div>
</a></div>
<div class=1>
<a href="http://example6.com">
<div>
<img src="image (6).jpg" >
</div>
</a></div>
</body>
</html>
myphp.php
/**echo '<style>
img{
width:100px;
height:100px;
}
</style>';**/
//using Simple HTML DOM. This file is in Simple Html Dom folder downloaded
include('simple_html_dom.php');
// get DOM from URL or file
$html = file_get_html('example.html');// you can write your external website file here www.external.com/index.html
// find all link
foreach($html->find('a') as $e)
//echo $e->href . '<br>';
$image_with_link['link'][]=$e->href;
// find all image
foreach($html->find('img') as $e)
//echo $e->src . '<br>';
$image_with_link['image'][]=$e->src;
//for debugging
//echo '<pre>';
//print_r($image_with_link);
//echo '</pre>';
//loop number of times, here i want to display three images
for($i=0;$i<3;$i++){
//get random key from array
$rand=array_rand($image_with_link['image'],1);
//print 3 images with its links
echo '<a href="'.$image_with_link['link'][$i].'" />';
echo '<img src="'.$image_with_link['image'][$i].'" />';
}
Treat the code as one big string. Remove <HTML>, </HTML>, <BODY>, and </BODY> from that string. You can add them back whenever you want. Next, explode the string around "<DIV ". For the array that is created, add "<DIV " to the start of each element. You now have an array containing each div section which has each image and link you want. You can then pick ones at random from that array and insert as needed:
// remove HTML and BODY tags
$remove1 = str_replace("<HTML>", "", $original);
$remove2 = str_replace("<BODY>", "", $remove1);
$remove3 = str_replace("</HTML>", "", $remove2);
$cleaned = str_replace("</BODY>", "", $remove3);
// explode remaining code around "<DIV " so we have each division for each image
$codeArray = explode("<DIV ", $cleaned);
// with our code sectioned in an array, add "<DIV " back to the start
// of each element in the array
for ($x = 0; $x < count($codeArray); $x++){
$codeArray[$x] =. "<DIV ";
}
// the $codeArray now has $x elements of the sections that contain the
// links and images you want.
// You can now randomly grab the div's that you want, by
// Shuffling that array, pick the first X images you want, and then
// echo back out the code you want.
shuffle($codeArray);
echo "<HTML>";
echo "<BODY>";
for ($x = 0; $x < $whateverNumberOfImagesYouWant; $x++){
echo $codeArray[$x];
}
echo "</BODY>";
echo "</HTML>";
i am working on a project in which i require the width of a image from href when i click on the specific image the width if the image displays in a alert .
the following is the href and image code i am using
<li>
<a href="<?php echo $pic;?>?id=<?php echo $id;?>&pic=<?php echo $picID;?>" data-title="" data-desc=" " data-rel="group2" data-bw="<?php echo $pic;?>" class="lightbox" id="plzx" >
<img src="<?php echo $pic;?>" width="160" height="160" title="Click To View"/></a>
</li>
whenever i try to get the width of the image it takes the image width from the img tag not from the href . as the img tag width is already defined "160" . is there a way possible for getting the width of the image from the <a href
i am using the following code which is nit working
$('a').click(function() {
var image = $("<img />").attr("src", $(".lightbox").attr("href"));
$(document).append(image);
alert(image.height());
alert(image.width());
image.remove();
});
the html code
<li>
<a href="uploads/kareena-kapoor-144a_$1$Ni5.St4.$kPORmHFjcfGBJjn2KHSis0.jpg?id=3&pic=101" data-title="" data-desc=" " data-rel="group2" data-bw="uploads/kareena-kapoor-144a_$1$Ni5.St4.$kPORmHFjcfGBJjn2KHSis0.jpg" class="lightbox" id="plzx" >
<img src="uploads/kareena-kapoor-144a_$1$Ni5.St4.$kPORmHFjcfGBJjn2KHSis0.jpg" width="160" height="160" title="Click To View"/></a>
</li>
Based on something like:
<img src="/path/to/small.jpg">
This should do it:
$('a').click(function() {
$(new Image()).load(function() {
alert(this.width); // image width
alert(this.height); // image height
}).attr('src', this.href);
});
Update: If you need to continue your program using the width/height, try:
var width,height;
$('a').click(function() {
$(new Image()).load(function() {
width = this.width;
height = this.height,
onLoaded();
}).attr('src', this.href);
});
function onLoaded() {
alert(width);
alert(height);
// continue...
}
You don’t need to append the temporary image to the document, but you do need to add a load listener before you extract width/height.
Remember that the AdBlock extension can affect the outcome of the extraction in webkit, so please turn it off when debugging.
How to know which HTML element is clicked using javascript and get its ID?
I have displayed 3 labels dynamically using PHP for pagination- Page 1 , 2, 3 ,
<label id="<?php echo 'labelofpagination'.$z; ?>" value="<?php echo $z; ?>" >
<a href=# onclick="paginationlabelclicked(); "><?php echo $z; ?>
</a>
</label>
Now i want that if 1 is clicked then 1-10 records are displayed , if 2 , then 11-20 and so on.For this i would run a MySQL query accordingly.
But how do i get the ID ,
Build on things that work. Start with a working link.
<a href="myScript.php?page=$z"
onclick="return paginationlabelclicked(this);">
<?php echo $z; ?>
</a>
Then your script can extract the value from the href attribute or the content.
function paginationlabelclicked(element) {
var page = element.firstChild.data;
// …
return false;
}
It would be a good idea to ditch the onclick attribute too.
try pass this to handler
<a href=# onclick="paginationlabelclicked(this); "><?php echo $z; ?>
</a>
and then you can access id by using
function paginationlabelclicked(el){
alert(el.id);
// your code
}
UPDATE
In order that to be working you have assign id to anchor
<a id="page<?php echo $z; ?>" href=# onclick="paginationlabelclicked(this); "><?php echo $z; ?>
</a>
and then you can access id by using
function paginationlabelclicked(el){
alert(el.id.replace('page', ''));
// your code
}
You can easily send the id into the function called onclick, something like that:
<label id="<?php echo 'labelofpagination'.$z; ?>" value="<?php echo $z; ?>" >
<a href=# onclick="paginationlabelclicked(<?php echo $z; ?>); "><?php echo $z; ?>
</a>
</label>
I'm assuming, what you want to do is to get the text out of the <a> link that was clicked on so you can know what number the user clicked on and you can use that for your query. Here's a jQuery version:
HTML:
<label id="labelofpagination">
1
2
3
4
5
</label>
Javascript:
$("#labelofpagination a").click(function() {
// get text, trim string, convert to number
var num = parseInt($(this).text().replace(/^\s+|\s+$/g, ""), 10);
// go to that page here
});
And a jsFiddle demo: http://jsfiddle.net/jfriend00/wesWd/
<a href=# onclick="paginationlabelclicked(this.parentNode); ">
...
function paginationlabelclicked(el){
alert(el.id);
// your code
}