Select multiple divs and change their backgrounds - php

I am creating multiple divs in a loop in php shown below.
<?php
for ($i=0; $i<=9; $i++)
{
for ($j=0; $j<=9; $j++)
{
echo "<div class=\"bg\" id=\"aaa".$i."\" style=\" position:absolute;top:".($i*10)."%;left:".($j*10)."%;\">
</div>";
}
}
?>
i want to select multiple divs (not all) and change their backgrounds using jquery. i cant seem to be able to figure out how to proceed with this

You can select div with id starting with aaa
$('div[id^=aaa]')

if you want to select yhe div's based on their index, you could use the nth-of-type selector:
divs = $('.bg:nth-of-type(1)');
divs.css('background-color','blue');
You can select multiple elements by adding them to the variable:
divs.add('.bg:nth-of-type(2)').add('.bg:nth-of-type(3)');
Note that these are css selectors so it may be an idea to simply do this in css:
.bg:nth-of-type(1),
.bg:nth-of-type(2),
.bg:nth-of-type(3){
background-color: blue;
}
also note you can use an expression inside the brackets to represent multiple values in a sequence.
.bg:nth-of-type(3n+1){ //will select every fourth div
background-color: blue;
}
Unless you can come up with a better criteria for which div's you want to change, this is probably the best way.
Source(s)
jQuery API - .add()
MDN - CSS :nth-of-type selector

This should do the trick:
var arrayDivs = $('div[id^=aaa]');
$.each(arrayDivs, function(){
$(this).css('background-color', '#000');
});
If you want to select multiple lists and not all "aaa"+integer ones, you will need to either know the numbers of those or you need to differ within your loops already.
More information would be awesome!

The "proper" way (if you can say that) would be to group the elements you want to assign common properties with appropriate classes. You can then manipulate them via CSS
So in essense, while looping in the above code :
for ($i=0; $i<=9; $i++) {
for ($j=0; $j<=9; $j++) {
$classes = 'bg';
if( [somelogic] ) { $classes .= ' bluefront'; }
if( [otherlogic] ) { $classes .= ' greenback'; }
echo "<div class=\"".$classes."\" id=\"aaa".$i."\" style=\" position:absolute;top:".($i*10)."%;left:".($j*10)."%;\"></div>";
}
}
and then, via CSS :
.bg.bluefront { color: blue; }
.bg.greenback.bluefront { background-color: green; color: white; }

//select all elements with class bg and add background image
$('.bg').css('background-image',"url('some_image.gif')");
better yet use css:
.bg {
background-image: url('some_image.gif');
}
if you only want some divs from the class bg:
$('.bg').each(function(index,element){
//your code here eg:
if(index == 2)
alert(index);
});

Related

PHP How to Echo Across the Whole Page

