I've been trying to pass an specific Div's height and width to a PHP code, the problem is, the page is supposed to be responsive, with div height and width changing accordingly.
How can I pass these values dynamically?
<?php
/* Configuration Start */
$thumb_directory = 'img/thumbs';
$orig_directory = 'img/original';
$stage_width=600; // How big is the area the images are scattered on
$stage_height=400;
/* Configuration end */
$allowed_types=array('jpg','jpeg','gif','png');
$file_parts=array();
$ext='';
$title='';
$i=0;
/* Opening the thumbnail directory and looping through all the thumbs: */
$dir_handle = #opendir($thumb_directory) or
die("There is an error with your image directory!");
$i=1;
while ($file = readdir($dir_handle))
{
/* Skipping the system files: */
if($file=='.' || $file == '..') continue;
$file_parts = explode('.',$file);
$ext = strtolower(array_pop($file_parts));
/* Using the file name (withouth the extension) as a image title: */
$title = implode('.',$file_parts);
$title = htmlspecialchars($title);
/* If the file extension is allowed: */
if(in_array($ext,$allowed_types))
{
/* Generating random values for the position and rotation: */
$left=rand(0,$stage_width);
$top=rand(0,400);
$rot = rand(-40,40);
/* Outputting each image: */
echo '
<div id="pic-'.($i++).'" class="pic" style="top:'.$top.'px;left:'.$left.'px;background:url('.$thumb_directory.'/'.$file.') no-repeat 50% 50%; -moz-transform:rotate('.$rot.'deg); -webkit-transform:rotate('.$rot.'deg);">
<a class="fancybox" rel="fncbx" href="'.$orig_directory.'/'.$file.'" target="_blank">'.$title.'</a>
</div>';
}
}
The specific variables are $stage_width and $stage_height, those are supposed to receive the div size, but as you can see, right now, all I can do is to set a static value in them.
Is there anyway to do that? Either with JS, PHP or something else entirely?
Take a moment to learn about AJAX.
AJAX stands for Asynchronous JavaScript And XML. In a nutshell, it is the use of the XMLHttpRequest object to communicate with servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files. AJAX’s most appealing characteristic is its "asynchronous" nature, which means it can communicate with the server, exchange data, and update the page without having to refresh the page.
In this case, you would:
Compute the actual div size on the client using javascript
Send an ajax request to the server with those values
Create the div markdown with the correct values
Replace the div on the client with the markdown received from the asynchronous request.
This, however, is a bit clunky. You could be better off simply doing all that transformation on the client, using JavaScript:
Generate the markdown with PHP (like you are doing) but without the top and left styling
On client side, after the page loads (the 'DOMContentLoaded' event in JavaScript) compute the actual sizes and transform the divs accordingly.
window.addEventListenet('DOMContentLoaded', () => {
// get the div real size with getComputedStyle or something like that
// replace the div's style with correct calculations
})
Related
Right, so I've been working on a website where all income is displayed and difference in percent is calculated. This data, including the percentages are set using MySQLI and are json encoded.
On the main page I set all the values in a span, which is bound to the span ID.
EXAMPLE:
DATAQUERIES SIDE:
<?php
$data("database_data") = getdata("SELECT * FROM table_name WHERE something")
echo json_encode($data);
?>
WEBSITE SIDE
$(document).ready(function() {
var interv = setInterval(getnumber, 10000);
function getnumber(){
$.get( "data.php", function( data ) {
var d=jQuery.parseJSON(data);
$('#span_id').html(d['database_data']);
});
});
};
HTML WEBSITE SIDE
//If the code has ran through, it will provide the following. Within this
//"database data" functions as example
<span id="span_id">'database data'</span>
The value that will be added to the span is supposed to be RED when the value is below zero, blue when the value IS zero and green when the value is above zero.
The provided code above is used throughout a lot of websites and is not supposed to be altered, just fyi.
You can listen for changes on "span_id", then read in the contents of the span and set a style based on the contents:
$('span_id').bind("DOMSubtreeModified",function(){
var text = $('span_id').text();
if (text.contains("blah")) {
// I don't know your text format or how to check it
$('span_id').attr('color','red')
}
});
I am using the following JavaScript to detect the screen-width and use it as a constant across my template files through conditional statements to display / not-display portions of my site. While it has nothing much to do with my questions, but just in case... Yes I am using WordPress. Also I am already using mobiledetect PHP Library.
function getLayoutWidth() {
if (isset($_GET['width'])) {
define( "SCREEN_WIDTH", $_GET['width']);
} else {
echo "<script language='javascript'>\n";
echo " location.href=\"${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}"
. "&width=\" + screen.width;\n";
echo "</script>\n";
exit();
}
}
Important :
Other techniques are like...... Let's assume if my site is 2MB in size, it will still load 2MB of content and then hide 1.5MB of it on mobile devices by using CSS properties like display:none; Whereas I don't want that template part to load itself, thus not needing to hide anything.
I am not looking to load an entire JavaScript library like jQuery or so to do this because location.href=\"${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}". "&width=\" + screen.width; is the only JavaScript in my entire site. Rest everything is pure PHP, HTML and CSS based. I even disabled jQuery of WordPress in the front-end template.
UPDATE :
Since some friends did not get my point although I mentioned clearly that I don't want to load the content into DOM at all, I am giving a bit more clarity here.....
For Example --- #1200px I want only 1 Sidebar to be displayed. #1600px I want 2 Sidebars to be displayed and over 1600px I want 3 Sidebars to be displayed. Please don't suggest Media Queries solutions as I already know it and that is exactly what I don't want to do. I want to avoid loading the content into DOM. Kindly let focus be only and only on questions asked. Also please don't post suggestions as answers. Let others with proper answers do it. Kindly post suggestions in Comment section.
My questions :
Is this a good / correct way to do from SEO stand point? If not why?
My URL is displayed as example.com/my-product-category/my-product-name/?width=1440 How to remove /?width=1343 and display just example.com/my-product-category/my-product-name part?
Simple answer, no, it is not good from a SEO standpoint. Or any other standpoint. Crawlers such as Googles are designed to completely ignore all hidden elements and thus you will lose big time SEO ranking if your content isnt getting fully crawled, and crawlers crawl each site multiple times masquerading as mobile devices to check if the site is mobile friendly as well.
http://www.seonick.net/responsive-design-seo/
Not to mention the trouble of calculating your arbitrary cutoff point of .5mb serves no purpose if the content is merely hidden (since its all getting sent anyway thus saving no bandwidth).
You need to do this in pure CSS using media queries, it is the most compatible way and allows for a fluid design (changes on the go as the window resizes.
<link rel="stylesheet" media="(max-width: 700px)" href="mobile.css">
<link rel="stylesheet" media="(min-width: 700px)" href="full.css">
That will use one css file if the window is smaller than 700px and the other if it is over.
Another of my more favorite methods is to use the http://mobiledetect.net/ class. Its small and fast, more accurate and better flexibility. Load that class then just add classes to your body element depending on the visitors browser
<body class="<?PHP if ($detect->isMobile() && !$detect->isTablet()) echo " .phone";?>">
Then style by targeting classes inside body.phone. This method also ensures you know if the browser is mobile BEFORE the DOM starts to process, meaning you can serve compressed versions of images through some simple logic rather than having CSS swap them out or just resize them or omit entire parts of the markup from being sent to the user at all ensure bandwidth is only used for parts of the DOM relevant to the users device.
<body>
This is normal content and will be visible to all devices
<?PHP if (!$detect->isMobile()) { ?>
This content will only be visible to desktop users, in fact it wont even be transmitted to mobile users thus making it NOT in the DOM
<?PHP } ?>
</body>
To set a cookie in javascript
function Cookies(){};
Cookies.prototype.save=function(name,value,days){
if( days ) {
var date = new Date();
date.setTime( date.getTime()+( days*24*60*60*1000 ) );
var expires = "; expires="+date.toGMTString();
var dom = "; domain="+document.domain;
} else { expires = ""; }
var path = "; path=/";
var tmp=[];
if( typeof( value )=='object' ) {
for( p in value ) tmp.push( p+'='+value[ p ] );
value=tmp.join(';');
}
document.cookie = name+"="+value+expires+path;
};
Cookies.prototype.read=function(name){
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for( var i=0; i < ca.length;i++ ) {
var c = ca[i];
while( c.charAt(0)==' ') c = c.substring(1,c.length);
if( c.indexOf( nameEQ ) == 0 ) return c.substring( nameEQ.length, c.length );
}
return null;
};
Cookies.prototype.erase=function(name){
this.save( name, "", -1 );
};
var cn='jsdim';
var ckie=new Cookies;
ckie.save( cn, JSON.stringify({ width:screen.availWidth, height:screen.availHeight, colour:screen.colorDepth, depth:screen.pixelDepth }), 1 );
In PHP
<?php
if( isset( $_COOKIE['jsdim'] ) ){
$json=json_decode( $_COOKIE['jsdim'] );
if( !defined('SCREEN_WIDTH') ) define( 'SCREEN_WIDTH', $json->width );
if( !defined('SCREEN_HEIGHT') ) define( 'SCREEN_HEIGHT', $json->height );
if( !defined('SCREEN_COLOUR_DEPTH') ) define( 'SCREEN_COLOUR_DEPTH', $json->colour );
if( !defined('SCREEN_PIXEL_DEPTH') ) define( 'SCREEN_PIXEL_DEPTH', $json->depth );
}
?>
I do not think, that screen size/resolution is really what you want to adjust your view templates for mobile devices. Actually you want to know what plattform/device someone is using, think about Nexus 7, which has 1920 × 1200 or Sony Xperia Z5 with 2160 x 3840px.
I would look at user-agent and HTTP headers for the server side code, there are already good libraries for that: e.g. mobiledetect. For the client side the best practice is to use CSS3 Media Queries: Media Queries for Standard Devices
You can retire the $_GET of the URL by the htaccess, I'm using RewriteRule.
Options +FollowSymLinks
RewriteRule ^folder/file.php$ folder/file.php?g=2
#if you want to remove php file extension, don't keep the .php before the $
To remove all php files extension: php.net.
Edit: this is for who doesn't use Wordpress
You can use this plugin:
https://wordpress.org/plugins/mobble/
It adds an is_mobile()-feature.
In your theme you can now use is_mobile() instead of $_GET['width'] > ...
This way you don't need a ?width= in your $_GET
I am trying to add to my site the capability, where the background will change based on part of the URL using stylesheets.
Example:
address/shop/index.php = background image 1
address/shop/index.php?cPath=22 = background image 2
address/shop/index.php?cPath=23 = background image 3
address/shop/index.php?cPath=24 = background image 4
Any ideas? I have looked at Javascript and jQuery but not sure on which one to choose or how to go about it.
It looks like you are using PHP, so you should be able to do it without javascript. You just need to use PHP's server variables.
Something like
$cPath = $_GET['cPath']; //This allows access to the query part of the url
if($cPath == 24){
//set background url
}
You can always let the part of url surrounded by a tag e.g. <font>
So the code would be like:
<a>your url link
<font class='background1'>part with background1</font>
<font class='background2'>part with background2</font>
</a>
Then in css you can have
.background1{background: url('...')}
.background2{background: url('...')}
This may be a hackish way but in this way you can at least categorize your 'link parts'.
If you really want to do this client-side, I'd suggest:
var pageBackground = {
'default' : 'classOne',
'22' : 'classTwo',
'23' : 'classThree'
};
document.body.className = pageBackground[window.location.split('cPath=')[1] || 'default'];
Coupled with the stylesheet:
body.classOne {
background-image: url(path/to/defaultImage.png);
}
body.classTwo {
background-image: url(path/to/imageTwo.png);
}
body.classThree {
background-image: url(path/to/imageThree.png);
}
on your html page inside the body tag type:
<body background="your file">
</body>
You can do that on each page that you want a different background and it will override any CSS style that styles the body
I want to preload all images in a directory called img,and that directory also contains sub directory called ui_images.
I know how to preload specific images by putting their names in an array and doing the preloading work, but i want to know how to tell the script to search dynamically for all images in that directory img and img/ui_images?
Here's my code :
var preloadImg = function(imgArr){
$.each(imgArr, function(index,value){
$("<img/>")[0].src = value;
});
}
var arrimg = ['img/check.png','img/add_sub.png'];
preloadImg(arrimg);
There is no generally available facility for doing a directory listing in http. The options I can think of are:
Name your images in a predictable fashion like (img001, img002, etc...) and then you can load images until you get an error.
Name your images in a predictable fashion like (img001, img002, etc...) and then code in one numeric limit value into your web page for how many there are.
Create an ajax call (on both client and server) that will give you a list of image names to preload.
Have your server embed an array of image names into the page so you know what to preload.
I was looking at improving the performance on one of my sites and looked into this. My solution seems to work and I haven't seen it anywhere else yet.
Its a two step approach using jquery and php
// Preload images via jquery .load and delete once their cached via the callback
<div id="preload"></div>
$('#preload').load('preload.php', function() {
$('#preload').remove();
});
// preload.php below - loop through the image folder and insert the images into a hidden div
<div style="display:none">
<?php
$dirf = 'images';
$dir = scandir($dirf);
foreach ($dir as $file) {
if (($file != '..') && ($file != '.')) {
echo "<img src='images/$file' />";
}
}
?>
</div>
This worked in Firefox but feel free to critique or improve
I am a bit of a pickle right now: I have an image displayed on my website, which has an src from a mysql server, it looks like this:
echo '<img src = "'.$sourceVariableFromDatabase.'" class = "profileImage" id = "profilePicture" />';
Also on my site, is a function that changes the database, and hence the value of $sourceVariableFromDatabase. However, the image won't update until the page is refreshed, but I would like it to display the new image src from the databse without refreshing.
I know this can be done through jQuery, but am unsure as to how to get the value from a database, as Javascript is not a server side, like javascript, and as far as I know cannot access databases in mysql.
How can I achieve this in Javascript/jquery.
Thanks, I have tried to be as clear as possible, and apologise for any waffle.
JQuery can be used to call a URL that returns data (e.g. HTML, JSON, text, etc). How that URL returns data can be however you want (PHP+MySQL, etc). Once JQuery receives the response, it can then update the img tag.
Here is a simple example:
Example HTML
<img id="profilePicture" src="(your source from db1)" />
Example JQuery on HTML page
function update_image(db)
{
// get new image src
$.get('some/url/to/get/new/src', {db: db}, function(response){
// update the img src
$('#profilePicture').attr('src', response);
});
}
Example page (/some/url/to/get/new/src):
<?php
// get request data
$db = $_GET['db'];
// get img src
$src = some_function_to_get_src($db);
// output src
echo $src;
$.get('/pathToCode', function(imagePath){
$('#profilePicture').attr('src', imagePath);
});
The file at /pathToCode would need to query the database and echo the path to the image. Just add this code to the end of your function that changes the database.