Help with jquery tabs - php

I need to know how to link (via a regular href anchor on a different page) to content that is inside a tab that is not the default tab. Can this be done? My code will explain hopefully what I require:
My Code:
The following is my profile_edit.php page:
The javascript:
<script src="Javascript/jquery-1.4.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8">
$(function () {
var tabContainers = $('div.tabs > div');
tabContainers.hide().filter(':first').show();
$('div.tabs ul.tabNavigation a').click(function () {
tabContainers.hide();
tabContainers.filter(this.hash).show();
$('div.tabs ul.tabNavigation a').removeClass('selected');
$(this).addClass('selected');
return false;
}).filter(':first').click();
});
$(function () {
var tabs = [];
var tabContainers = [];
$('ul.tabs a').each(function () {
// note that this only compares the pathname, not the entire url
// which actually may be required for a more terse solution.
if (this.pathname == window.location.pathname) {
tabs.push(this);
tabContainers.push($(this.hash).get(0));
}
});
// sniff for hash in url, and create filter search
var selected = window.location.hash ? '[hash=' + window.location.hash + ']' : ':first';
$(tabs).click(function () {
// hide all tabs
$(tabContainers).hide().filter(this.hash).show();
// set up the selected class
$(tabs).removeClass('selected');
$(this).addClass('selected');
return false;
}).filter(selected).click();
});
</script>
The html and PHP (a portion):
<div class="tabs">
<ul class="tabNavigation">
<li>Account</li>
<li>Password</li>
<li>Favorites</li>
<li>Avatar</li>
</ul>
<div id="account_div">
<?php include("personal_info_edit.php"); ?>
</div>
<div id="change_password_div">
<?php include("change_password.php"); ?>
</div>
<div id="favorites_div">
<?php include("favorites.php"); ?>
</div>
<div id="avatar_div">
<?php include("avatar.php"); ?>
</div>
</div>
The following is contained in my change_password_submit.php page:
$update_pass= ("Password changed successfully.");
header("location:profile_edit.php?update_pass=$update_pass#change_password_div");
exit();
By default, whenever profile_edit.php is loaded, the personal_info_edit div is shown and the others are hidden. What do I need to change in the code so that I can reference the 2nd div (ie. change_password div and hide the rest after someone changes their password?
Any help will be greatly appreciated.

This is perhaps not the most elegant solution, but it should work.
You can have PHP sniff your url variables for the existence of a particular variable. I'd probably call this something like 'selectedTabId' or something like that. Then, if that variable exists, you can have jQuery invoke the click action on that tab. You'll want to use switch/case for this rather than just sending through whatever happens to be in the URL, as people can put nasty things there that you don't want your jQuery to run. I won't do that in my example below, for expediency's sake.
This is a notional example...
<?php
if( array_key_exists('selectedTabId',$_GET) ){
$selectedTabId = $_GET['selectedTabId'];
echo "<script type=\"text/javascript\">";
echo "jQuery(document).ready(function(){'#$selectedTabId').click()});";
echo "</script>";
}
?>
Give that a shot and see if it works for you.

I use this thinger: http://flowplayer.org/tools/tabs/index.html
It does that for you. It also does a whole lot on top. It maybe worth implementing instead of your custom solution?
Here's an example of it in action: http://www.estanciaboerne.com/amenities#TAB2entertainment
(This doesn't actually teach you anything, but it is a solution to your problem, so I'm sorry and you're welcome all in one.)

Related

how do i include #include('layout.example') in Jquery code?

So if i have a small layout stored in example.blade.php, How do i use it in jquery ?
I want to include certain elements such as textboxes when a particular radio button is checked otherwise not.
Example:
$("document").ready(function(){
if ($("#role").prop( "checked")) {
$("#content").html(#include('layouts.nav'));
}
else
{
$("#content").html('');
}
});
The above code does not work so please provide some solution.
You can not do that. #include() is Blade and will be interpreted by PHP while JS runs in the browser. The Blade directives are already interpreted by PHP when the code hits the browser
You can create a hidden div in your view and then use jquery to get it's html content, here is an example:
<div class="layouts-nav" style="display:none;">
#include('layouts.nav')
</div>
<script>
$("document").ready(function(){
if ($("#role").prop( "checked")) {
var layoutNav = $('#layouts-nav').html();
$("#content").html(layoutNav);
}
else
{
$("#content").html('');
}
});
<script>

hide div if there is no paragraphs

So I have several divs that i assigned a class to. Each div has a header. The contents underneath each header are dynamically generated via php. Certain times of the year these divs contain no information but the header still displays. I want to hide the divs that do not have any paragraphs inside of them I cannot quite get them to work and I have a feeling it has to do with the paragraphs being generated by php.
EXAMPLE:
<div class="technology_connected article_headers">
<h3>TECHNOLOGY CONNECTED</h3>
<?php echo $tools->article_formatter($articles, 'Technology Connected'); ?>
</div>
Here is my Jquery code.
$(document).ready(function() {
$(".article_headers").each(function() {
if ($(this).find("p").length > 0) {
$('.article_headers').show();
}
});
});
Try this:
$(document).ready(function() {
$(".article_headers").each(function() {
if ($(this).find("p").length > 0) {
$(this).show();
}else{
$(this).hide();
}
});
});
DEMO
As noted by #JasonP above, this really should be done server side. However, since you do want it done server side, you can simplify the process greatly. Generate the data server side as you're doing. Make sure all <div> tags are visible. Then in your JavaScript use the following selector:
// Shorthand for $(document).ready(function() { ... });
$(function () {
$('.article-headers:not(:has(p))').hide();
});
The selector above targets all elements with the class .article-headers that do not contain a <p> tag and hides them.
JSFiddle demoing the above as a toggle button to show or hide the no paragraph sections.

Custom simple like button (not facebook)

I'm looking for the easiest way to add a simple like button to my site. Basically, a button that, when clicked - changes to a new graphic (letting you know you clicked it), can't be clicked again, and sends to a php script so the server knows what you liked.
I thought a good technique might be putting a like button inside an iframe so you can click it and the php page could just echo 'thanks for liking this' - but the problem is the iframe has to have a source. I don't want a ton of external files loading into each page. Is there any way I could just have an iframe tag and put HTML inside it without it being external?
Hopefully this makes sense. I do not know your server structure, so its hard for me to build a complete example but this should get you off your feet!
File: Index.php
// query the database and check to see if there is a record for this content piece and ip address
// select count() from statistics where contentId='1' and ip='0.0.0.0' limit 1;
$contentLiked = false;
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script src="site.js"></script>
</head>
<body>
<? if(!$contentLiked): ?>
like
<? else: ?>
unlike
<? endif ?>
</body>
</html>
File: site.js
$(document).ready(function() {
$('.likeButton').click(function() {
var contentId = $(this).attr('rel');
var link = this;
if(!$(link).hasClass('liked')) {
$.post("like.php", { Id: contentId }).done(function(data) {
if(data) {
$(link).addClass('liked');
$(link).html('liked');
}
});
}
});
});
File: like.php
<?
$contentId = $_POST['Id'];
$timestamp = time();
$usersIP = $_SERVER['REMOTE_ADDR'];
// php code to update the database
// insert: contentId, timestamp, ip address
// if injected then echo / print true;
echo 'true';
?>
You should use jquery animate. It allows you to create an animation on a HTML element that you choose with jquery.
With Jquery, using the 'click' event, you can use the animate effect, and have something like this:
$("#my-button").click(function(){
$(this).animate({
height: 'toggle'
}, 500, function(){
$(this).animate({
height: 'toggle'
}, 500);
});
});
Please see the following example of doing that

Code works in jsfiddle but doesn't work when I put all the code into my website

My goal is to have a button on each side of my iframe (which contains a calendar) which toggles back and forth between calendar #1 and calendar #2 in a single iframe.
Any suggestions?
|arrowLeft| |-----Iframe-------| |arrowRight|
The code works in jsfiddle but doesn't work when I put all the code into my website.
Why is that?
HTML:
<p id="toggle">
<span> Left </span>
<span> </span>
</p>
<div id="left"> <iframe>LEFT CONTENT</iframe> L</div>
<div id="right"> <iframe>RIGHT CONTENT</iframe>R </div>
<p id="toggle">
<span></span>
<span> Right </span></p>
CSS:
#right { display:none; }
Script:
$('#toggle > span').click(function() {
var ix = $(this).index();
$('#left').toggle( ix === 0 );
$('#right').toggle( ix === 1 );
});
Since you say you have loaded jquery..
Probably your onclick setter (the jquery code) is run before the document is loaded (and as such there are no elements in document.body at that moment to set).
In jsfiddle ('No-Library' pure JS) code is wrapped (by default) in:
window.onload=function(){
// your code here
};
That should already do the trick.
This is what jsfiddle does when you select the (default) option 'onLoad' in the options panel on the left, under "Frameworks & Extensions".
If you would select 'onDomready' then your code would (currently) be wrapped in a function called VanillaRunOnDomReady, like this:
var VanillaRunOnDomReady = function() {
// your code here
}
var alreadyrunflag = 0;
if (document.addEventListener)
document.addEventListener("DOMContentLoaded", function(){
alreadyrunflag=1;
VanillaRunOnDomReady();
}, false);
else if (document.all && !window.opera) {
document.write('<script type="text/javascript" id="contentloadtag" defer="defer" src="javascript:void(0)"><\/script>');
var contentloadtag = document.getElementById("contentloadtag")
contentloadtag.onreadystatechange=function(){
if (this.readyState=="complete"){
alreadyrunflag=1;
VanillaRunOnDomReady();
}
}
}
window.onload = function(){
setTimeout("if (!alreadyrunflag){VanillaRunOnDomReady}", 0);
}
Note that this eventually still ends up in a window.onload like the 'onLoad' option.
If you'd load library JQuery 1.9.1 then things change (a little).
The option 'onLoad' then wraps your code like this:
$(window).load(function(){
// your code here
});
Note that this is essentially still the the same as the first option in this answer, but then in the JQuery way.
If you'd select the option 'onDomready' (whilst the JQuery library is loaded in JSFiddle), then your code would be wrapped in:
$(function(){
// your code here
});
As ErikE pointed out in the comments below, since you already load and use JQuery you might also want to use yet another JQuery way:
$(document).ready(function() {
// your code here
});
Finally as ErikE also pointed out in his comment to your question (a serious problem I overlooked), id's are meant to be unique. Whereas you gave to both paragraphs the id "toggle".
You should instead give them the class "toggle" and select the elements by class to assign the onclick function.

How can PHP access the 'style' properties of a div?

So my PHP webiste generates DHTML output that looks like the following:
<div class="toggle-ctrl" onclick="toggleMenu();">
click me to toggle menu
</div>
<div id="site-menu">
<ul>
<li>opt 1</li>
<li>opt 2</li>
</ul>
</div>
<p>Link to Myself</p>
And of course, when clicked, the first div calls some JavaScript which toggles the visibility of the site-menu
function toggleMenu() {
var navigation_pane = document.getElementById('site-menu').style;
if ( navigation_pane.display == 'none' )
navigation_pane.display = 'block';
else
navigation_pane.display = 'none';
}
All this works fine. It's clicking on the link which is bothering me right now. Clicking it (of course) creates a new http request, and my PHP engine re-generates the page again.
The problem occurs when the visibility of the site-menu is 'none'. The PHP engine doesn't know that the menu is hidden, so it generates the same-html again, and the browser places the menu back in front of the surprised-looking user.
The question therefore, is how do I inform PHP (or how can PHP go to check) what the status of the site-menu's visibility is, before it goes to re-generate the page?
There are at least two options other than sending the menu state to the PHP script.
Use AJAX to load just part of the page. If you don't reload the menu, you don't need to re-initialize its style. Before going down this path, examine whether AJAX is suitable. If you implement this solution, don't break browser functionality.
Modern browsers support a storage mechanism. Store the menu state in localStorage when it changes, and set the menu state when the page loads. To support older browsers, you can create an API that uses web storage when available and cookies when not (jQuery.Storage does this).
Menu.js:
/* implementation of Storage, Class and addEventListenerTo left as
an exercise for the reader.
*/
var Menu = {
init: function(id, toggleId) {
if (! toggleId) {
toggleId = id + '-toggle';
}
var toggler = document.getElementById(toggleId),
menu = document.getElementById(id);
menu.toggler = toggler;
/* addEventListenerTo should call the browser-supplied event subscriber
method (e.g. addEventListener or attachEvent)
*/
addEventListenerTo(toggler, 'click',
function(evt) {
Menu.toggle(id);
});
if (! Storage.exists(id+'-open')) {
Storage.set(id+'-open', true);
}
if (Storage.get(id+'-open')) {
Menu.open(id);
} else {
Menu.close(id);
}
},
toggle: function(id) {
var menu = document.getElementById(id);
Class.toggle(menu, 'open closed');
if (Class.has(menu, 'open')) {
menu.toggler.firstChild.nodeValue = 'close menu';
Storage.set(id + '-open', true);
} else {
menu.toggler.firstChild.nodeValue = 'open menu';
Storage.set(id + '-open', false);
}
},
setState: function (id, toAdd, toRemove) {
var menu = document.getElementById(id);
Class.remove(menu, toRemove);
Class.add(menu, toAdd);
},
open: function(id) {
this.setState(id, 'open', 'closed');
},
close: function(id) {
this.setState(id, 'closed', 'open');
}
};
some CSS file:
.closed { display: none; }
page:
<div id="site-menu-toggle" class="toggle-ctrl">close menu</div>
<div id="site-menu" class="open">
<ul>
<li>opt 1</li>
<li>opt 2</li>
</ul>
</div>
<p>Link to Myself</p>
<script type="text/javascript">
Menu.init('site-menu');
</script>
You can play with a live version of the Menu.js approach on jsFiddle. Using jQuery, you can do away with Menu.js, resulting in a much more succinct implementation:
<script type="text/javascript">
$('#site-menu-toggle').click(function (evt) {
var $menu = $('#site-menu');
$menu.toggleClass('open close');
$.Storage.set('site-menu-state', $menu.attr('class'));
if ($menu.hasClass('open')) {
$('#site-menu-toggle').text('close menu');
} else {
$('#site-menu-toggle').text('open menu');
}
});
$(function() {
var state = $.Storage.get('site-menu-state');
if (! state) {
$.Storage.set('site-menu-state', $('#site-menu').attr('class'));
} else {
$('#site-menu').attr('class', state);
}
});
</script>
There's a jFiddle for the jQuery menu state implementation that you can play with.
Since differences in the menu state don't conceptually make for different resources, it doesn't matter whether having the menu open or closed is bookmarkable or affected by history.
NB. don't use the text "click me", it's too verbose and redundant (what other action is there? Affordances should be implicit.). Instead, you can use a graphic to indicate open/close, or simply say "open menu"/"close menu".
The question therefore, is how do I inform PHP (or how can PHP go to
check) what the status of the site-menu's visibility is, before it
goes to re-generate the page?
It can't. By the time the HTML is delivered to the browser, PHP is no longer in the picture. The only way you could make PHP aware of this would be to send a parameter in the URL indicating the menu is hidden, or set a cookie and have the cookie indicate visibility of the object. Then PHP can check for the presence of this value and set the visibility of the div when it renders it.
You could accomplish this in a number of ways, for example:
Use document.cookie to set the cookie in your toggleMenu function.
Use ajax to notify PHP in the toggleMenu function and have PHP set a cookie or session value
Append a flag to the link indicating the visibility of the menu from the toggleMenu function.
Actually, there are several types of answers to your question.
While it may sound there's no way to do what you want, there are, in fact, many ways.
Cookies
The obvious. Cookies can be accessed by javascript as well as PHP. Just modify the cookie whenever the menu is shown/hidden through javascript (there's the excellent jQuery cookie plugin).
Form input
If you are submitting a form, simply have a hidden input keep the value of the menu's visibility:
<input type="hidden" name="menu-visibility" value="0"/>
Again, you need javascript to keep this input updated.
Update relevant parts of the page
This is the hip & leet new trend. Well, actually, it's been there for some 6 years or so. Basically, don't submit anything and don't reload the page. Update the parts of the page that actually need updating, through AJAX.
Local Storage
As #outis mentioned, today browsers have something similar to cookies, except they keep it for themselves (hence locally). It's a pretty new feature, to be honest, I wouldn't trust it considering there are better ways to accomplish what you need.
In addition to drew010's suggestions: You could also create a form with a hidden input element named, let's say, 'menu_status' whose value gets set by toggleMenu(). Then when you click on your link, use javascript to POST or GET the form. Then you read the value server-side with php using either $_POST["menu_status"] or $_GET["menu_status"], depending on the form method.
UPDATE: Something like this:
<form name="session_form" action="" method="POST">
<input type="hidden" name="menu_state" value="block">
</form>
<?php $menu_state = isset($_POST["menu_state"]) ? $_POST["menu_state"] : "block"; ?>
<div id="site-menu" style="display:<?php echo $menu_state; ?>">
<ul>
<li>opt 1</li>
<li>opt 2</li>
</ul>
</div>
<p>Link to Myself</p>
function toggleMenu() {
var navigation_pane = document.getElementById('site-menu').style;
if ( navigation_pane.display == 'none' )
navigation_pane.display = 'block';
else
navigation_pane.display = 'none';
document.forms.session_form.menu_state.value = navigation_pane.display;
}
EDIT: Using jQuery ajax could involve something like this:
<div class="toggle-ctrl">click me to toggle menu</div>
<?php $menu_state = isset($_POST["menu_state"]) ? $_POST["menu_state"] : "block"; ?>
<div id="site-menu" style="display:<?php echo $menu_state; ?>">
<ul>
<li>opt 1</li>
<li>opt 2</li>
</ul>
</div>
<p>Link to Myself</p>
$("div.toggle-ctrl").click(function(){
$("#site-menu").toggle();
});
$("#go").click(function(e) {
e.preventDefault();
var menu_state = $("#site-menu").css("display");
$.post("", {menu_state:menu_state}, function (response) {
$("html").html(response);
});
});
Or without using ajax or a form, just append a parameter to the link and use $_GET instead of $_POST in your php:
$("#go").click(function(e) {
e.preventDefault();
var menu_state = $("#site-menu").css("display");
document.location.href = "index.php?menu_state=" + menu_state;
});
This seems to me the simplest solution.
I know it's not cool to answer your own question, but another possible solution occurred to me last night, and it only requires 1 new line of code to be written (sort of).
The first part of the solution has already been implicitly suggested by many of you. Modify the JavaScript to write to a cookie:
function toggleMenu() {
var navigation_pane = document.getElementById('site-menu').style;
if ( navigation_pane.display == 'none' )
navigation_pane.display = 'block';
else
navigation_pane.display = 'none';
document.cookie = "menu_vis=" + navigation_pane.display; // +1 line of code
}
Now, what are the possibilities if your CSS file just so happens to be a PHP file in disguise? my_css.php would look something like this:
<?php
header("Content-type: text/css");
?>
#site-menu {
display: <?php echo isset($_COOKIE['menu_vis']) ? $_COOKIE['menu_vis'] : 'block'; ?>; /* line of code modified, but not added! */
}
Tested this morning, and it works.
I find it a neat solution, because it means that I don't have to bend my PHP or HTML design around any presentational concerns.
--
I appreciate that there are more "encompassing" solutions out there. If I was a better JavaScript developer, (or made use of jQuery or the like), I could build more complicated classes which could then be applied more generally to other HTML elements. I may come back to investigate such solutions later, but that's just not where my project is at the moment.
Thank you everyone for all your replies. I wouldn't have found this solution without bouncing these ideas off you guys.

Categories