PHP/jQuery: Randomly display single div from loop - javascript

I have a loop that contains dynamic and multiple divs. I only need to display single div randomly and when refreshing the page it should change the div dynamically
Like for example PHP
for($i= 1; $i<=5; $i++){
echo'<div class="">
this is div '.$i.'
</div>';
}
Output will be
1
2
3
4
5
But i want to only display single div. Other should hide using jquery or php, so whenever i refresh the page it should display any number in the loop randomly
//output-->
//this is div 2

First need to calculate the length of div. Then we hide all other elements and show just the randomly chosen one.
$('.random').hide().eq(Math.floor(Math.random()*$('.random').length)).show();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="random">1</div>
<div class="random">2</div>
<div class="random">3</div>
<div class="random">4</div>
<div class="random">5</div>

You can accomplish this only with PHP.
$array = array("PHP", "CSS", "JavaScript", "jQuery");
$randomItem = $array[array_rand($array)];
<div><?php echo $randomItem ?></div>

You can use both css and php
CSS
.Hide_Divs{display: none;}
PHP
$random = rand(1, 5); // random number between 1 to 5
for($i= 1; $i<=5; $i++){
$ran = ($i !== $random)? 'Hide_Divs' ? '';
echo'<div class="'.$ran.'">
this is div '.$i.'
</div>';
}

Related

Javascript gets only the first id from a foreach loop. Why?

I use a foreach loop to get some tabs with different id's. This way I get tabs with ids tab1, tab2, tab3, etc. Than, when I want to get the id of each tab using javascript, it returns only the id of the first tab and uses this for all tabs. It does not loop as php do. Why?
<?php
foreach ($DB_con->query($foos) as $foo) {
?>
<div id='tab<?php echo $counter_foo; ?>'>
<div id="divid" style="visibility: hidden"><?php echo $counter_foo; ?></div>
<script>
$(document).ready(function() {
var dividvalue = document.getElementById('divid').innerHTML;
alert(dividvalue);
});
</script>
<?php
}
?>
Change the id in your HTML to class, and use getElementsByClassName instead of getElementById your in JavaScript.
Your div:
<div class="divid"> <!-- etc -->
and your JS..
var dividvalue = document.getElementsByClassName('divid')[0].innerHTML;
Also consider changing divid to divclass for consistency's sake.
Full edited code:
<script>
var i = 0;
</script>
<?php
foreach ($DB_con->query($foos) as $foo) {
?>
<div id='tab<?php echo $counter_foo; ?>'>
<div class="divclass" style="visibility: hidden"><?php echo $counter_foo; ?></div>
<script>
$(document).ready(function() {
var divclassvalue = document.getElementsByClassName('divclass')[i].innerHTML;
alert(divclassvalue);
i++;
});
</script>
<?php
}
?>

Making a Slideshow in Wordpress using the Advanced Custom fields plugin and the repeater field

I am making my first steps learning to code. I made some courses on Internet and now I decided to continue learning from the experience while I build a Wordpress child theme.
The thing is that I want to make an slideshow and I found this cool and simple one in w3schools http://www.w3schools.com/w3css/tryit.asp?filename=tryw3css_slideshow_self.
It's nice! But there are some problems if I want to implement it in Wordpress.
I made 10 image fields. Each one is one is a space to put one picture of my Slideshow. The code would be something like this:
<?php get_header(); ?>
<script>
var slideIndex = 1;
showDivs(slideIndex);
function plusDivs(n) {
showDivs(slideIndex += n);
}
function showDivs(n) {
var i;
var x = document.getElementsByClassName("mySlides");
if (n > x.length) {slideIndex = 1}
if (n < 1) {slideIndex = x.length}
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
x[slideIndex-1].style.display = "block";
}
</script>
<div class="mySlides"><?php the_field("image"); ?></div>
<div class="mySlides"><?php the_field("image_2"); ?></div>
<div class="mySlides"><?php the_field("image_3"); ?></div>
<div class="mySlides"><?php the_field("image_4"); ?></div>
<div class="mySlides"><?php the_field("image_5"); ?></div>
<div class="mySlides"><?php the_field("image_6"); ?></div>
<div class="mySlides"><?php the_field("image_7"); ?></div>
<div class="mySlides"><?php the_field("image_8"); ?></div>
<div class="mySlides"><?php the_field("image_9"); ?></div>
<div class="mySlides"><?php the_field("image_10"); ?></div>
<a class="home-btn-left" onclick="plusDivs(-1)">❮</a>
<a class="home-btn-right" onclick="plusDivs(1)">❯</a>
</div><!-- .content-area -->
<?php get_footer(); ?>
This has a problem: I have always to upload 10 images because if I upload less than 10 images I would have empty custom fields that would be showed as blank spaces.
Because of this problem I decided to make a repeater field. So I can create how many image subfields as I want without having this empty fields problem.
So the code would be something like this:
<?php
// check if the repeater field has rows of data
if( have_rows('image') ):
// loop through the rows of data
while ( have_rows('image') ) : the_row();
// display a sub field value
the_sub_field('subimage');
endwhile;
else :
// no rows found
endif;
?>
But now the question is: How can I do to apply an html class to my subfield? like this I can make the slideshow.
I tryied this but it doesn't work:
<?php
// check if the repeater field has rows of data
if( have_rows('image') ):
// loop through the rows of data
while ( have_rows('image') ) : the_row();
// display a sub field value
<div class="mySlides"> the_sub_field('subimage');</div>
endwhile;
else :
// no rows found
endif;
?>
Do you have some suggestion?
First of all, don't use the_sub_field() here. the_sub_field() echoes the field. Instead of this, use get_sub_field. It retrieves the value without outputting it. your code should look like this:
// check if the repeater field has rows of data
if( have_rows('image') ):
// loop through the rows of data
while ( have_rows('image') ) : the_row();
if( get_sub_field('subimage') ) :
// display a sub field value
echo '<div class="mySlides">' . get_sub_field('subimage') . '</div>';
endif;
endwhile;
endif;
Note the if( get_sub_field('subimage') ) : statement to check if there is really a value within the repeater field. If yes, it echoes strings chained with your get_sub_field('subimage') function.
Take a look here to advanced examples.
Replace the line
<div class="mySlides"> the_sub_field('subimage');</div>
with:
?><div class="mySlides"><?php the_sub_field('subimage'); ?></div> <?php
When mixing html and php you have to jump in and out of php-mode for the code to work.
An alternative would be using echo to print the html while in php-mode:
echo '<div class="mySlides">';
the_sub_field('subimage');
echo '</div>';

