Site navigation - php

I am making a website in HTML, CSS and PHP. I have a navigation on the top of the page, and when you hover your mouse over the buttons, they light up.
Now, when you click a button and go to that particular page, I would like the button for that page to be lit up, indicating that you are on that page. How would I go about doing this? Defining a variable on each page and then checking for it in the menu is not possible, as I have a forum on the site too, and that would require me to define a variable on each page.
EDIT
I managed to solve my problem. As it turns out, I could just define the pages, and for the forum I could do the same in the settings file that the forum used.
In my navigation, I just check what the current page is:
<li id="news"><a <? if(PAGE == "INDEX") print 'class="active"'; ?> href="/">News</a></li>

Add a class (or ID) to the body tag, like so:
<body class="Page1">...</body>
Then, in your CSS you can say something like:
.Page1 menu li, menu li:hover {...}

I'm not sure how to check for the current page in PHP - though, that would be ideal.
If you want to rely on JavaScript, though, I have used this function in the past successfully:
function highlightPage(id){
//make sure DOM methods are understood
if(!document.getElementsByTagName) return false;
if(!document.getElementById) return false;
if(!document.getElementById(id)) return false;
var nav = document.getElementById(id);
var links = nav.getElementsByTagName('a');
for (var i=0; i < links.length; i++){
var linkurl = links[i].getAttribute('href');
var currenturl = window.location.href;
//indexOf will return -1 on non-matches, so we're checking for a positive match
if (currenturl.indexOf(linkurl) != -1) {
links[i].className = "here";
var linktext = links[i].lastChild.nodeValue.toLowerCase();
document.body.setAttribute("id",linktext);
}
}
}
And to load the function at the load of the page:
function addLoadEvent(func){
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function(){
oldonload();
func();
}
}
}
addLoadEvent(function(){
highlightPage('navigation');
});
This assumes that your navigation has the ID of "navigation", but you can change it to whatever you want. The function simply attaches a class of "here" to the current navigation item.
This script comes from Jeremy Keith's "DOM Scripting".

Related

How to open a new tab with the content and the container together if using ajax load to get the content?

I have a php page with a nav and a content div. When I choose an option in the nav, the content is modified by loading another php file inside it. For this I use ajax with load function. My problem is that if I right click and select open in a new tab or a new window, evidently, only the content is open in the tab.
I know that I can have the whole page (container + content) in each php file and load only the content div, but I think there is no much sense in this.
Is there any way to get the container along the content in the new tab?
I already had a similar situation, the tabs have pages, and the menu was in the top page. you can apply this solution:
This logic will work with iframe, if you are using divs, you can adjust for this:
main page with the nav menu, here you need apply some logic like this:
<script>
//Object to get values of URL (GET)
var request = {
get get() {
var vars = {};
if (window.location.search.length !== 0)
window.location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
key = decodeURIComponent(key);
if (typeof vars[key] === "undefined") {
vars[key] = decodeURIComponent(value);
}
else {
vars[key] = [].concat(vars[key], decodeURIComponent(value));
}
});
return vars;
},
getParam: function (param) {
var vars = request.get;
if (vars[param] != undefined) {
return vars[param];
} else {
return null;
}
}, getParams: function () {
return request.get;
}
};
//variable that defines if the client are in mainWindow
window.mainWindowFrame = true;
var tabName = request.getParam("tab");
console.log("tabName",tabName);
//call some function to reload the content of iframe or div to requested tab.
//if(tabName != null || tabName != ""){
//tabs.load(tabName) ....
//}
</script>
In the pages of content you need aplly this piece of code to reload the page if the menu are not present:
<script>
//name of this tab
var tabName = "someTab";
//check if the menu are present here
if(window.top.mainWindowFrame == undefined){
window.location.href = "mainpage.html?tab="+tabName;
}
</script>

jquery change content in php template from file with "pages" in

