Using Javascript/Php: Trying to display background image - logic wrong? - javascript

So I want to display a background image (that is the thumbnail image in wordpress post) using css in hero-wrapper div if the screen size is min. 900px.
I have using php to check if there is a thumbnail image, then using javascript to check screen width and then adding background-image property to the dive. Not working, I think my logic is wrong??
HTML
<?php
if ( has_post_thumbnail() ) { ?>
<?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );?>
<script type="text/javascript">
if (jQuery(window).width() == 900) {
<?php echo '<section class="hero-wrapper" style="background-image: url(' . $thumb['0']. ') >'; ?>
}
</script>
<?php } ?>
<section class="hero-wrapper">
<figure class="frontpage-hero">
<div class="banner-box">
<h2>GET YOUR FREE CASE ASSESSMENT?</h2>
<h6>Enter your details below for a consultation</h6>
<form>
<input type="text" name="name" placeholder="Name..">
<input type="text" name="email" placeholder="Email..">
<input type="submit" name="submit">
</form>
</div>
</figure>
</section>
css
.hero-wrapper {
margin: 0;
padding: 0;
min-height: 669px;
background-repeat: no-repeat;
}
#media screen (min-width: 900px) {
.hero-wrapper {
min-height: 669px;
background-repeat: no-repeat;
}
}

You are echoing a <section> tag inside a <script> tag.
You should change this
<script type="text/javascript">
if (jQuery(window).width() == 900) {
<?php echo '<section class="hero-wrapper" style="background-image: url(' . $thumb['0']. ') >'; ?>
}
</script>
To something like this
<script type="text/javascript">
if (jQuery(window).width() >= 900) {
$('.hero-wrapper').css('background-image', 'url(' + <?php echo $thumb['0']; ?> + ')');
}
</script>

Your assumption is wrong twice:
your jQuery(window).width() == 900 condition will run only once and will not reflect window size changes
you're trying to use php (server side language) to output html (client side markup) inside javascript (client side code) code block. You will end up with syntax error.
Correct approach is to just output your html element and use CSS media queries to control its appearance. Something like:
.hero-wrapper {
display: none;
}
#media (min-width: 900px) {
.hero-wrapper {
display: block;
}
}
Please also notice that image displayed as background will not enforce element to have any height and hence your element will show up with 0px height (invisible in other words). You will need to specify element's dimensions somehow (and remember that images may have different aspect ratios).
After all it may be easier for you to not use background image but insert normal image instead and control its dimensions using CSS.

You're not adding anything to the existing "hero-wrapper" div with your code, you're just echoing some HTML within a Javascript block, which won't achieve anything. You've almost certainly got syntax errors in your console. The final rendered page will look something like this:
<script type="text/javascript">
if (jQuery(window).width() == 900) {
<section class="hero-wrapper" style="background-image: url('thumbnail.png') >
}
</script>
<section class="hero-wrapper">
<figure class="frontpage-hero">
...etc
This will get you a JS console error along the lines of:
Uncaught SyntaxError: Unexpected token <
Even if that part worked, the HTML is also invalid because you never close the style attribute with a ", and this code will only ever execute when the window width is exactly 900px, which I don't think you intended.
What you need to be doing is altering the existing div to add the style, and also allow it when the width is greater than or equal to 900px. This should do it:
<script type="text/javascript">
$(document).ready(function() {
if ($(window).width() >= 900) {
$(".hero-wrapper").css("background-image", "url('<?php echo $thumb['0']; ?>')");
}
});
</script>
I also wrapped the code in document.ready so that it won't run until the page is ready.

I'd remove the javascript and do this in your CSS media queries with display: none; to hide the element for screens under 900px i.e
HTML/PHP
<?php
if ( has_post_thumbnail() ) {
$thumb = wp_get_attachment_image_src(
get_post_thumbnail_id($post->ID), 'full' );
echo '<section class="hero-wrapper" style="background-image: url(' . $thumb['0']. ') >';
} ?>
And in your CSS
#media screen (min-width: 900px) {
.hero-wrapper {
min-height: 669px;
background-repeat: no-repeat;
display: block;
}
}
#media screen (max-width: 900px) {
.hero-wrapper {
display: none;
}
}