How do I move a php call to another div and have it still work

I've looked around a bit, and found issues similar to mine, but not quite the same. I have a page template that is laid out in 4 columns in HTML. Inside column 4, I have a php function echoing a gallery of images.
<div id="homepage-layout">
<div id="homepage-column-1">
<div class="homepage-small"><?php echo get_homepage_img_small_1(); ?></div>
<div class="homepage-small"><?php echo get_homepage_img_small_2(); ?></div>
<div class="homepage-small"><?php echo get_homepage_img_small_3(); ?></div>
</div><!-- End Column 1 -->
<div id="homepage-column-2">
<div class="homepage-large-left"><?php putRevSlider("homepage"); ?></div>
</div><!-- End Column 2 -->
<div id="homepage-column-3">
<div class="homepage-med"><?php echo get_homepage_img_med_1(); ?></div>
<div class="homepage-med"><?php echo get_homepage_img_med_2(); ?></div>
</div>
<div id="homepage-column-4">
<div class="homepage-large-right"><?php putRevSlider("home_small"); ?></div>
</div><!-- End Column 4 -->
</div>
I'm using jQuery to change the layout of the site based on the width of the window.
var column3 = $("#homepage-column-3").contents();
var column4 = $("#homepage-column-4").contents();
var swapped = false;
$(window).on('resize', function() {
if( $(window).width() <= 700 && !swapped){
$("#homepage-column-3").html(column4);
$("#homepage-column-4").html(column3);
swapped = true;
} else if( $(window).width() > 700) {
$("#homepage-column-3").html(column3);
$("#homepage-column-4").html(column4);
swapped = false;
}
});
However, when the window size triggers the jQuery, the RevSlider from Column 4 freezes on the image it was displaying at the time, and the only way to get it running again is to refresh the page.
Any thoughts? Or, if this question has been answered already, please point me in the right direction.
Thanks!
jeroen had the right idea. I was able to take the 4 columns, and split them into 2 chunks. I was then able to make them both flex containers, and with a of media query, was able to make the columns swap places while keeping the RevSlider initialized.
Thanks to all for your help!

How to access a internal div's ID (auto-incremented) by an external DIV id?

