Use a DIV's width in If statement in Php file - php

I have a .php file in which I have a layout that I would like to change depending of a div's width. That div is a parent of the following code and is situated in a other file.
<?php if ($(".container").width() > 400) { ?>
<div class="sub-container">
<div">sidepanel-left</div>
<div>content</div>
<div>sidepanel-right</div>
</div>
<?php } else { ?>
<div class="sub-container">
<div>sidepanel-left
<div>sidepanel-right</div>
</div>
<div>content</div>
</div>
<?php } ?>
That gives me a blank page with only Html, head and body tags.
I'm sure it's a pretty basic code that I need, but I'm just starting in PHP/JS and I'm not sure of what I'm doing -_-
Let me know if you need more information!
Thanks in advance for the help! :)
B.

You can not do this in PHP. What you can do is the following:
From PHP side, output this HTML code:
<div class="container">
...
<div class="sub-container">
<div>sidepanel-left</div>
<div>content</div>
<div>sidepanel-right</div>
</div>
</div>
Then in your HTML page, make sure jquery is loaded, and put this:
<script type="text/javascript">
$(document).ready(function() {
$('.container').each(function(){
var $this = $(this);
if ( $this.width() > 400 ) {
$this.addClass('wide-container');
}
});
});
</script>
Then, in your css file you can setup a class for regular container and wide container, and you can also control the styles of subcontainers:
.container {
// default styles here
}
.container.wide-container {
// override wide container styles
}
.container.wide-container > .subcontainer {
// override subcontainer styles
}
You might use #media queries to achieve similar result, but #media queries can be applied according to the width of the screen, not a particular container.

Related

How to display element randomly from another url?

I want to randomly display three divs (of the same class ".post-content") from a specific url.
I can display contents of a div from another url (with consent) using the following code, but it lacks the randomisation I need:
<script>
$(function(){
var contentURI= 'http://www.example.com/ .post-content';
$('#response').load('grabber.php?url='+ contentURI);
});
</script>
<?php echo file_get_contents($_GET['url']); ?>
<div id="response"></div>
EDIT This currently outputs a url with just the one div of that class. I need it to output x3 divs of the same class at random.
My skills are somewhat lacking to mash other code I've found into one concise code. Any assistance you can provide would be greatly appreciated. Thank you.
Found the answer...
JQuery
$.get("https://www.example.com", function(data) {
var $quotes = $(data).find(".container-articles-5"),
count = $quotes.length,
$random = function() {
return $quotes.eq(Math.floor(Math.random() * count));
};
$(".blog-ad-1").append($random);
});
HTML
<aside class="blog-ad-4">
<div class="blog-ad-5">
<div class="blog-ad-3">
<div class="blog-ad-1"></div>
</div>
<div class="blog-ad-3">
<div class="blog-ad-1"></div>
</div>
<div class="blog-ad-3">
<div class="blog-ad-1"></div>
</div>
</div>
</aside>

Can't access JQuery through CSS