Related

Dynamically change a background image depending on view port width

This is WordPress site that I'm updating. I have two images; one for larger screens and one for smaller screens/mobiles.
I'm aware I can do this through CSS, but the background images are intended to be changed by the user who don't have access to the CSS. I have some custom fields created on the Wordpress that allows them to easily change the images.
At the moment I have this in the PHP page, which only works for one image:
<div class="block block--overlay" style="background-image: url('<?php echo theme('background_image', 'url'); ?>');">
</div>
What's the best way to have something like this?
<div class="block block--overlay" style="background-image: url('<?php if_large screen: echo theme('background_image', 'url') else echo theme('mobile_background_image', 'url'); ?>');">
</div>
I've read about the wp_is_mobile() function and that it's not very reliable, and doesn't work responsively.
What other alternatives do I have?
You can inject a css variable for esktop and mobile versions, and use this variables in css #media queries.
the php will look like this:
<div style="--desktop: url('<?php echo 'https://picsum.photos/id/1/600/400'; ?>'); --mobile: url('<?php echo 'https://picsum.photos/id/1/200/600'; ?>')"></div>
The output should be like this:
:root {
--desktop: "placeholder-url";
--mobile: "placeholder-url";
}
div {
height: 100vh;
}
#media screen and (max-width:520px) {
div {
background-image: var(--mobile);
}
}
#media screen and (min-width:520px) {
div {
background-image: var(--desktop);
}
}
<div style="--desktop: url('https://picsum.photos/id/1/600/400'); --mobile: url('https://picsum.photos/id/1/200/600')"></div>

FireFox and <a href scrolling to a page part like div

I have a style for image button :
.sticky {
position: fixed;
top: 50px;
width: 120%;
z-index: 1;
}
#media screen and (min-device-width : 100px) and (max-width: 600px) {
.sticky{
display:none;
}
}
and script for these:
window.onscroll = function() {
myFunction();
}
var backarrow = document.getElementById("back");
var sticky = backarrow.offsetTop;
function myFunction() {
if (window.pageYOffset >= sticky) {
backarrow.classList.add("sticky");
} else {
backarrow.classList.remove("sticky");
}
}
it actually works! But I do not understand why Clicking is disabled for FireFox while other browsers do not have problems with it. z-index is set to 1 but other browsers are fine with it but FF. what I can do about it and how to fix it?
Thank you very much who knows!
I just did this for image buttons links:
<a href="#top" <a href="#wrap"
Supposed to work for any browser. This even not a script. but probably not good css enough that I have.
'>
<img alt="" class="mainlogo" src='data:image/png;base64,<?php echo base64_encode(file_get_contents("******.png")); ?> '>
<button class="right"> <img alt="" id="forward" class="logo" style='max-width: 40px;' src='data:image/png;base64,<?php echo base64_encode(file_get_contents("*****/Pictur3.png")); ?> '> </button>
I solved the problem!!!!!!!!!!
What I did is used my button id for my jquery script insted of img id. Thus, entire button would scroll down insted of only image and therefore I could implement
<button onClick="location.href = '#top'"
insted of any
<img onclick or <href onclick
events that I tried and do not work.
Hope it helps anybody too as example:)

show loading icon until the page is load?