I've created a php template with variables library and what not all pulled into an index page I've created a basic script with fades the page in and out on load and have got that working the next thing I wanted to do is to use my navbar links to pull formatted content into the page (as I'm using foundation 4 framework) now the code I tried is as follows
$(document).ready(function() {
var hash = window.location.hash.substr(1);
var href = $('#nav li a').each(function(){
var href = $(this).attr('href');
if(hash==href.substr(0,href.length-5)){
var toLoad = hash+'.html #content';
$('#content').load(toLoad)
}
});
$('#nav li a').click(function(){
var toLoad = $(this).attr('href')+' #content';
$('#content').hide('fast',loadContent);
$('#load').remove();
$('#wrapper').append('<span id="load">LOADING...</span>');
$('#load').fadeIn('normal');
window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);
function loadContent() {
$('#content').load(toLoad,'',showNewContent())
}
function showNewContent() {
$('#content').show('normal',hideLoader());
}
function hideLoader() {
$('#load').fadeOut('normal');
}
return false;
});
});
the idea is that onclick it removes the content with the wrapper displays a loading gif and then loads the page content which is stored in the link referred to in the
but its not working is just reloading the whole page . . . . i have tried reading up and it says that you can use
You can extract from another page using the load method thus >$('#targetElement').load('page.htm #container') syntax.
and using the get function but im not to good at all this jquery is there a way I can do it in php or where am I going wrong with what I've done.
Try this....You were calling the load, and functions inside improperly...
$('#nav li a').click(function(){
var toLoad = $(this).attr('href')+' #content';
$('#content').hide('fast',loadContent);
$('#load').remove();
$('#wrapper').append('<span id="load">LOADING...</span>');
$('#load').fadeIn('normal');
//window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);
function loadContent() {
$('#content').load(toLoad,showNewContent);
}
function showNewContent() {
$('#content').show('normal',hideLoader);
}
function hideLoader() {
$('#load').fadeOut('normal');
}
return false;
});
When a user clicks a link the browser by default unloads the current page and loads the page indicated by that link.
You need to prevent the default behavior of the browser, in order to do this you need to call the .preventDefault() method on the click event that was triggered for that link.
$('#your-context').click(function(event) {
event.preventDefault();
/**
* the rest of your code here
*/
});

load page at its hash, then display the result directly without showing the index first

on http://zentili.koding.com i've got this javascript that loads the content of the linked menu item inside the main #content div of the index page, and applies an hash with the name of the loaded page minus the '.php', otherwise it loads the hash + '.php' if it's entered in the url. works very good. On other hand, the ENG/ITA entries add ?locale=lang_LANG inside the url, right before the hash, so that localization is also working fine. If you look well, you may notice that when you switch between ENG and ITA, the index-content appears just for one moment before going to the hash. I know this is because the page is first loaded, then taken to the hash but i was wondering if there some way for hiding the homepage and going directly to the hash location when it's loaded.
Here the code for my menu:
<script type="text/javascript">
$(document).ready(function() {
var hash = window.location.hash.substr(1);
var href = $('#menubar a.item').each(function(){
var href = $(this).attr('href');
if(hash==href.substr(0,href.length-4)){
var toLoad = hash+'.php';
$('#content').load(toLoad);
$("#menubar a.item").removeClass("current");
$(this).addClass("current");
}
});
$('#menubar a.item').click(function(){
window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-4);
var toLoad = $(this).attr('href');
$('#content').fadeOut('fast',loadContent);
function loadContent() {
$('#content').load(toLoad,'',showNewContent) }
function showNewContent() {
$('#content').fadeIn('fast'); }
$("#menubar a.item").removeClass("current");
$(this).addClass("current");
return false;
});
});
function goENG(){
var hash = window.location.hash;
var eng = '?locale=en_EN';
window.location.replace(eng+hash) ;
};
function goITA(){
var hash = window.location.hash;
var ita = '?locale=it_IT';
window.location.replace(ita+hash) ;
};
</script>
the functions goENG() and goITA() are called via onclick on the ENG and ITA a's. I hope to find some solution into this.
The page cannot directly go to the link. It will load in its natural order and then it will go to the hash. For what you want to achieve, there is a simple solution i believe.
Hide the main content div until the document loads. use css rule "visibility:hidden" for this
If there is any hash, load it and then make the content visible.
If there is no hash in url, make the content visible on dom load.
$(document).ready(function() {
var hash = window.location.hash.substr(1);
if ($('#menubar a.item').length > 0) {
var href = $('#menubar a.item').each(function(){
var href = $(this).attr('href');
if(hash==href.substr(0,href.length-4)){
var toLoad = hash+'.php';
$('#content').load(toLoad, function(){
$('#content').attr('visibility', 'visible');
});
$("#menubar a.item").removeClass("current");
$(this).addClass("current");
} else {
$('#content').attr('visibility', 'visible');
}
});
} else {
$('#content').attr('visibility', 'visible');
}
});
--UPDATE--
If you are setting #content as "visibility:hidden"
$('#content').attr('visibility', 'visible');
should always fire, else your #content div will be invisible. The trick here is to set it to visible after we are done with checking for hash. You can keep loading the content in the div and make it visible. Making the #content div visible need not be done after entirely loading the hash.

Use Jquery to update a PHP session variable when a link is clicked