I have created a skin switcher and it is working great, but the code is messy.
I save a cookie and then for some defined css classes, I append '-userDelectedColourFromTheCookie' to the end of the css class to apply it on the page.
So far, I am adding a short php line to the end of every instance of these classes in the html code and as I have said, it is working.
I would prefer to run the php code just once across the whole page and update all occurrences of an array containing the required classes to append the class as above.
I have this at the top of my page:
<?php
$classList = array("theme-1","theme-2","theme-3","theme-4","theme-5","theme-6","theme-7","theme-8","theme-9","theme-10","theme-hover","theme-heading","theme-drop-content","theme-container","theme-banner-text");
if ((isset($_COOKIE["Theme"])) && in_array($_COOKIE["Theme"], array("Blue","Red","Grey","Ochre","Mauve"))) echo $classList."-".strtolower($_COOKIE["Theme"]);
?>
<!DOCTYPE html>
... etc
I am defining an array of css classes, then reading the user colour from the cookie and appending it to the css class.
As and example, the default class might be 'theme-3' but of the user selects the blue skin, then this class becomes 'theme-3-blue' and so on.
But it's not working.
Any help would be appreciated.
Don't mess with the element class lists. Use CSS files to apply the colours you want.
Start with a basic CSS design file:
p {
margin-left:10px
font-size: 12pt;
}
h1 {
font-size: 24pt;
}
div {
margin: 10px;
padding 20px;
}
Then create CSS colour files with different colour selections:
blue.css
p {
color:blue;
}
h1 {
color: darkblue;
background-color: lightblue;
}
red.css
p {
color:red;
}
h1 {
color: maroon;
background-color: pink;
}
default.css
p {
color:black;
}
h1 {
color:white;
background-color:black;
}
Then load the colour theme you want
<?php
if (isset($_COOKIE['theme'] && in_array($_COOKIE['theme'], ['red','blue'])) {
$themeCSS = '<link rel="stylesheet" href="'.$_COOKIE['theme'].'.css">';
} else {
$themeCSS = '<link rel="stylesheet" href="default.css">';
}
Then echo $themeCSS in your <head> just like any other <head> element
** I've used standard HTML elements here to illustrate, but any CSS selectors should work.
I believe you want to change the class names inside the $classList variable by appending the selected color theme from the cookies.
You may use the array_map function to modify all elements of your $classList array.
$classList = array("theme-1","theme-2","theme-3","theme-4","theme-5","theme-6","theme-7","theme-8","theme-9","theme-10","theme-hover","theme-heading","theme-drop-content","theme-container","theme-banner-text");
$themeColor = $_COOKIE["Theme"]; // blue
$classList = array_map(function($val) use ($themeColor) { return $val.'-'.$themeColor; }, $classList);
Once you use the array_map function, all elements of the $classList array will be appended with the "-blue".
You can execute and see the output here
http://sandbox.onlinephpfunctions.com/code/6051282e00be1eb7bb7e6a086de20bbcfe9bcc9f
Several good ways to do it. It's a little more complicated with the array of classes but you should be able to adjust this if you need it (not sure why the syntax highlighting is wonky).
Use output buffering and replace at the end:
<?php
ob_start();
?>
<html>
<head></head>
<body>
<div class="theme-1"></div>
</body>
</html>
<?php
$themes = array("Blue","Red","Grey","Ochre","Mauve");
if ((isset($_COOKIE["Theme"])) && in_array($_COOKIE["Theme"], $themes)) {
echo preg_replace('/class="(theme-[^"]+)"/', 'class="$1-' . $_COOKIE['Theme'] . '"', ob_get_clean());
}
With the array of classes, just do it the same way with output buffering but replace like so:
$replace = array_map(function($v) { return "{$v}-{$_COOKIE['Theme']}"; }, $classList);
echo str_replace($classList, $replace, ob_get_clean());

HTML expand div horizontally to fit children

I'm creating a horizontally scrolling web site. There's a container div which I want to retain a fixed height but expand as required horizontally to fit the content inside it. At the moment the div only expands horizontally as far as the page width. There are actually 9 images to display but only the first 4 are shown. See code and image below. How do I make the container div expand horizontally to show all images please?
css:
body
{
background-color:#dbdbdb;
}
div.infinite-container
{
background-color:#db0080;
height:180px;
}
img.infinite-item
{
width="320";
height="180";
margin-right:8px;
margin-bottom:8px;
display:inline-block;
}
.infinite-more-link
{
visibility:hidden;
}
PHP:
<div class="infinite-container">');
if ($num_results > 0)
{
$array = array();
while ($row = mysql_fetch_assoc($result))
{
$array[] = $row;
}
for ($i = 0; $i < $numImagesPerPage; $i++)
{
$filePath = "animations/".$array[$i]['animationid'].".gif";
echo('<img class="infinite-item" src="'.$filePath.'"/>');
}
}
echo('</div>');
This screenshot is after the changes below suggested by Andrei. The pink area is the container div. The images appear to break out below it.
From the code you posted, doing something like this should work:
body
{
background-color:#dbdbdb;
overflow:auto;
}
div.infinite-container
{
background-color:#db0080;
height:180px;
display:inline-block;
white-space: nowrap;
}
img.infinite-item
{
width: 320px;
height: 180px;
margin-right:8px;
margin-bottom:8px;
display:inline-block;
}
jsFiddle example:
http://jsfiddle.net/S6Abd/
What this does is:
set the display mode to inline-block on the container. This way the container will be as large as needed to contain all items.
set overflow:auto on body to show scroll-bars.
correct the width and height of each item.
add white-space: nowrap; to the container to force the items to stay on one line.
Add this CSS style :)
div.infinite-container
{
width:2952px; /* (320 + 8) * 9 = 2952 */
}
But on the serious note - DIV shows (kind of) all your images, only images 5-9 are in next line and because container have fixed height, then they are hidden.

PHP/CSS how to keep my checkboxs from going past my border

