If you load XML links into https://www.convertcsv.com/xml-to-csv.htm (by using Enter URL), you immediately get a nice table:
How can you do it directly in PHP without knowing the XML's structure in advance?
Sample code and URL:
<?php
url = 'https://uxdb.s3.amazonaws.com';
$input = new SimpleXMLElement($url, 0, TRUE);
echo '<pre>' . print_r($input, true) . '<pre>';
?>
Which gives you:
Here's how I ended up doing it - https://paiza.io/projects/-ouYa8tFfqcH8QeaVeQfIw (this fiddle tester has a limit on output, so I used 5 instead of count($array) there):
<?php
$url = 'https://uxdb.s3.amazonaws.com';
$input = new SimpleXMLElement($url, 0, TRUE);
$json = json_encode($input);
$array = json_decode($json,TRUE)['Contents'];
header('Content-Type: text/html; charset=utf-8');
?>
<head>
<style>
table2 {
border-spacing: 0;
width: 100%;
border: 1px solid #ddd;
}
th {cursor: pointer;}
th, td {
text-align: left;
padding: 16px;
}
tr:nth-child(even) {
background-color: #f2f2f2
}
</style>
</head>
<body>
<table id="sortable">
<?php
for ($i=0; $i<count($array); $i++) {
if ($i==0)
echo "<thead>\n";
echo "<tr>\n";
foreach ($array[$i] as $key => $value)
echo ($i==0 ? "<th>$key ↕</th>" : "<td>" . ($key == 'Key' ? "$value" : $value) . "</td>") . "\n";
echo "</tr>\n";
if ($i==0)
echo "</thead>\n<tbody>\n";
}
?>
</tbody>
</table>
<script>document.addEventListener('DOMContentLoaded', function() {
const table = document.getElementById('sortable');
const headers = table.querySelectorAll('th');
const tableBody = table.querySelector('tbody');
const rows = tableBody.querySelectorAll('tr');
// Track sort directions
const directions = Array.from(headers).map(function(header) {
return '';
});
// Transform the content of given cell in given column
const transform = function(index, content) {
// Get the data type of column
const type = headers[index].getAttribute('data-type');
switch (type) {
case 'number':
return parseFloat(content);
case 'string':
default:
return content;
}
};
const sortColumn = function(index) {
// Get the current direction
const direction = directions[index] || 'asc';
// A factor based on the direction
const multiplier = (direction === 'asc') ? 1 : -1;
const newRows = Array.from(rows);
newRows.sort(function(rowA, rowB) {
const cellA = rowA.querySelectorAll('td')[index].innerHTML;
const cellB = rowB.querySelectorAll('td')[index].innerHTML;
const a = transform(index, cellA);
const b = transform(index, cellB);
switch (true) {
case a > b: return 1 * multiplier;
case a < b: return -1 * multiplier;
case a === b: return 0;
}
});
// Remove old rows
[].forEach.call(rows, function(row) {
tableBody.removeChild(row);
});
// Reverse the direction
directions[index] = direction === 'asc' ? 'desc' : 'asc';
// Append new row
newRows.forEach(function(newRow) {
tableBody.appendChild(newRow);
});
};
[].forEach.call(headers, function(header, index) {
header.addEventListener('click', function() {
sortColumn(index);
});
});
});</script>
Related
I have a big problem. I have a mysql database which contains 12 character length fields. I would like to display somehow.
Sample data from the field:
233215334523
I would like to display 0 and 1 with red background 2 3 with yellow background and 4 5 with green background.
Important! I know str_split could split the string into characters, or I could use $string[1] $string[2] etc. also, but not now, because this cms use the lex parser ( you couldn't use php variables here!).
So I need some great idea how could I split virtual this 12 character length variable. The best should be some which display these numbers with the background colors what I wrote earlier.
I hope someone could help for me, because I have no idea. Many thanks!
Wrap each character in a span, with a classname:
HTML:
<div id="fieldToSplit">233215334523</div>
javascript:
var element = document.getElementById("fieldToSplit")
var data = element.innerHTML.split("");
var wrappedString = "";
for (var i = 0; i < data.length; i++) {
wrappedString += "<span class='shade" + data[i] + "'>" + data[i] + "</span>";
}
element.innerHTML = wrappedString;
CSS:
.shade0, .shade1 {
background-color: #FF0000;
}
.shade2, .shade3 {
background-color: #FFFF00;
}
.shade4, .shade5 {
background-color: #00FF00;
}
This solution allows you to freely style each digit independently, say you wanted a darker green for 5 than for 4. And if later you need styles for 6,7,8, and 9, all you need to do is add classes .shade6, .shade7, .shade8, and .shade9.
Fiddle here:
http://jsfiddle.net/rwbm9ttn/1/
Something like this?
$(document).ready(function() {
var letters = $('.source').html().split(/\s?/)
for (var i = 0; i <= letters.length; ++i) {
$('<span class="lt' + letters[i] + '">').html(letters[i]).appendTo(".letters");
}
});
.lt2 {
background: yellow;
}
.lt3 {
background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div class="source">233215334523</div>
<div class="letters"></div>
Here is a pure jquery & CSS solution:
http://jsfiddle.net/k91ax5g9/1/
HTML
<div class='num'>101234567</div>
<div class='num'>1011223444</div>
<div class='num'>124413223</div>
<div class='num'>323123133</div>
JS
$(".num").each(function(){
var $el = $(this);
var t =$el.html();
$el.html('');
for(var c in t){
var char = t[c];
$el.append($("<span>", {'text_val': char}).html(char));
}
});
CSS
[text_val="0"], [text_val="1"]{
background: red;
}
[text_val="2"], [text_val="3"]{
background: orange;
}
[text_val="4"], [text_val="5"]{
background: green;
}
An entirely jQuery version would be like this -
$(document).ready(function(){
var data = 233215334523;
var str = data.toString();
var hold = '';
for(var i = 0; i<str.length; i++)
{
if(str[i] == 0 || str[i] == 1)
{
hold = hold + '<span style="background-color: red;">'+str[i]+'</span>';
$('.print').html(hold);
}
else if(str[i] == 2 || str[i] == 3)
{
hold = hold + '<span style="background-color: yellow;">'+str[i]+'</span>';
$('.print').html(hold);
}
else if(str[i] == 4 || str[i] == 5)
{
hold = hold + '<span style="background-color: green;">'+str[i]+'</span>';
$('.print').html(hold);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="print"></p>
What about generate tree with selected values? What i do is storing the selected keys, and then on edit, i generate the tree with the help of an extra json array with the selected keys. But the problem is if i change the order of the images via mysql, the keys does not stand for the real values.
This is how i create the json array for a tree, with depth = 1.
/*** get image tree structure ***/
$i = 0; $j = 0;//$j = 0; $l = 0;
$counter = 0;
$whole_tree = $this->cms_model->get_tree_big_array('0');
foreach ($whole_tree as $node_key => $node_array) {
foreach ($node_array as $key_name => $node_element_value) {
if($key_name == 'title'):
$new_array[$i][$key_name] = $node_element_value;
elseif($key_name == 'filename'):
$new_array[$i][$key_name] = $node_element_value;
elseif($key_name == 'id'):
$new_array[$i][$key_name] = $node_element_value;
elseif($key_name == 'is_folder'):
$new_key_name = 'isFolder';
if($node_element_value == '1'):
$new_node_element_value = 'true';
$new_array[$i][$new_key_name] = $new_node_element_value;
$cur_id = $node_array['id'];
$children = $this->cms_model->get_children_array($cur_id);
foreach ($children as $child_key_name => $child_element_value) {
foreach ($child_element_value as $super_child_key_name => $childnode_element_value) {
if($super_child_key_name == 'title'):
$new_array[$i]['children'][$child_key_name][$super_child_key_name] = $childnode_element_value;
elseif($super_child_key_name == 'filename'):
$new_array[$i]['children'][$child_key_name][$super_child_key_name] = $childnode_element_value;
elseif($super_child_key_name == 'id'):
$new_array[$i]['children'][$child_key_name][$super_child_key_name] = $childnode_element_value;
endif;
}
$counter++;
}
else:
$new_node_element_value = 'false';
endif;
$cur_id = $node_array['id'];
$children = $this->cms_model->get_children_array($cur_id);
endif;
$j++;
}
$i++;
}
//print_r($new_array);
$json_tree = json_encode($new_array);
$data['json'] = $json_tree;
Above is the dynatree script, where i pick some photos for a page and make previews for what is selected and what is activated. In this case i have photos.
jQuery(function(){
jQuery("#tree").dynatree({
checkbox: true,
onPostInit: function(isReloading, isError){
var data = <?php echo $json;?>; // the whole json array tree object
var array = <?php echo $key_array;?>; // these the stored keys where selected from last post.
var imgarray = <?php echo $img_array;?>; // these are the selected images id's
for(i=0; i<array.length; i++){
var tree = jQuery("#tree").dynatree("getTree");
tree.getNodeByKey(array[i]).select(); // i'm selecting on load the selected nodes using this function.
// what i want is to select the nodes using the $img_array array in order to have
// an independence in what order the nodes are generated
}
},
onActivate: function(node) {
var site_url = '<?php echo site_url(); ?>';
var controller_path = '/admin/actions/get_image_path/';
var image_id = node.data.id;
jQuery.ajax({
url: site_url+controller_path+image_id,
type: 'GET',
datatype: 'html',
processData: false,
success: function(msg){
jQuery('.image-previewer').css({display: 'block'});
jQuery('.image-previewer').html(msg);
}
});
},
onSelect: function(flag, node) {
//alert(node.data.id);
if(flag){
jQuery('<div id="'+node.data.id+'">').css({
display: 'block',
borderRadius: '3px',
margin: '0 0 10px 0',
})
.appendTo('.list');
jQuery('<span id="'+node.data.id+'" style="padding:0px 5px; line-height:40px; margin-right:5px; float:left; background:#fffccc;">Εχεις επιλέξει: '+node.data.filename+' </span>').appendTo('div#'+node.data.id+'');
jQuery('<img id="img_'+node.data.id+'" src="http://pinecone.gr/files/thumbs/'+node.data.filename+'" style="float:left; margin-right:5px">').appendTo('div#'+node.data.id+'');
jQuery('<span>').css({
lineHeight: '40px',
display: 'block',
float: 'left',
id: 'span_'+node.data.id
})
jQuery('<input>',
{
type: 'hidden',
name: 'img_array[]',
id : 'input_'+node.data.id,
value: 'img_'+node.data.id
}).appendTo('div#'+node.data.id+'');
jQuery('<input>',
{
type: 'hidden',
name: 'keys_array[]',
id : 'inputkeys_'+node.data.id,
value: node.data.key
}).appendTo('div#'+node.data.id+'');
jQuery('<br clear="all" />').appendTo('div#'+node.data.id+'');
jQuery('input#input_'+node.data.id+'').attr({ value: node.data.id})
}else if(!flag){
jQuery('.list div#'+node.data.id+'').remove();
}
},
persist: false,
children:
<?php echo $json; ?>
});
});
If i change the order of the images records in database, or by adding an image, the selected keys for the current record does not stand for real, because the structure is changed, and i have data integrity failure. What do you suggest for solution.
Thanks in Advance
Hi this question relates to a recent question I had posted that I'm trying to find at least some help with in general that leads to solve the entire problem.
The following code is not mine and I had to fix it just to get it working to the extent it is now but the problem the algorithm within _get_chat_messages continues to execute the else condition. This doesn't make sense because there's chat message data in Mysql. I'm trying to make this source code work hoping it will lead me in the right direction with refreshing chat message content automatically without forcing browser client refreshes or redirecting headers.
What's causing _get_chat_messages to execute the else condition disregarding the if condition. The if conditions seems to evaluate to TRUE which doesn't make sense.
Any help much appreciated. Thanks.
//JQUERY/AJAX:
$(document).ready(function() {
setInterval(function() { get_chat_messages(); } , 2500);
$("input#chat_message").keypress(function(e) {
if (e.which == 13) {
$("a#submit_message").click();
return false;
}
});
$("#submit_message").click(function() {
var chat_message_content = $("input#chat_message").val();
//this if condition seems to be ignored not sure why?
if (chat_message_content == "") { return false; }
$.post(base_url + "chat/ajax_add_chat_message", { chat_message_content : chat_message_content, chat_id : chat_id, user_id : user_id }, function(data) {
if (data.status == 'ok')
{
var current_content = $("div#chat_viewport").html();
$("div#chat_viewport").html(current_content + data.message_content);
}
else
{
// there was an error do something
}
}, "json");
$("input#chat_message").val("");
return false;
});
function get_chat_messages()
{
$.post(base_url + "chat/ajax_get_chat_messages", { chat_id : chat_id }, function(data) {
if (data.status == 'ok')
{
var current_content = $("div#chat_viewport").html();
$("div#chat_viewport").html(current_content + data.message_content);
}
else
{
// there was an error do something
}
}, "json");
}
get_chat_messages();
});
//CONTROLLER:
class Chat extends CI_Controller {
public function __construct()
{
parent:: __construct();
$this->load->model('chat_model');
}
public function index()
{
/* send in chat id and user id */
$this->view_data['chat_id'] = 1;
// check they are logged in
if (! $this->session->userdata('logged_in')) {
redirect('user/login');
}
$this->view_data['user_id'] = $this->session->userdata('user_id');
$this->session->set_userdata('last_chat_message_id_' . $this->view_data['chat_id'], 0);
$this->view_data['page_title'] = 'web based chat app :)';
$this->view_data['page_content'] = 'view_chat';
$this->load->view('view_main', $this->view_data);
}
public function ajax_add_chat_message()
{
/* Scalar Variable data that needs to be POST'ed to this function
*
* chat_id
* user_id
* chat_message_content
* *
*/
$chat_id = $this->input->post('chat_id');
$user_id = $this->input->post('user_id');
$chat_message_content = $this->input->post('chat_message', TRUE);
$this->chat_model->add_chat_message($chat_id, $user_id, $chat_message_content);
// grab and return all messages
$this->ajax_get_chat_messages($chat_id);
}
public function ajax_get_chat_messages($chat_id)
{
$chat_id = $this->input->post('chat_id');
echo $this->_get_chat_messages($chat_id);
}
private function _get_chat_messages($chat_id)
{
$last_chat_message_id = (int)$this->session->userdata('last_chat_message_id_' . $chat_id);
$chat_messages = $this->chat_model->get_chat_messages($chat_id, $last_chat_message_id);
if ($chat_messages->num_rows() > 0)
{
// store the last chat message id
$last_chat_message_id = $chat_messages->row($chat_messages->num_rows() - 1)->chat_message_id;
$this->session->set_userdata('last_chat_message_id_' . $chat_id, $last_chat_message_id);
// we have some chat let's return it
$chat_messages_html = '<ul>';
foreach ($chat_messages->result() as $chat_message)
{
$li_class = ($this->session->userdata('user_id') == $chat_message->user_id) ? 'class="by_current_user"' : '';
$chat_messages_html .= '<li ' . $li_class . '>' . '<span class="chat_message_header">' . $chat_message->chat_message_timestamp . ' by ' . $chat_message->name . '</span><p class="message_content">' . $chat_message->chat_message_content . '</p></li>';
}
$chat_messages_html .= '</ul>';
$result = array('status' => 'ok', 'content' => $chat_messages_html);
//header('Content-Type: application/json',true);
return json_encode($result);
exit();
}
else
{
// we have no chat yet
$result = array('status' => 'no chat', 'content' => '');
//header('Content-Type: application/json',true);
return json_encode($result);
exit();
}
}
}
//MODEL:
class chat_model extends CI_Model {
public function __construct()
{
parent::__construct();
}
public function add_chat_message($chat_id, $user_id, $chat_message_content)
{
$query_str = "INSERT INTO chat_messages (chat_id, user_id, chat_message_content) VALUES (?, ?, ?)";
$this->db->query($query_str, array($chat_id, $user_id, $chat_message_content));
}
public function get_chat_messages($chat_id, $last_chat_message_id = 0)
{
$query_str = "SELECT
cm.chat_message_id,
cm.user_id,
cm.chat_message_content,
DATE_FORMAT(cm.create_date, '%D of %M %Y at %H:%i:%s') AS chat_message_timestamp,
u.name
FROM chat_messages cm
JOIN users u ON cm.user_id = u.user_id
WHERE cm.chat_id = ?
and cm.chat_message_id > ?
ORDER BY cm.chat_message_id ASC";
$result = $this->db->query($query_str, array($chat_id, $last_chat_message_id));
return $result;
}
}
//VIEW FILE HENCE VIEW_CHAT.PHP
<html>
<head>
<script type="text/javascript" src="/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="<?php echo base_url() . 'public/';?>chat.js">
</script>
<script type="text/javascript">
var base_url = "<?php echo base_url();?>";
var chat_id = "<?php echo $chat_id; ?>";
var user_id = "<?php echo $user_id; ?>";
</script>
</head>
<body>
<style type="text/css">
div#chat_viewport {
font-family:Verdana, Arial, sans-serif;
padding:5px;
border-top:2px dashed #585858;
min-height:300px;
color:black;
max-height:650px;
overflow:auto;
margin-bottom:10px;
width:750px;
}
div#chat_viewport ul {
list-style-type:none;
padding-left:10px;
}
div#chat_viewport ul li {
margin-top:10px;
width:85%;
}
span.chat_message_header {
font-size:0.7em;
font-family:"MS Trebuchet", Arial, sans-serif;
color:#547980;
}
p.message_content {
margin-top:0px;
margin-bottom:5px;
padding-left:10px;
margin-right:0px;
}
input#chat_message {
margin-top:5px;
border:1px solid #585858;
width:70%;
font-size:1.2em;
margin-right:10px;
}
input#submit_message {
font-size:2em;
padding:5px 10px;
vertical-align:top;
margin-top:5px;
}
div#chat_input { margin-bottom:10px; }
div#chat_viewport ul li.by_current_user span.chat_message_header {
color:#e9561b;
}
</style>
<h1>Let's do some chatting :D</h1>
<div id="chat_viewport">
</div>
<div id="chat_input">
<?php echo form_open('chat/ajax_add_chat_message'); ?>
<input id="chat_message" name="chat_message" type="text" value="" tabindex="1" />
<?php echo form_submit('submit_message','submit_message'); ?>
<?php echo anchor('#', 'Say it', array('title' => 'Send this chat message', 'id' => 'submit_message'));?>
<div class="clearer"></div>
<?php echo form_close(); ?>
</div>
</body>
</html>
I am not sure but I have a feeling that the json that you receive from the server is not formatted properly. See this: jQuery won't parse my JSON from AJAX query
I'm trying to assign three different colours to three different articles on a single page using a:hover in Wordpress.
This is the site http://paragrams.wpshower.com/
At present all the articles turn pale yellow on a:hover. I'm trying to create different colours for each article (for example, first article to be yellow, the second article red, third blue and so on).
Below is the php & CSS for the a:hover at present. I assume I need to wrap each thumb id in a different div and specify the colour in the CSS?
PHP:
<ul class="mcol">
<?php if(have_posts()) : ?><?php while(have_posts()) : the_post(); ?>
<li class="article">
<?php
if ( has_post_thumbnail() ) { ?>
<?php
$imgsrcparam = array(
'alt' => trim(strip_tags( $post- >post_excerpt )),
'title' => trim(strip_tags( $post- >post_title )),
);
$thumbID = get_the_post_thumbnail( $post->ID, 'background', $imgsrcparam ); ?>
<div><?php echo "$thumbID"; ?></div>
<?php } ?>
<h2><?php the_title(); ?></h2>
and CSS:
.li_container {
background-attachment: scroll;
background-image: url(images/main-bg.gif);
background-repeat: repeat-y;
background-position: left top;
}
.li_container .article:hover {
background-color:#57bfeb;
}
This is the js:
# * Splits a <ul>/<ol>-list into equal-sized columns.
# *
# * Requirements:
# * <ul>
# * <li>"ul" or "ol" element must be styled with margin</li>
# * </ul>
# *
# * #see http://www.codeasily.com/jquery/multi-column-list-with-jquery
# */
jQuery.fn.makeacolumnlists = function(settings){
settings = jQuery.extend({
cols: 3, // set number of columns
colWidth: 0, // set width for each column or leave 0 for auto width
equalHeight: 'li', // can be false, 'ul', 'ol', 'li'
startN: 1 // first number on your ordered list
}, settings);
if(jQuery('> li', this)) {
this.each(function(y) {
var y=jQuery('.li_container').size(),
height = 0,
maxHeight = 0,
t = jQuery(this),
classN = t.attr('class'),
listsize = jQuery('> li', this).size(),
percol = Math.ceil(listsize/settings.cols),
contW = t.width(),
bl = ( isNaN(parseInt(t.css('borderLeftWidth'),10)) ? 0 : parseInt(t.css('borderLeftWidth'),10) ),
br = ( isNaN(parseInt(t.css('borderRightWidth'),10)) ? 0 : parseInt(t.css('borderRightWidth'),10) ),
pl = parseInt(t.css('paddingLeft'),10),
pr = parseInt(t.css('paddingRight'),10),
ml = parseInt(t.css('marginLeft'),10),
mr = parseInt(t.css('marginRight'),10),
col_Width = Math.floor((contW - (settings.cols-1)*(bl+br+pl+pr+ml+mr))/settings.cols);
if (settings.colWidth) {
col_Width = settings.colWidth;
}
var colnum=1,
percol2=percol;
jQuery(this).addClass('li_cont1').wrap('<div id="li_container' + (++y) + '" class="li_container"></div>');
for (var i=0; i<=listsize; i++) {
if (colnum > settings.cols) colnum = 1;
var eq = jQuery('> li:eq('+i+')',this);
eq.addClass('li_col'+colnum);
colnum++;
//if(i>=percol2) { percol2+=percol; colnum++; }
//var eq = jQuery('> li:eq('+i+')',this);
//eq.addClass('li_col'+ colnum);
//if(jQuery(this).is('ol')){eq.attr('value', ''+(i+settings.startN))+'';}
}
jQuery(this).css({cssFloat:'left', width:''+col_Width+'px'});
for (colnum=2; colnum<=settings.cols; colnum++) {
if(jQuery(this).is('ol')) {
jQuery('li.li_col'+ colnum, this).appendTo('#li_container' + y).wrapAll('<ol class="li_cont'+colnum +' ' + classN + '" style="float:left; width: '+col_Width+'px;"></ol>');
} else {
jQuery('li.li_col'+ colnum, this).appendTo('#li_container' + y).wrapAll('<ul class="li_cont'+colnum +' ' + classN + '" style="float:left; width: '+col_Width+'px;"></ul>');
}
}
if (settings.equalHeight=='li') {
for (colnum=1; colnum<=settings.cols; colnum++) {
jQuery('#li_container'+ y +' li').each(function() {
var e = jQuery(this);
var border_top = ( isNaN(parseInt(e.css('borderTopWidth'),10)) ? 0 : parseInt(e.css('borderTopWidth'),10) );
var border_bottom = ( isNaN(parseInt(e.css('borderBottomWidth'),10)) ? 0 : parseInt(e.css('borderBottomWidth'),10) );
height = e.height() + parseInt(e.css('paddingTop'), 10) + parseInt(e.css('paddingBottom'), 10) + border_top + border_bottom;
maxHeight = (height > maxHeight) ? height : maxHeight;
});
}
for (colnum=1; colnum<=settings.cols; colnum++) {
var eh = jQuery('#li_container'+ y +' li');
var border_top = ( isNaN(parseInt(eh.css('borderTopWidth'),10)) ? 0 : parseInt(eh.css('borderTopWidth'),10) );
var border_bottom = ( isNaN(parseInt(eh.css('borderBottomWidth'),10)) ? 0 : parseInt(eh.css('borderBottomWidth'),10) );
mh = maxHeight - (parseInt(eh.css('paddingTop'), 10) + parseInt(eh.css('paddingBottom'), 10) + border_top + border_bottom );
eh.height(mh);
}
} else
if (settings.equalHeight=='ul' || settings.equalHeight=='ol') {
for (colnum=1; colnum<=settings.cols; colnum++) {
jQuery('#li_container'+ y +' .li_cont'+colnum).each(function() {
var e = jQuery(this);
var border_top = ( isNaN(parseInt(e.css('borderTopWidth'),10)) ? 0 : parseInt(e.css('borderTopWidth'),10) );
var border_bottom = ( isNaN(parseInt(e.css('borderBottomWidth'),10)) ? 0 : parseInt(e.css('borderBottomWidth'),10) );
height = e.height() + parseInt(e.css('paddingTop'), 10) + parseInt(e.css('paddingBottom'), 10) + border_top + border_bottom;
maxHeight = (height > maxHeight) ? height : maxHeight;
});
}
for (colnum=1; colnum<=settings.cols; colnum++) {
var eh = jQuery('#li_container'+ y +' .li_cont'+colnum);
var border_top = ( isNaN(parseInt(eh.css('borderTopWidth'),10)) ? 0 : parseInt(eh.css('borderTopWidth'),10) );
var border_bottom = ( isNaN(parseInt(eh.css('borderBottomWidth'),10)) ? 0 : parseInt(eh.css('borderBottomWidth'),10) );
mh = maxHeight - (parseInt(eh.css('paddingTop'), 10) + parseInt(eh.css('paddingBottom'), 10) + border_top + border_bottom );
/*eh.height(mh);*/
}
}
jQuery('#li_container' + y).append('<div style="clear:both; overflow:hidden; height:0px;"></div>');
});
}
}
jQuery.fn.uncolumnlists = function(){
jQuery('.li_cont1').each(function(i) {
var onecolSize = jQuery('#li_container' + (++i) + ' .li_cont1 > li').size();
if(jQuery('#li_container' + i + ' .li_cont1').is('ul')) {
jQuery('#li_container' + i + ' > ul > li').appendTo('#li_container' + i + ' ul:first');
for (var j=1; j<=onecolSize; j++) {
jQuery('#li_container' + i + ' ul:first li').removeAttr('class').removeAttr('style');
}
jQuery('#li_container' + i + ' ul:first').removeAttr('style').removeClass('li_cont1').insertBefore('#li_container' + i);
} else {
jQuery('#li_container' + i + ' > ol > li').appendTo('#li_container' + i + ' ol:first');
for (var j=1; j<=onecolSize; j++) {
jQuery('#li_container' + i + ' ol:first li').removeAttr('class').removeAttr('style');
}
jQuery('#li_container' + i + ' ol:first').removeAttr('style').removeClass('li_cont1').insertBefore('#li_container' + i);
}
jQuery('#li_container' + i).remove();
});
}
You wouldn't need to do anything fancy with divs; just give each li tag a unique class, and specify those class colors in css.
From your code, you could change the line
<li class="article">
to
<?php
switch($post->ID) {
case 1:
$class = 'yellow'; break;
case 2:
$class = 'blue'; break;
case 3:
$class = 'green'; break;
}
?>
<li class="article <?php echo $class; ?>">
This will effectively output class='article yellow' for the first article, class='article blue' for the second, etc. You can then make this all work by changing the css as follows:
.li_container .article.yellow:hover { background-color:#57bfeb; }
.li_container .article.green:hover { background-color:green; }
.li_container .article.blue:hover { background-color:blue; }
If you want to get fancy, you could also change switch($post->ID) to switch(mod($post->ID,3)) to do lots of color changing.
eykanal has a good solution. Just to throw out another option, you could use jquery and just dynamically add the classes based on the article positions in the dom. Something like:
Add this inside the head element of your page:
<script type="text/javascript"src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('.mcol li.article:nth-child(1)').addClass('yellow')
$('.mcol li.article:nth-child(2)').addClass('red')
$('.mcol li.article:nth-child(3)').addClass('blue')
});
</script>
You would then add something like this to your css file:
.yellow:hover { background-color: yellow; }
.red:hover { background-color: red; }
.blue:hover { background-color: blue; }
Change the colors to the hex codes of your choice of course.
Have Fun!
What i'd personally do is add an incrementing class using PHP, like so..
<ul class="mcol">
<?php if(have_posts()) : $i = 0; while(have_posts()) : the_post(); $i++; ?>
<li class="article <?php echo "item-$i";?>">
You then get something like..
<li class="article item-1">content</li>
<li class="article item-2">content</li>
<li class="article item-3">content</li>
Then toggle a class on hover to..
$(document).ready(function(){
$('li.article').hover(function(){
$(this).toggleClass('active-item');
});
});
That then gives you one class that covers all list items, one unique to each item shown, and one that is only attached to the element on hover..
li.article { /* CSS for all list items */ }
li.article.active-item { /* CSS for all any item active */ }
li.item-1 { /* CSS for the first item */ }
li.item-2 { /* CSS for the second item */ }
li.active-item.item-1 { /* CSS for the first item when hovered */ }
li.active-item.item-2 { /* CSS for the secpnd item when hovered */ }
NOTE: It doesn't hurt to make your CSS selectors more specific, adding an ID infront of those(say, the parent list ID) will help ensure you get less conflict with other competing styles.
I hope that's helpful.. ;)
i am trying to transfer a array list from php to javascript with json, but it does not work.
JS:
$.ajax({
url: 'getProfilePhotos.php',
type: 'post', // post or get method
data: {}, // if you need to pass post/get parameterds you can encode them here in JSON format
dataType: 'json', // the data type you want returned... we will use json
success: function(responseData) {
var arrayList[0] = new Array();
var lung = arrayList.length;
for(var i = 0; i<lung; i++)
//arrayList[i] = responseData.i;
console.log(responseData.i);
}});
PHP:
<p> <?php
$array = array();
$nr = count($friends['data']);
for($i = 0; $i < $nr; $i++){
$array = 'link'=>array("http://graph.facebook.com/".$friends['data'][$i]['id']."/picture");
?>
<img src="http://graph.facebook.com/<?php echo $friends['data'][$i]['id'] ?>/picture" />
<?php
}
header('Content-type: application/json');
echo json_encode($array);
?></p>
Update for Christopher McCann
i have got a error in console. this is the error.
[02:46:21.281] missing } after property list # http://romanager.ro/api/examples/script.js:3
line 3 in script.js is
type: 'post', // post or get method
In fact i want to get from facebook profile photos. with php script i managed to get photos, but i can transfer ids from php to javascript. if you need i will try to write entire php script and javascript files.
Update
still have problems with these scripts. in php script i do and authentification of user on facebook, because i need for user ID from facebook to get ids of his friends. to make login i need to create html in php script. well i will post the code of my scripts and i hope you will help me.
PHP script:
<?php
require '../src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => '137061043024243',
'secret' => '619c4dc94343584eb7792ae9933978c9',
'cookie' => true,
));
// We may or may not have this data based on a $_GET or $_COOKIE based session.
//
// If we get a session here, it means we found a correctly signed session using
// the Application Secret only Facebook and the Application know. We dont know
// if it is still valid until we make an API call using the session. A session
// can become invalid if it has already expired (should not be getting the
// session back in this case) or if the user logged out of Facebook.
$session = $facebook->getSession();
$me = null;
// Session based API call.
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
$friends = $facebook->api('/me/friends');
} catch (FacebookApiException $e) {
error_log($e);
}
}
// login or logout url will be needed depending on current user state.
if ($me) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
// This call will always work since we are fetching public data.
$naitik = $facebook->api('/naitik');
?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>php-sdk</title>
<style>
body {
font-family: 'Lucida Grande', Verdana, Arial, sans-serif;
}
h1 a {
text-decoration: none;
color: #3b5998;
}
h1 a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<!--
We use the JS SDK to provide a richer user experience. For more info,
look here: http://github.com/facebook/connect-js
-->
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $facebook->getAppId(); ?>',
session : <?php echo json_encode($session); ?>, // don't refetch the session when PHP already has it
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// whenever the user logs in, we refresh the page
FB.Event.subscribe('auth.login', function() {
window.location.reload();
});
};
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
<?php if ($me): ?>
<a href="<?php echo $logoutUrl; ?>">
<img src="http://static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif">
</a>
<?php else: ?>
<div>
Using JavaScript & XFBML: <fb:login-button></fb:login-button>
</div>
<div>
Without using JavaScript & XFBML:
<a href="<?php echo $loginUrl; ?>">
<img src="http://static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif">
</a>
</div>
<?php endif ?>
<?php $array = array();
$nr = count($friends['data']);
echo $nr;
for($i = 0; $i < $nr; $i++) {
$array[$i] = "http://graph.facebook.com/".$friends['data'][$i]['id']."/picture";
}
header('Content-type: application/json');
echo json_encode($array);
?>
</body>
</html>
JAVASCRIPT
$.post("getProfilePhotos.php", function(data) { alert(data); console.log(data);/*DO WHAT YOU WANT WITH DATA HERE*/}, "json");
window.onload = init;
function init() {
if (window.Event) {
document.addEventListener("mousemove", getCursorXY("mousemove"), false);
var cursorXX = 0;
var cursorYY = 0;
var cursorX = document.getElementById("cursorX");
var cursorY = document.getElementById("cursorY");
cursorX.innerHTML = cursorXX;
cursorY.innerHTML = cursorYY;
}
//initializare canvas1
canvas = document.getElementById('game');
//coordonatele unde se afla mouseul
canvas.onmousemove = getCursorXY;
//initializare canvas2
canvas2 = document.getElementById('teroristi');
//coordonatele unde se afla mouseul
canvas2.onmousemove = getCursorXY;
//lista de inamici
lista = new Array();
initial();
for(var j = 0; j < 20; j++)
for(var k = 0; k < 2;k++)
console.log(matx[j][k]);// = -1000;
scor = 0;
viata = 5;
//creerea contextului de desenare 2D
ctx2 = canvas2.getContext("2d");
ctx = canvas.getContext("2d");
//creerea unui obiect imagine
img = new Image();
img.src = 'glont.png';
imgTerorist = new Image();
imgTerorist.src = 'terorist.jpg';
ctx.beginPath();
ctx.stroke();
imgviata = new Image();
imgviata.src = 'vieti.png';
//score();
viataF();
}
//initializeaza matricea de aparitii
function initial(){
matx = new Array(24);
for (var m = 0; m <24; m++)
matx[m] = new Array(3);
for(var m = 0; m < 24; m++)
matx[m][2] = 0;
matx[0][0] = 20;
matx[0][1] = 20;
for(var m = 1; m < 6; m++){
matx[m][0] = matx[m-1][0] + 80;
matx[m][1] = matx[m-1][1];
}
matx[6][0] = matx[0][0];
matx[6][1] = matx[0][1] + 120;
for(var m = 7; m < 12; m++){
matx[m][0] = matx[m-1][0] + 80;
matx[m][1] = matx[m-1][1];
}
matx[12][0] = matx[0][0];
matx[12][1] = matx[0][1] + 240;
for(var m = 13; m < 18; m++){
matx[m][0] = matx[m-1][0] + 80;
matx[m][1] = matx[m-1][1];
}
matx[18][0] = matx[0][0];
matx[18][1] = matx[0][1] + 360;
for(var m = 19; m < 24; m++){
matx[m][0] = matx[m-1][0] + 80;
matx[m][1] = matx[m-1][1];
}
}
function getCursorXY(e) {
//se ia pozitia de pe axa x al cursorului
cursorXX = (window.Event) ? e.pageX : event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
//se ia pozitia de pe axa y al cursorului
cursorYY = (window.Event) ? e.pageY : event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
//
var cursorX = document.getElementById("cursorX");
var cursorY = document.getElementById("cursorY");
cursorX.innerHTML = cursorXX;
cursorY.innerHTML = cursorYY;
}
function Nr(){
return Math.floor(Math.random()*24);
}
//stergerea inamicului
function sterge(x){
//setTimeout("genereaza(flag)",3000);
var img = ctx.createImageData(60, 100);
for (var i = img.data.length; --i >= 0; )
img.data[i] = 0;
ctx.putImageData(img, matx[x][0], matx[x][1]);
matx[x][2] = 0;
}
//genereaza inamici
function genereaza(flag){
if(flag == 1){
setTimeout("genereaza(flag)", 2000);
var x = Nr();
terorist(x);
if(lista.length > 3){
viata = viata - 1;
sterge(lista[0]);
lista.splice(0, 1);
viataF();
}
}
}
//creeaza un inamic
function terorist(x){
console.log("X primit = " + x + "valoarea flagului = " + matx[x][2]);
//sterge(x);
if(matx[x][2] == 0){
ctx.drawImage(imgTerorist,matx[x][0],matx[x][1]);
matx[x][2] = 1;
lista.push(x);
}
else if(matx[x][2] == 1){
var q = Nr();
console.log("in recursie: " + q);
terorist(q);
}
}
function viataF(){
var remove = ctx2.createImageData(20,20);
for (var i = remove.data.length; --i >= 0; )
remove.data[i] = 0;
ctx2.putImageData(remove, 10, (10+(viata*20)));
console.log(viata);
for(var m = 0; m < viata; m++)
ctx2.drawImage(imgviata,10,(10+(m*20)));
}
function impuscat(){
var shootX = cursorXX;
var shootY = cursorYY;
var tm = 0;
console.log("ShootX = " + shootX + " ShootY = " + shootY);
for(var m = 0, tm = lista.length; m < tm; m++){
if(shootX >= matx[lista[m]][0] && shootX <= matx[lista[m]][0] + 60 && shootY >= matx[lista[m]][1] && shootY <= matx[lista[m]][1] + 100){
sterge(lista[m]);
lista.splice(m, 1);
scor = scor + 10;
console.log("IMPUSCAT");
}
}
}
function glont(x, y){
ctx.beginPath();
ctx.stroke();
ctx.drawImage(img,x-40,y-40);
impuscat();
}
function mouse(){
impuscat();
/*console.log('Maus apasat');
console.log(cursorXX);
console.log(cursorYY);*/
//glont(cursorXX, cursorYY);
//console.log("Dupa glont()");
}
function start(){
viataF();
flag = 1;
genereaza(flag);
setTimeout("stop()", 10000);
}
function stop(){
ctx2.fillStyle = '#000000';
ctx2.strokeStyle = '#FFFFFF';
ctx2.font = 'bold 30px sans-serif';
ctx2.fillText ('TIMPUL A EXPIRAT!', 100, 200);
ctx2.fillText('Scorul tau este: ' + scor, 100, 235);
console.log("TIMPUL A EXPIRAT");
flag = 0;
genereaza(flag);
}
function score(){
ctx2.fillStyle = '#000000';
ctx2.strokeStyle = '#FFFFFF';
ctx2.font = 'bold 15px sans-serif';
ctx2.fillText('Scorul tau este: ', 350, 20);
}
Your PHP section is wrong as you are still trying to generate HTML, rather than just JSON.
Also the array handling within the loop is incorrect.
Try changing the PHP code to:
<?php
$friendData = array();
foreach ($friends['data'] as $cFriend) {
$friendData[$cFriend['id']] = "http://graph.facebook.com/" . $cFriend['id'] . "/picture";
}
header('Content-Type: application/json');
echo json_encode($friendData);
exit;
Header will not work in this case as you cannot output any content (including whitespace) to the browser before you call header(). In your for loop you output HTML to the browser which will cause an error.
As Orbling said you are also not correctly adding the element to the array. I am just assuming this is what you want but the loop you want is:
for($i = 0; $i < $nr; $i++) {
$array[] = "http://graph.facebook.com/".$friends['data'][$i]['id']."/picture";
}
I am confused by what you are trying to achieve with your javascript. I would use the following code instead to simplify:
$.post("getProfilePhotos.php", function(data) { alert(data); //DO WHAT YOU WANT WITH DATA HERE }, "json");
I would run that code first to check you get the JSON back and then play about with the callback function to do what you want with the returned json.