I have several divs that a user can Minimize or Expand using the jquery toggle mothod. However, when the page is refreshed the Divs go back to their default state. Is their a way to have browser remember the last state of the div?
For example, if I expand a div with an ID of "my_div", then click on something else on the page, then come back to the original page, I want "my_div" to remain expanded.
I was thinking it would be possible to use session variables for this, perhaps when the user clicks on the expand/minimize button a AJAX request can be sent and toggle a session variable...IDK..any ideas?
There's no need for an ajax request, just store the information in a cookie or in the localstorage.
Here's a library which should help you out: http://www.jstorage.info/
Some sample code (untested):
// stores the toggled position
$('#my_div').click(function() {
$('#my_div').toggle();
$.jStorage.set('my_div', $('#my_div:visible').length);
});
// on page load restores all elements to old position
$(function() {
var elems = $.jStorage.index();
for (var i = 0, l = elems.length; i < l; i++) {
$.jStorage.get(i) ? $('#' + i).show() : hide();
}
});
If you don't need to support old browsers, you can use html5 web storage.
You can do things like this (example taken from w3schools):
The following example counts the number of times a user has visited a
page, in the current session:
<script type="text/javascript">
if (sessionStorage.pagecount) {
sessionStorage.pagecount=Number(sessionStorage.pagecount) +1;
}
else {
sessionStorage.pagecount=1;
}
document.write("Visits "+sessionStorage.pagecount+" time(s) this session.");
</script>
Others have already given valid answers related to cookies and the local storage API, but based on your comment on the question, here's how you would attach a click event handler to a link:
$("#someLinkId").click(function() {
$.post("somewhere.php", function() {
//Done!
});
});
The event handler function will run whenever the element it is attached to is clicked. Inside the event handler, you can run whatever code you like. In this example, a POST request is fired to somewhere.php.
I had something like this and I used cookies based on which user logged in
if you want only the main div don't use the
$('#'+div_id).next().css('display','none');
use
$('#'+div_id).css('display','none');
*Here is the code *
//this is the div
<div id = "<?php echo $user; ?>1" onclick="setCookie(this.id)" ><div>My Content this will hide/show</div></div>
function setCookie(div_id)
{
var value = '';
var x = document.getElementById(div_id);
var x = $('#'+div_id).next().css('display');
if(x == 'none')
{
value = 'block';
}
else
{
value = 'none';
}
console.log(div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/")
//alert(x);
document.cookie = div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/";
}
function getCookie(div_id)
{
console.log( div_id );
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==div_id)
{
return unescape(y);
}
}
}
function set_status()
{
var div_id = '';
for(var i = 1; i <= 9 ; i++)
{
div_id = '<?php echo $user; ?>'+i;
if(getCookie(div_id) == 'none')
{
$('#'+div_id).next().css('display','none');
}
else if(getCookie(div_id) == 'block')
{
$('#'+div_id).next().slideDown();
}
}
}
$(document).ready(function(){
get_status();
});
Look about the JavaScript Cookie Method, you can save the current states of the divs, and restore it if the User comes back on the Site.
There is a nice jQuery Plugin for handling Cookies (http://plugins.jquery.com/project/Cookie)
Hope it helps
Ended up using this. Great Tutorial.
http://www.shopdev.co.uk/blog/cookies-with-jquery-designing-collapsible-layouts/

Pop-Up Window on page load

I need to have a pop-up window displayed when a page loads. What's happening is this. After an order is placed the user is redirected to their index page (main log-in page for the account) when they are redirected to the index page, I need a pop-up window to display on the page load that says something like "Your order for $variable has been saved". The $variable is defined on the previous page (where they are coming from) and I need that to carry over so I can display it in the pop-up box. Then once they click on "Ok" in the pop-up box, they are at the main page like always.
I have used a java popup box before on this project, but I am unsure of how to do one with these requirements. If there are any other/better ways to do this I am open to ideas. The layout of how this needs to work is below:
Client is logged into their account -> Order.php Page (Place an order) -> redirected to their member-index.php page (Pop-up needs to load on page load, and only when it comes from the order.php page)
Thanks!
Well from what I understand this would be the best match for you.
On previous page save a cookie (source http://www.quirksmode.org/js/cookies.html).
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(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;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
createookie("prevData", prevData, 30);
Then on the page you want the popup to appear (I suggest using an alert) (Note: you need the cookie code available on this page as well):
var prevData = readCookie("prevData");
if(prevData != null){
alert("Your order for " + prevData + " has been saved");
eraseCookie("prevData");
}
this could be in <body onLoad="code"> or simply a script in the header or anywhere really.
You can't force a popup page to open upon page load; browsers won't do that anymore. You can create a "fake" popup window by just positioning an element in the middle of the screen and decorating it so that it looks kind-of like a window. Various JavaScript libraries provide such "dialog" facilities.
`
function showpopup() {
var findString = /order.php/gi;
var referringURL = document.referrer;
var data = getQuerystring('variable');
if(referringURL.match(findString)) {
var windowprops = "left=50,top=50,width=500,height=500";
var preview = window.open("http://google.com", "preview", windowprops);
preview.document.write(data);
} else {
alert("Not order.php "+data);
}
}
function getQuerystring(key, default_) {
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
</script>
</head>
<body onload="showpopup()">
`
I assume you mean javascript. You may want to do this
<body onLoad="popup()">
Any code in the "onLoad" event should fire once the html is loaded.
If you are using Jquery, it should look like this
$("document").ready(function() {
popup();
});
You can pass your variable into the popup function.

Categories