I wanted to show a loading icon to users until the page elements are fully loaded. How can I do that with javascript and I want to do it with javascript, not jquery?
Here is a link how google does it
How can I do this?
triggering some function on onload event or something like this .. I know it will be done somewhat like this or any other ways to do it?
Or there is some event for it?
UPDATE
I did something using display property I hide the body element but and onload of body tag I change its property but where to put the loading icon and add more interactivity.
HTML
<body>
<div id="load"></div>
<div id="contents">
jlkjjlkjlkjlkjlklk
</div>
</body>
JS
document.onreadystatechange = function () {
var state = document.readyState
if (state == 'interactive') {
document.getElementById('contents').style.visibility="hidden";
} else if (state == 'complete') {
setTimeout(function(){
document.getElementById('interactive');
document.getElementById('load').style.visibility="hidden";
document.getElementById('contents').style.visibility="visible";
},1000);
}
}
CSS
#load{
width:100%;
height:100%;
position:fixed;
z-index:9999;
background:url("/loading.gif") no-repeat center center rgba(0,0,0,0.25)
}
Note:
you wont see any loading gif if your page is loaded fast, so use this code on a page with high loading time, and i also recommend to put your js on the bottom of the page.
DEMO
http://jsfiddle.net/6AcAr/ - with timeout(only for demo)
http://jsfiddle.net/47PkH/ - no timeout(use this for actual page)
update
http://jsfiddle.net/d9ngT/
The easiest way to put the loader in the website.
HTML:
<div id="loading"></div>
CSS:
#loading {
position: fixed;
width: 100%;
height: 100vh;
background: #fff url('images/loader.gif') no-repeat center center;
z-index: 9999;
}
JQUERY:
<script>
jQuery(document).ready(function() {
jQuery('#loading').fadeOut(3000);
});
</script>
add class="loading" in the body tag then use below script with follwing css code
body {
-webkit-transition: background-color 1s;
transition: background-color 1s;
}
html, body { min-height: 100%; }
body.loading {
background: #333 url('http://code.jquery.com/mobile/1.3.1/images/ajax-loader.gif') no-repeat 50% 50%;
-webkit-transition: background-color 0;
transition: background-color 0;
opacity: 0;
-webkit-transition: opacity 0;
transition: opacity 0;
}
Use this code
var body = document.getElementsByTagName('body')[0];
var removeLoading = function() {
setTimeout(function() {
body.className = body.className.replace(/loading/, '');
}, 3000);
};
removeLoading();
Demo: https://jsfiddle.net/0qpuaeph/
HTML, CSS, JS are all good as given in above answers. However they won't stop user from clicking the loader and visiting page. And if page time is large, it looks broken and defeats the purpose.
So in CSS consider adding
pointer-events: none;
cursor: default;
Also, instead of using gif files, if you are using fontawesome which everybody uses now a days, consider using in your html
<i class="fa fa-spinner fa-spin">
Element making ajax call can call loading(targetElementId) method as below to put loading/icon in target div and it'll get over written by ajax results when ready. This works great for me.
<div style='display:none;'><div id="loading" class="divLoading"><p>Loading... <img src="loading_image.gif" /></p></div></div>
<script type="text/javascript">
function loading(id) {
jQuery("#" + id).html(jQuery("#loading").html());
jQuery("#" + id).show();
}
HTML page
<div id="overlay">
<img src="<?php echo base_url()?>assest/website/images/loading1.gif" alt="Loading" />
Loading...
</div>
Script
$(window).load(function(){
//PAGE IS FULLY LOADED
//FADE OUT YOUR OVERLAYING DIV
$('#overlay').fadeOut();
});
firstly, in your main page use a loading icon
then, delete your </body> and </HTML> from your main page and replace it by
<?php include('footer.php');?>
in the footer.php file type :
<?php
$iconPath="myIcon.ico" // myIcon is the final icon
echo '<script>changeIcon($iconPath)</script>'; // where changeIcon is a javascript function whiwh change your icon.
echo '</body>';
echo '</HTML>';
?>

How to pack contents in a div to move to the right when content reaches bottom of the div

