So, im building a website and i want to give a "active" class to my menu depending on the page the user access. I'm new to Jquery, so i don't know if this is the best way to do it, or if there is a better code to achieve what i want.
Currently my main structure is:
Header
Navbar where is the menu i'm giving the active class
Content called with the php code
Footer
The only thing i need to change when loading another page, is the content it doesn't really matter if it's php or ajax. Actually, i know ajax can do it more dynamic, but i just don't know how to do it yet.
So this is the code i made to give a active class to my li a element correspondent to the webpage:
php to load page:
<?php
if(!empty($_GET['p'])){
if (file_exists ($_GET['p'].".php")){
include($_GET['p'].".php");
} else include ("erro.php");
} else include("content/home.php");
?>
Jquery to give it a class:
$(document).ready(function() {
var home = $('a[href$="home"]'),
servicos = $('a[href$="servicos"]'),
advogados = $('a[href$="advogados"]'),
escritorio = $('a[href$="escritorio"]'),
noticias = $('a[href$="noticias"]'),
contato = $('a[href$="contato"]');
$(function() {
var loc = window.location.href;
if(/home/.test(loc)) {
$('.navbar li').find(home).addClass('active');
} else if(/servicos/.test(loc)) {
$('.navbar li').find(servicos).addClass('active');
} else if(/advogados/.test(loc)) {
$('.navbar li').find(advogados).addClass('active');
} else if(/escritorio/.test(loc)) {
$('.navbar li').find(escritorio).addClass('active');
} else if(/noticias/.test(loc)) {
$('.navbar li').find(noticias).addClass('active');
} else if(/contato/.test(loc)) {
$('.navbar li').find(contato).addClass('active');
};
});
});
Is there another way or a best/easy way to do it?
Since you are using jQuery, take a look at jQuery's load function. Using load you can specify an html element(usually div) in which you will load pages, like this:
$("#myDiv").load("/my/page/folder/page.html");
To handle the menu you will need this piece of code:
// Select all menu links and attack event handler on them
$(".navbar li a").on("click", function(event){
// This stop the link from loading into the browser tab(we want it to load in a div)
event.preventDefault();
// Remove any previous highlight
$(".active").removeClass("active");
// Add highlight to the menu we clicked
$(this).addClass("active");
// Load the link into "myDiv"
$("#myDiv").load(this.href);
});
You may need to tweak around with this code, i haven't tested it, but this is how it works in general.
Note: in the pages you load, using jQuery's load function, you need only the content and not the whole HTML structure.
If you want to load only part of the page you can do so like this:
$("#myDiv").load("/my/page/folder/page.html #container");
Your method of page's inclusion is extremely dangerous as I can basically access any php file on your server.
I would recommend to use an array that contains all the allowed pages, like:
$pages = array('home', 'about', 'contact');
$current_page = '';
//Default page
if(!isset($_GET['p']) || empty($_GET['p'])){
$current_page = 'home';
}
Now, when you print the menu, you can do something like this:
foreach($pages as $page){
echo '<li><a href=""';
if($page == $current_page) echo ' class="active"';
echo '></a></li>';
}
You can expand your array of pages to contain also title, meta tags, etc.
For instance:
$pages = array(
'home' => array('title' => 'Home', 'meta_description' => 'Bla Bla Bla'),
'about' => array('title' => 'About Us', 'meta_description' => 'Bla Bla Bla')
);
Related
I am creating menu, and if the specific page is current , menu item assign different color.
Simple situation.
So i do :
<?php $page = $_SERVER['SCRIPT_NAME'];?>
<?php if ($page == "index.php"){ echo "class='active'";} ?> >
Home
That works for every page, except one.
I tried some other options suggested on stackoverflow
How to get current PHP page name , like :
echo basename($_SERVER['PHP_SELF']); returns file_name.php
and
if(basename(__FILE__) == 'file_name.php') {
//Hide
} else {
//show
}
Still does not work.
$pagename = basename($_SERVER['PHP_SELF']);
if($pagename=='index.php'){
echo "class='active'";
}
According to the data you supplied I suggest to use client-side solution instead of server-side solution. I mean that you use javascript.
This is may be done as follows:
<ul id="menu">
<li>Home</li>
<li>About</li>
<li>Any Other</li>
</ul>
<script>
function setCurrentNavLink(id){
nav = document.getElementById(id);
links = nav.getElementsByTagName('a');
for (i = 0; i < links.length; i++){
if (links[i].href == location.href){
links[i].className = 'current';
break;
}
}
}
setCurrentNavLink('menu');
</script>
Check this demo: http://jsbin.com/tomid/1
Sorted. The problem was in JQuery , thats operates Tabs on the current page.
$(document).ready(function(){
// When a link is clicked
$("a.tab").click(function () {
// switch all tabs off
$("ul.tabs li a.active ").removeClass("active");
//$(".active ").removeClass("active");
// switch this tab on
$(this).addClass("active");
//$(".collapse navbar-collapse").addClass("active");
// slide all content up
$(".content").slideUp();
// slide this content up
var content_show = $(this).attr("title");
$("#"+content_show).slideDown();
});
});
The mistake was in 3rd section, where Class .active was removed from Every object. Including header. Therefore header did not appear as active.
Instead of that, class .active had to be removed only from Tabs tab.
I am working on making a dynamically loaded website using some php code to swap out content from various other files. While on top of that I am using jquery to beautify this swap out.
Relevant PHP:
<?php
// Set the default name
$page = 'home';
// Specify some disallowed paths
$disallowed_paths = array('js.php','css.php','index.php');
if (!empty($_GET['page'])){
$tmp_page = basename($_GET['page']);
// If it's not a disallowed path, and if the file exists, update $page
if (!in_array($tmp_page, $disallowed_paths) && file_exists("{$tmp_page}.php"))
$page = $tmp_page;
}
// Include $page
if(!file_exists("$page.php")){
$page = 'home';
}
else{
include("$page.php");}
?>
Relevant jquery:
$(function (a) {
var $body = $('body'),
$dynamo = $('.dynamo'),
$guts = $('.guts');
$body.fadeIn('slow');
if (history.pushState) {
var everPushed = false;
$dynamo.on('click', 'a', function (b) {
var toLoad = $(this).attr('href');
history.pushState(null,'',toLoad);
everPushed = true;
loadContent(toLoad);
b.preventDefault();
});
$(window).bind('popstate', function () {
if (everPushed) {
$.getScript(location.href);
}
everPushed = true;
});
} // otherwise, history is not supported, so nothing fancy here.
function loadContent(href) {
$guts.hide('slow', function () {
$guts.load(href, function () {
$guts.show('slow');
});
});
}
a.preventDefault();
});
What is happening is when I link to a page using ?page=about it will work but it will instead of just swapping out the content it will load the entire page including the content inside the dynamically loaded div.
If I were to link straight to about.php it would work beautifully with no fault whatsoever, but anybody who wanted to share that link http://example.com/about.php would get just the content with no css styling.
If I were to change the jquery in "loadContent" to:
$guts.load(href + ' .guts', function () {
EDIT 1:
, ' .guts'
to
+ ' .guts'
It would then work but any script, java, jquery, or the like would not work because it gets stripped out upon content load.
check out http://kazenracing.com/st3
EDIT 2:
It also seems to be that the site does not work properly in the wild either.
No background and none of the icons show up, but it still gets the general problem across.
I can fix that myself, it will just take some time. For now my focus is on the recursion problem.
EDIT 3: Site no longer needs to be worked on, problem never solved but we are letting that project go. So the link no longer is a valid URL.
In my website authors (users) can mark posts as favorite.
It works this way:
if ($favinfo == NULL || $favinfo == "") {
$favicon = "ADD"; .
}
else {
$favicon = "REMOVE";
}
Its suposed to look dynamic, it works, when user click ADD, it adds the post to his favorites and reload the page with the REMOVE link.
The problem is its not really dynamic it reloads all the page.
How can i only reload that link (wich is inside a div)?
I know i have to use ajax, jquery, etc, but i tried some examples found here in S.O. but no success.
$('a').on('click', function(e){
// the default for a link is to post a page..
// So you can stop the propagation
e.stopPropagation();
});
Including this stop you page from reloading your entire page
If you want it to be dynamic, you will need to use AJAX. jQuery has ajax support which makes this really easy. If you are not familiar with ajax or javascript you should read up on it first.
PHP
if ($favinfo == NULL || $favinfo == "") {
$favicon = "<a class=\"fav-btn\" data-id=\"".$articleinfo['id']."\" data-action=\"add\" href=\"".$siteurl."/author/favorites.php"\">ADD</a>"; .
}
else {
$favicon = "<a class=\"fav-btn\" data-id=\"".$articleinfo['id']."\" data-action=\"remove\" href=\"".$siteurl."/author/favorites.php"\">REMOVE</a>";
}
JavaScript
$('a.fav-btn').on('click', function(e){
var $this = $(this), // equates to the clicked $('a.fav-btn')
url = $this.attr('href'), // get the url to submit via ajax
id = $this.attr('data-id'), // id of post
action = $this.attr('data-action'); // action to take on server
$.ajax({
url: url+'?'+action+'='+id
}).done(function(){ // once favorites.php?[action]= is done...
// because this is in .done(), the button will update once the server has finished
// if you want the link to change instantly and not wait for server, move this outside of the done function
if(action === 'add'){
$this.attr('data-action', 'remove').html('REMOVE'); // update the button/link
}else{
$this.attr('data-action', 'add').html('ADD');
}
})
return false; // prevent link from working so the page doesn't reload
}
If you are okay with using JQuery, you have some tools to accomplish this.
Have a structure / method of identifying your links.
You can have a click() listener on your add button that will call a JQuery $.post(url, callback) function.
In that callback function, you can have it update the corresponding DIV (that you defined in #1) with a 'remove' link. i.e if you identify the DIV by ID, you can retrieve it via $('#id') and then update that object.
The same idea can apply with the 'remove' link that you add.
So, generally...
<button id="add">Add</button>
<div id="links"> ...</div>
<script>
$('#add').click(function() {
$.post('your url',
function(data) {
var links = $('#links');
// update your links with 'remove' button, etc
}
);
});
</script>
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".
I am a newbie in Javascript and I a trying to accomplish something certainly obvious, but I do not seem able to do it right.
I have a menu on the left, and there's one particular link which should load an external .php page in a certain destination div.
The .php page includes PHP statements like
echo "<script> blah blah blah </script>;"
When I load the page these scripts are not executed.
I try to avoid using jQuery, but even with jQuery I do not seem able to make it work.
Could someone tell me how I should do it?
Calling page:
<script>
//jQuery method, jQuery loaded
function loadPage(destId, pagetoload){
$('<div id="info" />').load(pagetoload, function() {
$(this).appendTo(destId)
.slideDown(3000);
});
return false;
}
</script>
<a id='assigncusts' href="javascript:loadPage('others', 'players.php')">Assign</a>
The called .php page:
<?PHP
function createDropdown($arr, $code_cust, $log) {
echo "".$arr[$log]."";
foreach ($arr as $key => $value) {
if ($key != $log){
echo '<option value="'.$value.'">'.$value.'</option>';
}
}
echo '</select>';
}
?>
//In a while loop:
echo "<tr><td>".$row['player_name']."</td><td>";
createDropdown($users_array, $row['player_name'], $row['Login']);
echo "</td></tr>\n";
Thank you in advance
Create your div in html, then:
$(document).ready(function() {
$("#info").load("yourscript.php");
});
Your passing the string 'others' to destId and doing $(this).appendTo(destId) -- it's basically do [info div].appendTo('other') searching for the TAG "other"
Instead try doing:
$('#info').hide().load(pagetoload, function() {
$(this).show().slideDown(3000);
});
Or you might want $('#' + divId) it depends on where you want the page loaded to. The matched element before .load() is where the content will be automatically placed into.