I'm working on a responsive website. I'm using CSS Media Queries and Adaptive Images (http://adaptive-images.com/) to render each page correctly on different devices.
My problem is that some elements are downloaded by the browser even if there are hidden! For instance, a element with the property {display:none;} is downloaded despite the fact that I don't want it.
So, here is my question: is there a way to add or remove HTML code depending on the device's screen-size?
By reading the code of "Adaptive Images" script, I saw they used a cookie, which stores the screen-size value.
<script>
document.cookie='resolution='+(window.innerWidth)+'; path=/';
window.addEventListener("resize", function() {
document.cookie='resolution='+(window.innerWidth)+'; path=/';
}, false);
</script>
So, I tried to read this cookie with a PHP function:
<?php
$fallback_res = 481;
$res = !empty($_COOKIE['resolution']) ? $_COOKIE['resolution'] :
$fallback_resolution; // Get the viewport resolution in $res variable
?>
It allows me to write a very useful PHP condition :
<?php if(isset($res) AND $res >= $fallback_res) // if viewport >= 481px
{
echo '<video>...</video>'; // Display the video
}
else { //if the screen is smaller
echo ''; // Echo something else
}
?>
It work very well. If the viewport is < 481px, the video is not downloaded. If the viewport is > 481px, the video is downloaded. But it only works, on page load! If I load the page with a 480-wide-opened-browser (=video not loaded), and then resize my browser to higher resolution, there is a big hole in the middle of the page.
What I need is to reload some part of the code on window resize. (Each time I resize the browser window, I want the $res condition to be updated automatically, and the following code as well)
Thanks.
if you combine blow jquery code with ajax , maybe you can do that .
$(window).resize(function() {
if($(window).width() > 480 )
{
#ajax code for download video
#or use .after in jquery
}
})
Html will looks like
<div id="phone">Content For the below 450px </div>
<div id="desktop">Content For the above 450px </div>
Add jQuery
if($(window).width() < 450 )
{
$('#desktop').remove();
}
else
{
$('#phone').remove();
}
Related
First posting here. I know inline php is not preferred but I haven't converted all my scripts to echo json_encoded arrays to work in javascript on the client side...so for now, I have inline php.
I do not know the extension of the user uploaded media because it could be a jpg,mp4,etc and upon upload it goes into a media folder with the user id as an identifier.
When my user first loads the div (and html page), the php script cycles through an array and does a fetch_assoc from sql query to the database each time; It returns the (media_id #) and prints out an li with the respective media displayed next to some other values from the query.
I only know the (media_id) and the file path name without the extension. When the page first loads, everything works great and the file_exists function returns correctly.
THE PROBLEM
When I AJAX the div and do the query again, because the user added a row to the database, the new list prints out with all info, BUT the file_exists function doesn't recognize the exact same paths as before and I don't have an img or video on the page.
I copy/pasted the exact same code from the original div and put it in a file for ajax to re-query and print the new li's.
All variables are the same and when I hard code a test filepath, it prints fine. Maybe there's a caching issue?
THE CODE
<?php
$result=$conn->query($select);
$row=$result->fetch_assoc();
?>
<li>
<?php
if ($row['count']>0) {
echo "<div class='media-container'>";
$pathname = "uploads/".$row["id"]."media1";
$testjpg=$pathname.".jpg";
$testjpeg=$pathname.".jpeg";
$testpng=$pathname.".png";
$testmp4=$pathname.".mp4";
if (file_exists($testjpg)==TRUE || file_exists($testpng)==TRUE || file_exists($testjpeg)==TRUE) {
echo '<img src="'.$pathname.'">';
}if(file_exists($testmp4)==TRUE) {
echo "<video></video>";
}
echo "</div>";
}?>
</li>
I could use some advice on how to fix this and how to print appropriate media tags on unknown media types.
THE OUTPUT
<div class='media-container'>
</div>
DEBUGGING ATTEMPTS
echoing the exact file path of a known image in an <img> tag works fine. putting echo'test'; inside the file_exists case does nothing.
--
Solution (Kind of)
So I've used html's onerror before and I found a workaround, though I'd still like to know why I was getting an error. PSA this uses JQuery but javascript works too:
My Solution
<script>
function img2video(el, src) {
$( el ).replaceWith( '<video class="videoClass"><source src="'+src+'" type="video/mp4"></video>' );
}
</script>
<body>
<img style="width:100%" onerror="img2video(this,'<?php echo$pathname;?>')" src="<?php echo$pathname;?>">
</body>
Alright, so here's the final answer I made to best fit the problem using glob:
Javascript:
function img2video(el,src,place) {
if (place=='type') {
$( el ).replaceWith( '<video controls controlsList="nodownload" disablePictureInPicture style="width:100%;object-fit:contain;" preload="auto"><source src="'+src+'" type="video/mp4"></video>');
}
}
PHP:
<?php for ( $i=1; $i <= $limit; $i++) {
$path ="[DIRECTORY]/".$row["id"]."media".$i;
$path = (!empty(glob($path . '*.{jpg,png,jpeg,avi,mp4}', GLOB_BRACE)[0])) ? glob($path . '*.{jpg,png,jpeg,avi,mp4}', GLOB_BRACE)[0] : false;?>
<div>
<img onerror="img2video(this,'<?php echo$path;?>','type',<?php echo$row["id"];?>,<?php echo$i;?>)" src="<?php echo$path;?>">
</div>
<?php } ?>
I don't know how to mark as duplicate, if someone could help with that. My answer uses Glob_Brace from #Akif Hussain 's response on This Question.
I seek a simple way to call a php file using jquery.
The ultimate outcome has to do with a Magento site I am working on:
http://bouquetsco.com/flowersplants.html
^^This page
This page displays products: 3 in a row.
<?php $this->setColumnCount(3); ?>
<?php $this->setColumnCount(2); ?>
^^This php code manually sets the number of product columns.
By default the page displays 3 wide, which looks fine until the browser window re-sizes down to tablet width (760px or so). When the website's design is tablet size (760px or so) I would like to display only two columns of products.
To do this, it seems one must use javascript to determine the window width, then run some php code depending on the browser-window width... like
this...
if ( browser-window-widith > 760) { get '3-column.php' }
else { get '2-column.php' }
This is grossly over-simplified.
What would this code logic look like? How would one write this functionality?
Also, one could change the initial if statement to:
if (browser-window-width < 760) { get '2-column.php' }
else { get '3-column.php' }
====================================
There would exist two .php files (2-column.php, & 3-column.php)
Each contains:
<?php $this->setColumnCount(2); ?>
or
<?php $this->setColumnCount(3); ?>
The code would call one file or another depending on the browser window width, (which would be found by the javascript) and thus result in
3-column product list for displays > 760px
and
2-column product list for displays < 760px
I use this on the login page of my site:
if(!isset($_GET['width']))
{
echo '<script type="text/javascript">window.location = "' . $_SERVER['PHP_SELF'] . '?width="+screen.width+"&height="+screen.height;</script>';
}
else
{
$_SESSION['screen_width'] = $_GET['width'];
$_SESSION['screen_height'] = $_GET['height'];
}
Now the width and height are saved to the current session, and I can do a condition check before displaying the page division.
if($_SESSION['screen_width']>= '1400')
{
$this->setColumnCount(3);
}
else
{
$this->setColumnCount(2);
}
You can use jquery width and some ajax calls.
index.php
<html>
....
<div id="somedivport"></div>
<--! if that script is used the above div will load differently depending on the width-->
</html>
script.js
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
//or use this$(document).width();
$("#somedivport").load(width>$(window).width()?"/3-column.php":"/2-column.php");
});
</script>
Edit for reducing kloc
An ex developer of ours when working on one of our first versions of our internal PHP framework integrated the dropdown element of main navigation using javascript and I need to get a fix applied for IE8 which is causing the dropdown to appear offset even though using CSS displays fine in Firefox / Chrome.
The site in question is http://www.benchmemorials.co.uk/
In the event there is sub menu items from the main navigation that use a dropdown, javascript is called to display this I believe (below)...
<script type="text/javascript">
$(document).ready(function() {
var position = $('#link_why-buy-from-us').offset();
$('.dropdown').css(position);
$('#link_why-buy-from-us').mouseover(function() {
$('.dropdown').show();
});
$('.dropdown').mouseover(function() {
$('.dropdown').show();
});
$('.dropdownstyle').mouseover(function() {
$('.dropdown').show();
});
$('#link_why-buy-from-us').mouseleave(function() {
$('.dropdown').hide();
});
$('.dropdown').mouseleave(function() {
$('.dropdown').hide();
});
$('.dropdownstyle').mouseleave(function() {
$('.dropdown').hide();
});
});
</script>
I'm not too hot on javascript but from what I gather, I presume the above is instructing the drop down to appear below the 'Why Buy from Us' top navigation menu item. As I mention, this is working as expected in Firefox/Chrome.
However, the issue appears to be the fact that somewhere along the line, inline CSS is being generated dynamically for the dropdown class - this is dynamically generating
style="top: 61px; left: 964px; display: none;"
Every file on the server has been searched and nowhere is this specified, my only guess is that the javascript above is somehow creating this line of CSS which is therefore preventing me from altering the position of the dropdown in the IE only stylesheet to fix the display in IE8.
The rest of the code for the dropdown menu from the php file is below:-
<div class="dropdown"><div class="dropdownstyle">
<?php
mysql_select_db($database_config, $config);
$query_sub_pages = "SELECT * FROM `pages` WHERE site_id = '".$current_site_id."' AND menu_location = 'sub' ORDER BY `order` ASC";
$sub_pages = mysql_query($query_sub_pages, $config) or die(mysql_error());
$row_sub_pages = mysql_fetch_assoc($sub_pages);
$totalRows_sub_pages = mysql_num_rows($sub_pages);
$current_sub_link = 0;
do {
$current_sub_link = $current_sub_link + 1;
?>
<p<?php if ($current_sub_link != $totalRows_sub_pages) {echo ' style="margin-bottom: 10px;"';}; ?>><a class="sub_link" href="<?php echo $site_base.$row_sub_pages['page_location']; ?>"><?php echo $row_sub_pages['page_display_name']; ?></a></p><?php //if ($current_sub_link != $totalRows_sub_pages) {echo '<br />';}; ?>
<?php } while ($row_sub_pages = mysql_fetch_assoc($sub_pages)); ?>
</div>
</div>
As you can see, there is no inline CSS applied to .dropdown. All CSS from the sylesheets can be viewed if you inspect element in browser.
Please could anyone advise how or if it is possible to prevent this dynamic CSS positioning from being generated or an alternative / easier method of ensuring the dropdown appears consistently across all browsers including IE?
Thanks in advance.
The positioning is done by this code:
var position = $('#link_why-buy-from-us').offset();
$('.dropdown').css(position);
It takes the position of #link_why-buy-from-us relative to the document, and adds it to the .dropdown element.
I don't know if you're familiar with jQuery, but the code above is written using that JavaScript library. For more documentation about .offset(), look here: http://api.jquery.com/offset/
I have a form for user input in which users can add images hosted elsewhere using a form. The images are displayed as a small icon which is both a link and which will load an image into a div with stacking order +1 on hover. The image source address is stored in the link tag only.
I am using a <div /> with contenteditable=true for the user input. The icon is appended when the form is used. The code for this part works fine. What I would like to do is check the source of all image tags to make sure that users are not adding their own html to display full size images in their post.
I am using php on the backend to remove all tags except links and images, but would like to use jQuery to check the src of the image tags before posting.
<img src="my_icon" /> //this is what my form will input
<img src="anything_else"> //this is what I want to prevent
Update: I apologize if this is not clear. Essentially, I don't want the user to be able to input any html of their own. If they want to add an image, they have to use my built in form which inserts something like above.
You could loop over the images and then check the src attribute.
$("img").each(function(index) {
if ($(this).attr("src") == ...) {
// do something
}
}
See http://api.jquery.com/each/ and http://api.jquery.com/attr/ for more information.
Say we have the <div id="editor" /> the jQuery script would look something like this:
var srcs = [];
jQuery ('div#editor img').each (function () {
srcs.push (jQuery (this).attr ('src'));
});
srcs will now hold all the src-attributes from the <img />-tags provided in the <div id="editor" /> tag.
Especially for your site following code alerts the links for all images:
$('.postimage').each(function(){
alert($(this).attr('href'));
});
I have an answer. When users input a < or > in a contenteditable="true" div, the browser replaces them with the html notation < and >. The good news is the images would have never displayed when outputting the user comment. The bad news is that the jQuery based solutions given above will not work to remove the ugly coding. I ended up using php to do it with
$post = $_POST['comment'];
$imgcheck = true;
$stringstart = 0;
while($imgcheck == 'true'){
if($stringstart = strpos($post,'<img',$stringstart)){
if ($stringend = strpos($post,'>',$stringstart)){
$strlength = $stringend - $stringstart +4;
$substring = substr($post,$stringstart,$strlength);
if (!preg_match('~src="\/images\/ImageLink.jpg"~',$substring)){
$post = str_replace($substring, "", $post);
}
else{
$stringstart = $stringend;
}
}
else{
$imgcheck = 'false';
}
}
else{
$imgcheck = 'false';
}
}
If you guys check out this webpage:
http://www2.scandvision.se/oresund10/
How have they done this background fade in fade out?
When i check the source this
<img id="wrapper-background" src="images/body-background-0.jpg" alt="Background" />
and i think theres some kind of script maybe php or js, or both, that every 5 sec changes the background:
images/body-background-1.jpg
images/body-background-2.jpg
images/body-background-3.jpg
and so on..
So how did they do this? an example would be great, as i want to learn how to do that. If i was going to do something like this i think i would only manage to do a script in php that randomize everytime you refresh.
Thank you, this will expand my knowledge
I did that one time on a website, I use "Prototype JS" and "Script Aculo US" but you can easily do the same thing without these library. You can see an example here: www.envolulm.fr
I extract below and translate some comment of my code:
/* In my HTML PAGE*/
<div id="slideshow">
<p id="text1"><img src="/url/of/your/image1"/></p>
<p id="text2"><img src="/url/of/your/image1"/></p>
<p id="text3"><img src="/url/of/your/image1"/></p>
<p id="text4"><img src="/url/of/your/image1"/></p>
</div>
CSS:
#text1, #text2, #text3, #text4 {
position:absolute;
height:402px; // you can put other value...here
width:850px; // you can put other value...here
}
Javascript function
function changeimg(){
var sec = 6000; // Change each 6 secondes
var paras = $$('#slideshow p'); // Grab element "<p>" of the div with slideshow for ID
// For each element "<p>"
paras.each(function(para){
if(para.visible()){
paraFade = para; // We stock the item which will disappear
paraAppear = para.next(); // We got the next element (The one who wants to appear)
//If it's the last "p" element we come back to the first one
if(paraAppear == undefined){
paraAppear = paras[0];
}
}
});
Effect.Appear(paraAppear); // Script Aculo US animation
Effect.Fade(paraFade); // Script Aculo US animation
timer = setTimeout("changeimg()",sec); // Timer
}
Event.observe(window, 'load', function() { changeimg(); }
Hope that can help you.
They are using mootools framework. Check this out:
http://mootools.net/forge/p/slideshow
The jquery cycle plugin is a simple script to do this effect.
I think you can have the same effect if you use a jquery plugin called "jquery innerfade"
Here is a website when you can get the .js file of it, of course you need jquery to use it
Inner Fade