Im generating some content with PHP, but after the number of contents is more than 5 the height becomes greater than that of the div, so i don't want it to stack on top of the div, but to move to the right of the div and start from the top. Here's an image.
PHP
echo '<a class="LibSectOpen">
<span style="display:none" class="SectionName">'.$Section.'</span>
<div class="LibrarySects"><div class="LibrarySectsHeader">'.$Section.'</div>
<div class="LibrarySectsShelf">';
while($row = mysql_fetch_array($log2)){
echo '<div class="LibrarySectsShelf_Book" style="background-color:'.$Color.'"
title="Author: '.$row['bbookauthor'].'">'.$row['bbookname'].'</div>';
}
echo ' </div>
</div>
</a>';
As it looks, the philosophy books in the example goes down, and i want it to go to the right and start another column of five books and so on.
Any ideas i can do this with JQuery and CSS?
.LibrarySectsHeader {
border:1px #CCC solid;width:500px; margin:2px; padding:1px; height:18px;border-radius:2px 2px 2px 2px; font-size:10px; color:rgba(0,0,0,1) !important; background-color: rgba(255,255,255,0.6); line-height:18px;
}
.LibrarySectsShelf {
border:1px #CCC solid;width:499px; margin:2px; padding:1px; height:129px;border-radius:2px 2px 2px 2px; font-size:10px; background-color: rgba(255,255,255,0.2); line-height:18px; background-image:url(images/bg/wood.jpg); background-size:100%; background-repeat:no-repeat;
}
.LibrarySectsShelf_Book {
border:1px #C90 solid;width:148px;height:23px; margin-bottom:1px;border-radius:3px 3px 3px 3px; font-size:10px; background-color: rgba(51,153,255,0.9); padding-left:2px; line-height:22px; color:rgba(255,255,255,1) !important; overflow: hidden;
}
.LibraryBooks {
border:1px #CCC solid;width:502px; margin:2px; padding:1px;border-radius:2px 2px 2px 2px; font-size:10px; background-color: rgba(102,102,102,1); line-height:18px;
}
You can achieve the output you want using only PHP,HTML,CSS solution which you are already using:
PHP
$i=1;
echo '<a class="LibSectOpen">
<span style="display:none" class="SectionName">'.$Section.'</span>
<div class="LibrarySects"><div class="LibrarySectsHeader">'.$Section.'</div>
<div class="LibrarySectsShelf"><div class="move_right">';
while($row = mysql_fetch_array($log2)){
echo '<div class="LibrarySectsShelf_Book" style="background-color:'.$Color.'"
title="Author: '.$row['bbookauthor'].'">'.$row['bbookname'].'</div>';
if($i%5==0)
{
echo '</div><div class="move_right">';
}
$i++;
}
echo '</div></div></div></a>';
The above code uses <div class="move_right"> ... </div> to divide elements in group of 5 so as to display each group in a new column.
CSS (.move_right)
.move_right{
display:inline-block;
vertical-align:top;
}
Fiddle of how the generated HTML's output will be
I'll provide you with 2 solutions here, PHP and CSS, as #ariel has already contributed a jQuery solution, since I always like to be JS independent, and also it will save you, using a third party script, along with jQuery Library (If you aren't using jQuery), I chosed PHP first, and than the CSS one which may be less compatible in terms of IE.
If you want to achieve that using PHP, you need to alter your loop and set a counter, which will break..
Assume that we are having an array of elements, and we want to set just like you need it..
<div class="wrapper">
<ul>
<?php
$arr = array('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15');
$counter = 0;
foreach ($arr as $value) {
if($counter%5==0 && $counter != 0){ echo "</ul><ul>";}
?>
<li><?php echo $value; ?></li>
<?php
$counter++;
}
?>
</ul>
</div>
Here, am using a counter variable which am incrementing at the end of the loop, the line over here $counter%5==0 in if condition states that if the loop counter is divisible by 5, add </ul><ul>, hence, this will generate a group of ul which are floated to left.. consisting of 5 li each.
Demo - Fiddle Code
CSS
* {
margin: 0;
padding: 0;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
.wrapper {
height: 150px;
margin: 50px;
border: 1px solid #eee;
}
ul {
float: left;
list-style-type: none;
}
ul li {
height: 30px;
width: 150px;
background: tomato;
border: 1px solid #515151;
}
Now as you said that but after the number of contents is more than 5 the height becomes greater than that of the div hence if you apply the same logic in your markup, it will force the div to start another column.
Demo - Fiddle Code
<a class="LibSectOpen">
<span style="display:none" class="SectionName"><?php $value; ?></span>
<div class="LibrarySects"><div class="LibrarySectsHeader">Whatever</div>
<div class="LibrarySectsShelf">
<div class='inner_wrap'>
<?php
$arr = array('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15');
$counter = 0;
foreach ($arr as $value) {
if($counter%5==0 && $counter != 0){ echo "</div><div class='inner_wrap'>";}
?>
<div class="LibrarySectsShelf_Book" title="Author:">Whatever <?php echo $value; ?></div>
<?php
$counter++;
}
?>
</div>
</div>
</div>
</a>
Doing the same with CSS, you can use column-count property, but as far as IE is concerned, it will make a mess.. though if you're interested in the solution, than here you go...
Demo
HTML
<ul>
<li>1</li>
<!-- More incremented li -->
</ul>
CSS
ul {
list-style-type: none;
-moz-column-count: 3;
-webkit-column-count: 3;
column-count: 3;
}
For Multi Column Support Reference
My solution involves jQuery and the plugin Columnizer.
Here's the working fiddle: http://jsfiddle.net/bortao/qGfsr/
The code is very simple:
$('.LibrarySectsShelf').columnize({
width: 166,
height: 150,
doneFunc: function () {
$('.LibrarySectsShelf_Book').removeClass('hidden');
}
});
The only change in your css is this new class:
.hidden {
visibility: hidden
}
Which should be added to every LibrarySectsShelf_Book. This is solely to prevent the flickering of the unorganized items. The class is removed when the columnization is complete.
Easy.
.LibrarySectsShelf {writing-mode: vertical-lr;}
.LibrarySectsShelf_Book {display: inline-block;}
Works in every browser I tested, despite wiki pages claiming otherwise, and it's been around since IE8.
Solution using only CSS
The best way of doing this, is using CSS3 flex boxes like this:
Here is how:
In the CSS add these 3 lines in .LibrarySectsShelf{ ... }
.LibrarySectsShelf {
display: flex; // to add
flex-flow: column wrap; // to add
align-content: flex-start; // to add
... // the rest of your code
}
and 1 line in .LibrarySectsShelf_Book{ ... }
.LibrarySectsShelf_Book{
flex: 0 0 23px;
... // the rest of your code
}
Cross browser support
Please note that since Flex box is a new feature in CSS3, you may have to add some browser prefixes like -webkit-, -moz- and -ms- to let it work properly in all major browsers.
Also note that the flex box wrap feature is only available in Firefox 28 and newer.
A working cross-browser example is available on http://jsfiddle.net/29Cmz/
Why Flexbox
Because it is very flexible, it will fill up all the available space and you don't have to hardcode the number of rows in PHP/JavaScript.
I believe this may be helpful HTML list elements top to bottom, then left to right
The jsfiddle shows that if you want to do this with css you can use css columns. Otherwise an answer below links to a js plugin to achieve this. Alternatively you could just do the positioning when you create the content in PHP if this is possible.
It seems to me that you dont need the complete width of your main container.
Why don't you just add a fixed width to both categories and set them to display:inline; or display:inline-block (still messing these two up... sry).
If you want to determine it dynamically, you could check weather the height of your main container is sufficient for both categories. If this is not the case you could set the css attributes of both categories (I srsly hope for you they have the same css class ;) with
$('.your-class').css({'width':'250px', 'display':'inline'});
I think this should do the magic.
EDIT: Ahh sry. didint see your code... Never the less it should work this way ;)
First of all . Don't put div in a tag .
Then you can find array_chunk php function .
So What you need to do.
It will be better if you use PDO .
PDO fetch all will return array;
<?php
$chunkSize = 5; // or any other value you need
$chunks = array_chunk($result_array,$chunkSize);
foreach($chunks as $links_array):?>
<div class="move_right">
<?php foreach($links_array as $link):?>
<!-- your link code -->
<?php endforeach; ?>
</div>
<?php endforeach ?>
The following code detects the end of the div and creates a new column using css.
var col = 1;
jQuery(
function($)
{
$('#flux').bind('scroll', function()
{
if($(this).scrollTop() +
$(this).innerHeight()
>= $(this)[0].scrollHeight)
{
$("#yourdiv").css("-moz-column-count",col);
$("#yourdiv").css("-webkit-column-count",col);
col++;
}
})
}
);
Tons of great answers here, I vote the javascript/CSS ONLY solution because.
1) the PHP stays solely responsible for getting data to screen ( re use the same php logic for new presentations in the future )
2) The Javascript and CSS can be flexible to provide personalised markup arrangement per device, browser and view size
DEMO : http://jsfiddle.net/9Bc76/1/
Markup - Let PHP just generate the items and forget about presentation.
<div class="container">
<div class="item">An Item</div>
<div class="item"> An Item</div>
<div class="item">An Item</div>
....
Javascript to wrap the elements ( here is a hardcoded per 5 'items' ) - making use of the jquery selector and wrapAll method.
var items = $(".item");
for(var i = 0; i < items.length; i+=5) {
items.slice(i, i+5).wrapAll('<div class="wrapper"></div>');
}
CSS to layout
.wrapper { display:inline-block; float:left; }
/* clear the float so the container keeps 'containing' */
.container:last-child:after {
clear:both; display:block;visibility:hidden;
height:0; content:"."; }
That's it.
More, If we need our 'wrap count' to be dynamic, we can do some calculation based on the height of the .item and the height of .container to get the desired 'wrap' count.
Lets say the container has a fixed height that is not allowed to grow;
.container { height: 300px; width: 100%; overflow: hidden; }
Javascript can find the 'wrap count interval' dynamically ( find how may items fit in the container height }
var containerheight = $(".container").height(),
itemheight = $(".item").height();
var wrapinterval = Math.floor(containerheight/itemheight);
Now we can use
var items = $(".item");
for(var i = 0; i < items.length; i+=wrapinterval) {
items.slice(i, i+wrapinterval).wrapAll('<div class="wrapper"></div>');
}
DEMO with dynamic wrap interval - http://jsfiddle.net/2paNY/2/
APologies to fellow SO'ers if this contains parts already answered in one way or another, I just got into typing away
Just Copy and paste this piece of code and try at your end and use the logic.
<?php
for($i = 1; $i <= 20; $i++){
if($i % 5 == 1){
echo '<div style="float:left;">';
}
echo '<div class="LibrarySectsShelf_Book" style="background-color:'.$Color.'"
title="Author: '.$row['bbookauthor'].'">'.$row['bbookname'].'</div>';
if($i % 5 == 0){
echo '</div>';
}
}
?>