guys!
I got the following code:
<?php
for ($i = 0 ; $i < 4 ; $i++) {
?>
<!--EXTERNAL DIV-->
<div class = "square" onClick = "paint(this.id); doSomethingElse(this.id)"<br> id = "<?php echo "$i" ?>">
(...)
<!--Internal DIV-->
<div id = "test<?php echo "$i";?>">
</div>
</div>
What I want is: I need to call the 'doSomethingElse' function in the External DIV (because it's a square that will be clicked), but it will show (display: visible) the Internal DIV, so I need to access the internal div's ID from the external div's ID using jQuery or javascript.
I know it's a little confusing, but I think that's the way I can get what I want.
Thank you!
Well, to start, get rid of the break tag in your div. and your id's need to begin with a letter. and your echo statements need a semi-colon:
<div class="square" onClick="paint("#a<?php echo "$i"; ?>"); doSomethingElse("#a<?php echo "$i"; ?>")" id = "a<?php echo "$i"; ?>">

JQuery click slidetoggle only working for the first DIV of PHP repeated DIVS

I have DIVs which are repeated for records in a database via PHP, and I have jquery script which on click should expand a div bellow out.
This is the simple code for the slide, generic stuff:
<script src =
"http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){ // Line A
$("#flip").click(function(){ // Line B
$("#panel").slideToggle("slow"); // Line C
});
});
</script>
<body>
<div style="background:red" id="flip">Click to slide the panel down or up</div>
<div style="background:green" id="panel">Oh Hello There</div>
#panel {
display:none;
}
Fiddle: http://jsfiddle.net/hpvgp/3/
However when I try and apply this to my code where I have the divs looped out, it only works for the first div.
Current code:
<?php
$webserver = 'localhost';
$administrator = 'root';
$password = '';
$db_name = 'cdb';
$db = mysqli_connect($webserver, $administrator, $password, $db_name)
or die('Error connecting');
if( isset($_REQUEST['page'])) {
$_SESSION['page'] = $_REQUEST['page'];
}else{
$_SESSION['page'] = 1;
}
$records_per_page = 8;
$query = "SELECT * FROM cars";
$result = mysqli_query($db, $query)
or die("Error in query: '$query'");
$row = mysqli_fetch_assoc($result);
$i = 0;
$start = ($_SESSION['page'] - 1) * $records_per_page;
$end = ($_SESSION['page']) * $records_per_page;
while($row = mysqli_fetch_assoc($result) and $i < $end) {
$i++;
if( $i > $start )
{;
echo'
<div><br><br>
<div id="flip" class="navbar navbar-inverse" style ="margin-top:-40px; height:128px">
<div style="float:left; height:100px; width:200px">
<img src="'.$row['logo'].'" style="margin:10px; float:left" height="100"/></div>
<div style="float:left"><h2>'.$row['make'].' '.$row['model'].'</h2></div>
</div>
</div>
<div><img id="panel" style="padding-bottom: 100px" src="images/cars/'.$row['carIndex'].'.jpg" height="300"/><div> ';
}
}
I'm currently using Bootstrap, not sure if that would matter.
I find it really strange that this would work for the first DIV but not any of the following ones. Do I perhaps need to place the script somewhere else? I'm really lost on this.
Any help appreciated -Tom
IDs are expected to be unique. Never use the same id more than once in a document. Change your code to:
while($row = mysqli_fetch_assoc($result) and $i < $end) {
$i++;
if( $i > $start )
{
echo'
<div><br><br>
<div class="flip navbar navbar-inverse" data-panel="panel_' + $i . '" style ="margin-top:-40px; height:128px">
<div style="float:left; height:100px; width:200px">
<img src="'.$row['logo'].'" style="margin:10px; float:left" height="100"/></div>
<div style="float:left"><h2>'.$row['make'].' '.$row['model'].'</h2></div>
</div>
</div>
<div><img id="panel_' . $i . '" style="padding-bottom: 100px" src="images/cars/'.$row['carIndex'].'.jpg" height="300"/><div> ';
}
}
And now chang your javascript to:
<script>
$(document).ready(function(){
$(".flip").click(function(){
var panelId = $(this).attr('data-panel');
$('#' + panelId).slideToggle("slow")
});
});
</script>
This way your IDs are unique, and each panel is related to its 'flip' div via a custom attribute (data-panel) that contains the panel's ID.
You're assigning the same ID to multiple divs. An ID is, by definition, unique. If you set the same ID on more than one element then your HTML will be invalid and all bets are off. jQuery will use GetElementByID () to select which element to grab when you pass it an ID, and the behaviour of GetElementByID when there's more than one element with the same ID is undefined. It could in theory do anything (throw an exception, return the first matching element, select the last matching element, select a single matching element at random, make demons fly out of your nose, etc).
As you want your code to affect more than one element, then all those elements have something in common. Therefore they all belong to the same class of elements, and you should use class="someclass" to indicate which elements belong to that class. HTML like:
<div class="flip navbar navbar-inverse" style ="margin-top:-40px; height:128px">
JS like:
$(".flip").click(function(){ // Line B
As an advice that works at least for me, when I'm using classes for bind functions, I like to difference that class to the others, so I add the prefix "js-" to the class. That way I'll know that it's not a design class, that an event is bind to that class and that class should not be removed. So I'll use "js-flip" instead "flip". But it is just and advice as good practises and some people cannot be agree with me, but it has been quite useful in projects where more than one person were touching the same code. Also I will not add css styles to that class because the porpoise of it is only programmatic, so it will be transparent for the designers.

Categories

Resources