I am trying to write a menu for a front page that when an item is hovered over, the background image of the background div changes.
I have three main documents creating this effect, menuFunction.php, which is included in the header file, so it is not a link problem, then there is index.php, and finally my stylesheet.
Here is an example of one of the menu items functions from my menuFunction.php file:
<script>
$(document).ready(function () {
$(".resume").hover(function () {
$(".backgroundImage").css("background", "url(http://www.vhawley.com/wp-content/themes/vhawleycomtheme/css/style/images/menuResume.jpg)");
});
$(".resume").mouseleave(function () {
$(".backgroundImage").removeAttr('style');
});
});
</script>
Now here is where it is mentioned in index.php:
<div id="photoBackground" class="backgroundImage">
<div id="menuWrap">
<ul id="menu">
<li id="menuResume" class="resume">Resume</li>
<li id="menuAbout" class="about">About</li>
<li id="menuGallery" class="gallery"><a href="http://www.vhawley.com/gallery">Gallery</li>
<li id="menuContact" class="contact"><a href="http://www.vhawley.com/contact">Contact</li>
</ul>
</div>
</div>
Notice that the classes mentioned in the menuFunctions.php are also mentioned in the corresponding li.
Now, I am able through my stylesheet to define that the background have the following attributes for #photoBackground
#photoBackground{
height:450px;
width:100%;
background-image:url(http://www.vhawley.com/wp-content/themes/vhawleycomtheme/css/style/images/menuDefault.jpg);
background-repeat:no-repeat;
background-position:center;
}
Lastly, what I am now trying to accomplish is to get the rest to work, but even when I use the class .resume in my CSS, it does not work, even when I use the div #menuResume, no luck. I have been trying forever and have tried putting off asking for help on this one, but I really am stuck. I have really no JQuery experience, just CSS, HTML 5, and some PHP, which usually if you can master them, they can make a decent site alone. Until you want to get fancy like this.
Any ideas?
EDIT:
It is an issue with linking the JQuery variables to CSS, it has nothing to do with getting the background to change, because as Popnoodles proved on JSFiddle, nothing is wrong with that.
You could do this with the css :hover selector. However, if you want to use jQuery, you need to change .css('background'... to .css('background-image'...
It is the small mistakes that trip us up the most.
Edit to clarify your mistake:
The background style overrides everything, including background-repeat and background-position so those are all gone. If you used background-image it wouldn't override those other css options.
<script>
$(document).ready(function () {
$(".resume").hover(function () {
$(".backgroundImage").css("background-image", "url(http://www.vhawley.com/wp-content/themes/vhawleycomtheme/css/style/images/menuResume.jpg)");
});
$(".resume").mouseleave(function () {
$(".backgroundImage").removeAttr('style');
});
});
</script>
Best way to do this would be plain css
.resume #photoBackground {
...
}
.resume:hover #photoBackground {
... new image
}
I would research spriting to save some image loads, but that would requeire a fixed or known hight for the background image container. I would also use the following instead of wiring up a handler for each menu item:
HTML
<div id="photoBackground" class="backgroundImage">
<div id="menuWrap">
<ul id="menu">
<li id="menuResume" class="resume">Resume
</li>
<li id="menuAbout" class="about">About
</li>
<li id="menuGallery" class="gallery">Gallery
</li>
<li id="menuContact" class="contact">Contact
</li>
</ul>
</div>
</div>
Script
//Save looking up background container each time
var background = $("#photoBackground");
$("#menu li").hover(
//Hanldes Mouse Enter
function () {
var cssClass = $(this).attr('class');
$(background).addClass(cssClass);
},
//Handles Mouse Exit
function () {
var cssClass = $(this).attr('class');
$(background).removeClass(cssClass);
})
CSS
.backgroundImage {
background-image:url(http://www.vhawley.com/wp-content/themes/vhawleycomtheme/css/style/images/menuResume.jpg);
}
.backgroundImage.resume {
background-position:left -100px;
}
.backgroundImage.about {
background-position:left -200px;
}
.backgroundImage.gallery {
background-position:left -300px;
}
.backgroundImage.contact {
background-position:left -400px;
}
This also kind of demonstrates the principle of spriting by just changing the offset of the background image. OF course you could always just change the background image itself.
Demo

Jquery Tools Overlay: php foreach loop not working

I put Jquery Tools's Overlay in my site to show a projects' info in several overlays. This works pretty ok, but I have been trying to 'automate' the code to read new projects and load them in overlays. What happen looks ok, but no matter which project I click, the overlays allways load the content of the first project...
I did a lot of googling around and copy-pasting to get this far, I am not (yet) much of a programmer, I hope the code doesn't scare you guys.. ;-)
Anyway, here's a link: http://www.wgwd.nl/test
If you click 'Projects' a normal div opens that loads all the projects it finds (two, for now). When you click one it opens that content in 3 overlays. As said, unfortunately it allways loads the same content independent of which project you click.
I have tried to assign the JScript a unique function name (generated with php from the project's filename) but that doesn't seem to work.
Any ideas? here's my code :
<?
//reads projectfolder and distills
//a basename out of the project description.txt
$textfiles = glob('content/projects/*.txt', GLOB_BRACE);
foreach ($textfiles as $textfile) { ?>
<div id="details"> <?
$pad = pathinfo ($textfile);
$base_name = basename($textfile,'.'.$pad['extension']);
// the link that opens the overlays. Don't think the "id" tag is nescessary
echo '<a id="'.$base_name.'" href="#" onclick="'.$base_name.'()"><img src="'.$base_name.'/main.jpg"/></a>' ?>
<!-- defines overlay, hidden by default -->
<div id="dragwindow1" class="overlay ol1">
<a class="close"></a>
<?
include ('content/projects/'.$base_name.'/content.txt');
?>
</div>
</div>
<?
// the description of each project
include ($textfile);
?>
<script>
// within the foreach open all overlays with function name $base_name
var <?=$base_name?> = function () {
$("a[rel]").each(function() {
$(this).overlay().load();
});
}
</script>
<hr />
<? } //end foreach ?>
</div>
<!-- somehow, without defining these links, the whole 'open all overlay' thing doesn't work -->
<a rel="div.overlay:eq(0)" type="button" style="display: none">first</an>
<a rel="div.overlay:eq(1)" type="button" style="display: none">second</a>
<a rel="div.overlay:eq(2)" type="button" style="display: none">third</a>
<script type="text/javascript">
$(function projects() {
// positions for each overlay
var positions = [
[120, '15%'], //uppper left, #1
[70, '60%'], // lower left, #2
['60%', '40%'], // lower right, #3
];
// setup triggers
$("a[rel]").each(function(i) {
$(this).overlay({
// common configuration for each overlay
oneInstance: false,
// setup custom finish position
top: positions[i][0],
left: positions[i][1],
});
});
});
</script>
Thx in advance!
EDIT: I edited the code to omit all that's unrelated
The question remains: Javascript only returns the content of the first call in the foreach loop. Is there anyway to generate multiple instances of the javascript for each loop in the PHP?
SOLVED! With big, big, help of a friend, who redefined how multiple Overlays from Jquery Tools could work (and should have worked in the first place...)
Without getting too much into it, here's the code for future reference:
Basically the trick is:
// open all overlays
function openAll(currentOverlays) {
$(currentOverlays).each(function()
{
$(this).overlay().load();
});
}
The complete page is now something like this:
<script type="text/javascript">
$(function () {
// positions for each overlay
var positions = [
['60%', 540], // lower right, #3
[80, '65%'], // lower left, #2
[120, '12%'], //uppper right, #1
];
// setup triggers
$("div.overlay").each(function(i) {
$(this).overlay({
// some configuration for each overlay
// positioning the overlays
top: positions[i % 3][0],
left: positions[i % 3][1]
});
});
});
// open all overlays
function openAll(currentOverlays) {
$(currentOverlays).each(function()
{
$(this).overlay().load();
});
}
// close all overlays
function closeAll(currentOverlays) {
$(currentOverlays).each(function()
{
$(this).overlay().close();
});
}
</script>
<div id="projectstarter">
<h2>Projects</h2>
<div class="maindetails">
<a class="close"></a> <!-- defines a close button for the overlay -->
<?
$textfiles = glob('content/projects/*.txt', GLOB_BRACE);
rsort($textfiles);
foreach ($textfiles as $textfile) {
$pad = pathinfo ($textfile);
$base_name = basename($textfile,'.'.$pad['extension']);
echo '<a href="#" onclick="openAll(\'div.'.$base_name.'\')">';
echo '<img src="./content/projects/'.$base_name.'/projectimage.jpg" class="thumb"/></a></div>';
include '$textfile'; //project description
} // end MAIN foreach ?>
</div>
</div>
<div id="projects">
<?
foreach ($textfiles as $textfile) {
$pad = pathinfo ($textfile);
$base_name = basename($textfile,'.'.$pad['extension']); ?>
<div id="dragwindow3" class="<?=$base_name?> overlay ol3">
<a class="close"></a>
<h2>Media</h2>
<div class="details">
// include media here
</div>
</div>
<div id="dragwindow2" class="<?=$base_name?> overlay ol2">
<a class="close"></a>
<h2>Credits</h2>
<div class="details">
// include credits here
</div>
</div>
<div id="dragwindow1" class="<?=$base_name?> overlay ol1 ">
<a class="close"></a>
<h2>Content</h2>
<div class="details">
// include content here
</div>
</div>
<? } ?>
<script>
$( "#projectstarter" ).overlay();
$( "#projectstarter" ).draggable().resizable({ghost: true});
$( ".ol1" ).draggable().resizable({ghost: true});
$( ".ol2" ).draggable().resizable({ghost: true});
$( ".ol3" ).draggable().resizable({ghost: true});
</script>

jQuery code will not work/apply to elements that are within a file called from an ajax using javascript

Hoping someone can point me in the right direction to an annoying problem.
To summarize before I put the code; I have two files.. a html file with javascript called "bookings.php", and a php file with php "getBookings.php".
The bookings.php file contains all the static information like menus, text etc along with javascript + ajax calls.
I'm calling the getBookings file successfully with javascript/ajax and works well and i don't have any problems with it.
My problem is, that from the file that is loaded (getBookings.php); there are some html elements that i need to toggle. The jQuery for it, I have included in the bookings.php file.. but the jquery won't apply or work when the ajax file is called.
All the contents on getBookings.php gets loaded into an #bookingSummary element.
Now, my code is very long, so i will include all the important parts..
// Usual Head Content, Meta, CSS, jQuery files
// Filters
<script language="javascript" type="text/javascript">
function bookings()
{
var fltr="";
if(document.frm.bkid.value != "")
fltr+='bkid='+document.frm.bkid.value+'&';
if(document.frm.customer.value != "")
fltr+='cid='+document.frm.customer.value+'&';
if(document.frm.site.selectedIndex != 0)
fltr+='sid='+document.frm.site.value+'&';
if(document.frm.status.selectedIndex != 0)
fltr+='st='+document.frm.status.value+'&';
if(document.frm.supp.selectedIndex != 0)
fltr+='sup='+document.frm.supp.value+'&';
if(document.frm.datefrm.value != "")
fltr+='dfrm='+encodeURI(document.frm.datefrm.value)+'&dto='+encodeURI(document.frm.dateto.value);
document.getElementById('bookingsummary').innerHTML="<br /><p align='center'> <img src='img/bigloading.gif'></p>";
url='get/getBookings.php?'+fltr;
getAjaxRec(url, viewbookings);
}
function viewbookings()
{
if (xmlHttp.readyState == 4 && (xmlHttp.status==200 || window.location.href.indexOf("http")==-1))
{
document.getElementById("bookingsummary").innerHTML = xmlHttp.responseText;
}
}
</script>
The Above code is the javascript that all works fine.. the following is the html code that calls the above function - bookings():
<!-- Several Form fields are here..-->
<input type="button" value="Apply Filter" class="searchBtn" onClick="bookings();">
<!-- Show booking results -->
<div id="bookingsummary"></div>
Now, within the getBookings file there is an html element with a class name "hiddenDetails" that i need to toggle and the Jquery for it is:
<script type="text/javascript">
$(document).ready(function() {
$('.bookingKeyDetails').click(function()
{
$(this).next('.hiddenDetails').slideToggle('medium");
});
});
</script>
The above code all works apart from the jquery.. here is a snippet from the getBookings.php file.. the part i want to apply the jquery to..
<?php
// A while loop happens then..
$result="
<div class=\"bookingKeyInfo\">
<div class=\"lb1\"><input type=\"checkbox\" name=sup1x".$rw['id']." ></div>
<div class=\"lb2\">".$rw['id']." </div>
<div class=\"lb3\">".date('d/m/Y', strtotime($rw['pickupDate']))." <strong><font color=\"#FF0000\">".date('H:i', strtotime($rw['pickupTime']))."</font></strong></div>
<div class=\"clearLeft\"></div>
</div>
<div class=\"bookingKeyDetails\">
<div class=\"b-one\"><img style=\"margin-top:9px; padding-bottom: 5px;\" src=\"$base_dir/img/".strtolower($rw['status']).".png\"></div>
<div class=\"b-two\"><img id=\"isCustomerEmailed\" style=\"margin-top:9px; padding- bottom: 5px;\" src=\"$base_dir/img/unassigned.png\"></div>
<div class=\"b-three\"><img id=\"isSupplierEmailed\" style=\"margin-top:9px; padding- bottom: 5px;\" src=\"$base_dir/img/unassigned.png\"></div>
<div class=\"b-four\"><img id=\"isSupplierConfirmed\" style=\"margin-top:9px; padding- bottom: 5px;\" src=\"$base_dir/img/unassigned.png\"></div>
<div class=\"b-trip\">".substr($rw['DA'],0,6)."..<strong> to </strong> ".substr($rw['DB'],0,6)."..</div>
<div class=\"b-pax\">".$rw['pax']." Pax</div>
<div class=\"b-cost\">€$cost </div>
<div class=\"b-supplier\">".substr($sup,0,10)."..</div>
<div class=\"clearLeft\"></div>
<div class=\"hiddenDetails\">More Booking Information...</div>
</div>";
echo $result;
?>
I know this is a very long description of the problem.. so I have tried to give my code exactly as it is..
Could anyone shed some light, as to why the jQuery isn't working.. cz it works separately, just not on any element that is called from getBookings..
The problem is, you're binding an event handler with jQuery to bookingKeyDetails before it actually exists on the page. Remember that this element is being added to your html only after the page is loaded, so any actions you make in $(document).ready(function() { will not apply to it.
Bind the event handler only after you change the html:
function viewbookings()
{
if (xmlHttp.readyState == 4 && (xmlHttp.status==200 || window.location.href.indexOf("http")==-1))
{
document.getElementById("bookingsummary").innerHTML = xmlHttp.responseText;
$('.bookingKeyDetails').click(function()
{
$(this).next('.hiddenDetails').slideToggle('medium');
});
}
};
Since the HTML element you need to toggle was never on the page when the calling page instantaiate the jQuery to toggle, you need to reinitialize the function after a successful call from your ajax.
You can use jQuery .success callback function for their AJAX call tools... I use that to help with this kind of processing instead of native AJAX. Makes life simpler and better cross browser support.
Just call your toggle function after the success.
http://api.jquery.com/jQuery.post/
It's very obvious that it will not toggle because you have writtent the Jquery in the "bookings.php". During the page load of bookings.php, it will not find any content of the getBookings.php so that Jquery will not apply as no element is available with that id.
You have to bind the event for the toogle on Ajax success event of the when you are calling for getBooking.php.
$.ajax({
url: URL,
success: function(){
$('.bookingKeyDetails').click(function()
{
$(this).next('.hiddenDetails').slideToggle('medium");
});
},
error: function(){
alert('failure');
}
});
You're using single and double quotes in your function call
$(this).next('.hiddenDetails').slideToggle('medium");
user 'medium' or "medium"

Opening a link inside a div in the same div

I am trying to make a div where I include PHP web pages into it, however when I click any link inside the div, it loads in new window.
Does anyone know how to solve this problem?
I also tried using an iframe instead of a div but it caused other problems.
HTML code:
<div id="cover5">
<div id="warning">
<?php include 'SignIn.php'; ?>
<p align="center">
Home
</p>
</div>
</div>
JS code:
function cover5() {
var cover = document.getElementById('cover5');
if (vis) {
vis = 0;
cover.style.display='block';
}
else {
vis = 1;
cover.style.display='none';
}
}
You have to make a distinction bitween the client-side and the server-side of a Web application.
<?php include 'SignIn.php'; ?> is a server-side command, because of the <?php ?>, which means that the user will never see that line exactly.
If your SignIn.php file contains for example my link, the user will only get the ouput of that inclusion, i.e.
<div id="warning">
<a href="go-there.php">my link</a
</div>
When the user clicks on the link, his browser will load it as if this <a /> would have been hard written within your HTML code directly, and then open it in a new window.
I don't no how to do it using native JS, but with jQuery, you can try something like this:
$(function() {
$("#warning a").each(function() {
$("#warning").load($(this).attr("href"));
});
});
To render html from a specific link within an element on the page you need to run an ajax GET call, and load the html. Then insert the response in your div.
using jQuery:
$("a").click(function(){ //calls function when anchor is clicked
var link = $(this).prop("src"); //finds the link from the anchor
$.get(link,function(data, status, xhr){ //makes an ajax call to the page
$("#myDiv").html(data); //replaces the html of #myDiv with the returned page
});
});
Hope that helps
HTML CODE :
<div id="cover5">
<div id="links">
<p align="center">
Home
</p>
</div>
<div id="warning">
<?php include 'SignIn.php'; ?>
</div>
</div>
and JS code:
function cover5() {
var cover = document.getElementById('warning');
if (vis) {
vis = 0;
cover.style.display='block';
}
else {
vis = 1;
cover.style.display='none';
}
}
Whenever an user click on the link in "links" div it will call JS function "cover5()"
You can use jQuery or ajax to pop-up "warning" div
In your code you added the links to the worning div so as when in second time ti will hide all the links form there.

Categories