If Div is empty, hide it and change width of another div

I am new to css and php and am trying to find a way to hide my .item-page aside if the Div is empty. And then change the width of item-page to 100%. Right now the aside takes up 85px empty or not. How can do this in my php file?
Here is my CSS:
item-page {
position:relative;
width: 100%;
}
.item-page aside {
float:left;
position:absolute;
width:85px;
}
gk-article {
font-size:14px;
line-height:26px !important;
margin:0 0 80px 110px;
}
Here is my php file:
<div id="main">
<jdoc:include type="component" />
</div>
You've tagged javascript/jquery here, and that's probably what you should use (not PHP).
(in jQuery) you can do something like this - use classes as charlietfl suggested:
if( $('.item-page aside').html() == '') ) {
$('.item-page aside').hide();
$('.item-page').removeClass('isntempty').addClass('isempty');
} else {
$('.item-page aside').show();
$('.item-page').removeClass('isempty').addClass('isntempty');
}
CSS:
.isntempty {
width: 100%;
}
.isempty {
width: 50%; /* whatever your default width is */
}
You could set up different css class rules for empty vs not empty. These rules would set widths and/or display. Empty element would be zero...or don't even print it. Then run whatever test in your server code that determines status...and apply appropriate calsses to the elements
check by js in php:
<?php
...
echo "<script>if (document.getElementById('divId').innerText=='')
//or document.getElementById('divId').textContent=='' in firefox//
$('#divId').attr('style','width:100%;');
</script>";
...
?>
You can use Javascript, with the jQuery framework you could do this :
<script type="text/javascript">
$( document ).ready(function() {
//Hide if empty
if( $('.item-page').is(':empty') ) {
$('.item-page').hide();
}
//Change to width 100%
$('.item-page').css({width:'100%'});
});
</script>
Learn more here :
http://api.jquery.com/empty-selector/
http://learn.jquery.com/using-jquery-core/document-ready/

Categories

Resources