Basically I am createing a unknown size of checkboxs that is dependent on the row that is chosen from a table in my database. The reason I dont know the size is that the user chooses which row they will use with some rows containing what will become 10 checkboxs adn others containing as many as 75. So the problem is that if the user selects a row with a large amount of options it goes through the border of my div and then forces me to scroll the page down what I am looking for is a way to say >
if(number of checkboxs is >25 )
create a new column on my page
I dont know whether the right way to go about this is to use php or javascript or possibly do it using css I am new to all of these languages so any help no matter how trivial will greatly appreciated.
<div id="major1">
<?php
$courses=mysql_query("SELECT * FROM MAJORS_CHECKLIST WHERE MAJOR='$major'");
$courses_row=mysql_fetch_row($courses);
$count = 0;
echo "$courses_row[0] <br/>";
$checkit = 0;
$sidebyside = 0;
foreach($courses_row as $i=>$courses_row){
if($courses_row['$count'] == NULL)
{
break;//if we run out of courses stop printing them
}
if($courses_row[$count] == $courses_row[0] && $checkit == 0 )
{
$checkit = $checkit + 1;
}
else
{
echo "<input type='checkbox' value='$courses_row' name='majorCourses[]' /> ";//answer-$i
echo "$courses_row<br /> ";
}
$count = $count + 1;
/*$sidebyside++;
if($sidebyside == 2)//tried using this to put 2 checkboxes side by side that ened up just messing everything up
{
echo "<br/>";
$sidebyside = 0;
}*/
}
?>
here is my css:
#major1{
color: white;
/*border: 1px solid black;*/
padding: 5px;
float: left;
height:500px;
width:150px;
}
Producing a bunch of checkboxes in the div can be controlled using CSS. Should set the parent div of the checkboxes to the following rules: width:auto; height:auto; padding:10px 10px; position:relative; This is all assuming that the parent div of the checkboxes is a child of another div to control the preferred dimensions
edit: if you do not want to want to use css with the methods above, you can control the "X" amount of checkboxes per row. You can create a counter to count how many are being displayed and do a if($counter % X == 0) echo "</div><div>"; This is all assuming you have a starting div at the beginning of your code and an ending div at the end of the code.

Create a dynamic table-like grid without using tables

I am wondering if it's possible to create a grid-like layout using div's that are dynamically created using PHP.
I am creating a product page that will display all products in a PHP database. I want each product to be housed in a div, and 3 divs to display in a row with as many rows as needed to get through all the products.
Something like this:
div div div
$row['product1'] $row['product2'] $row['product3']
div div div
$row['product4'] $row['product5'] $row['product6']
I would prefer not to use a table. I know how to line divs up using the float and clear properties, but not if they are all being created in a while statement, which makes me think it might not be possible.
So I guess, is this possible without using tables, or should I just stick with that?
This can be done the way you ask, though it isn't the best way. It's entirely possible to identify the <div> positions within columns in a while loop:
// Looping over your results simplified...
$i = 1;
while ($results) {
if ($i % 3 == 1) {
$div_class = 'left';
}
else if ($i % 3 == 2) {
$div_class = 'middle';
}
else {
$div_class = 'right';
}
$i++;
// output, simplified
echo "<div class='$div_class'>$row_contents</div>";
}
Then use your CSS to float and clear as necessary for the left, middle, right classes.
.left, .middle, .right {
float: left;
}
.left { clear: left; }
.right { clear: right; }
However,
Given all of this, I still probably wouldn't bother with <div>s. Semantically if this is a list of products, you should be listing them in <li> tags. Then just style the <li> to float: left; and make each one 33% the width of the container so you get 3 per line.

display data in grid using php

I am trying to display the retrieved data in grid.
I used while loop and retrieved every thing.I applied css but now all rows are getting displayed in same color.
I am trying to do like this row0 blue color row1 green color row2 blue color row3 green color.How do i do it?
Use something like this (of course, adapt it to your loop) :
echo '<table>';
$i = 0;
foreach($myrows as $row) {
echo '<tr class="row'.(++$i % 2).'"><td>';
echo $row;
echo '</td></tr>';
}
echo '</table>';
With the following CSS code :
tr.row0 > td { background-color: blue; }
tr.row1 > td { background-color: green; }
Few methods if happy using CSS3 look at nth-child
Or place a counter inside your while statement and use mod function to apply a class
e.g.
while(...){
if($count%2)
{
\\add class
}
$count++;
}
You can do it in CSS3 (see http://www.w3.org/Style/Examples/007/evenodd)
In PHP, you can apply a "odd" class using a modulo:
<?php for ($i = 0; $i < 10; $i++) {
$class = ($i%2 != 0) ? ' class="odd"' : '';
echo '<tr'.$class.'>...</tr>';
}
You can also use a free tool like SDTable.com and it will do the job for you. You just go in into template css file and change row-1 and row-2 background colors or create a rule which specify the background color dynamicly based on the native data in your database.

Categories