Set a CSS class on the current page in a menu - javascript

I have a static website, but I have included different bits of the page (head, header, image slider, footer) by php's include function, to make the website manageable.
Now the problem is that the current page's name in the menu-bar must have selected="selected" to show the current page's name pressed in the front end.
I made a solution of giving every menu-item an id and than injecting the following code to end of every page and setting that page's id (the home button id selected in the example code).
<script type="text/javascript">
$(document).ready(function() {
$('#home').addClass('active');
});
</script>
Now the problem is that I must include this script in every page and to change the id to that page (eg in the above script I have pasted the code in the home page,
I wanna have a solution where I add only once chunk of the code to my footer.php and it automatically detect the current page and set the select="selected" for that menu-item.
Thank You all in advance...

In PHP, you can put the active class on your menu definition (if it's the same on every page), if you know the current page visited:
<ul>
<li <?php if($current_page == 'home') echo 'class="active"'; ?>>Home</li>
<li <?php if($current_page == 'blog') echo 'class="active"'; ?>>Blog</li>
<li <?php if($current_page == 'contact') echo 'class="active"'; ?>>Contact</li>
</ul>
and so on... You don't need Javascript for this (which is disable by some users). The only need is to get the $current_page variable, which can be based on the URL or the ID of the page, depending on your current website architecture.

The solution I discovered for my (specific) problem is,
I gave id(s) to all the menu-items, and those ids were the namesake of the related files (the files to which they'll link), for example the button which links to the home.php was given the id of "home" and the button which was linking to the profile.php was given the id of "profile" than included the following code in the footer
<?php
$php_self = $_SERVER['PHP_SELF'];
$basename = basename($php_self);
$id = basename($basename, ".php");
?>
<script type="text/javascript">
$(document).ready(function() {
$('#<?php echo $id; ?>.addClass('active');
});
</script>
( jQuery used, but if the website doesn't have jQuery already, than the document.getElementById must be used ).
Thank You all for Your time..

You can use js and php together:
$(document).ready(function(){
$("#<?=$current_page?>").addClass('active')
})
It's shorter than Maxime Lorant's code...
Or if your url is something like site.com/#home , this is the solution:
Get css id from url (without php/js)

Related

When I click a link, click a link on another page?

Really struggling to think of a solution to this problem. I have thought anchor links might help (using the #example on the end of a link to scroll to a position on the page) but not sure how best to implement them.
So on the homepage of my site I have a list of links, that correlate to tabs on another page.
The links on the homepage:
(What is e-Bate, What are rebates etc.)
Links
When you click one of the tabs on the other page, it activates a script which shows a certain div below:
Tabs
This is how the tabs are shown:
HTML:
<div class="page-links">
<ul>
<li>What is e-Bate?</li>
<li>What are rebates?</li>
<li>e-Bate features</li>
<li>How e-Bate works</li>
<li>Case studies</li>
</ul>
</div>
<div class="page-contents">
<div id="whatebate" class="hideshowdiv">
<?php echo CFS()->get('whatisebate'); ?>
</div>
<div id="whatrebate" class="hideshowdiv">
<?php echo CFS()->get('what_are_rebates'); ?>
</div>
<div id="ebatefeat" class="hideshowdiv">
<?php echo CFS()->get('e_bate_features'); ?>
</div>
<div id="howebate" class="hideshowdiv">
<?php echo CFS()->get('how_e_bate_works'); ?>
</div>
<div id="casestud" class="hideshowdiv">
<?php echo CFS()->get('case_studies'); ?>
</div>
</div>
jQuery:
jQuery(document).ready(function() {
jQuery(".page-contents div.hideshowdiv").hide();
// Show chosen div, and hide all others
jQuery("a").click(function (e)
{
//e.preventDefault();
jQuery("#" + jQuery(this).attr("class")).fadeIn().siblings('div.hideshowdiv').hide();
});
});
So when one of the links is clicked on the homepage, for instance, the 'What is e-Bate?' link, I want it to go to the other page, and click the corresponding tab, showing the content for that section. Is this possible? Thanks in advance.
This is very possible and you had half the equation with the anchors. Now you just need to write a small function to parse out the URL and check for a certain tag.
So something like this:
$(function(){
if (location.href.indexOf("#example") != -1) {
//This is where you put your function to show the tab
}
if (location.href.indexOf("#anotherexample") != -1) {
//This is where you put your function to show the tab
}
})
Well, if you can use PHP, then it is indeed pretty easy:
First, you need to create a PHP file, obvious with an input parameter, preference, two GET variables, the first one being the link of the page you want to visit and the second one can be, well that depends on how you want it to be, it can be a div id, or a div class or pretty much id of anything you want to click on the second site (You MUST KNOW which button/link you want to click on the second site)
Then first in your php code, store these two things into variables, Let us take $Path and $DivToClick,
Now, use this PHP function:
file_get_contents(path,include_path,context,start,max_length)
Here, the path is an required field, rest is all optional.. and then after that, echo a JQuery code which will do something like this
function ClickTheButton ()
{
$('#divId').click ();
}
Now, let me explain what we are doing here... First, you are sending link to a php script that get all the contents of that webpage and display it on my screen, and then when you are echo-ing the JQuery code, you are telling browser, that yes, this is the part of the page, execute it and simulate the action of click on this page, and thus the click action is simulated and things are done as per your need...
Hope this helps... :)

Load js when visible

I have a phtml page that has separate tabs
<div id="maintabs">
<ul id='mainTabNav'>
<li>Tab 1</li>
<li>Tab 2</li>
</ul>
<div id="maintabs-1">
<p><?php require_once VIEW_DIR."somewhere/tab1.phtml"; ?></p>
</div>
<div id="maintabs-2">
<p><?php require_once VIEW_DIR."somewhere/tab2.phtml"; ?></p>
</div>
</div>
Each tab/page has a header with a js source specific to the page like this
<script src="js/tab<num>.js"></script>
On the page load though each javascript file is loading. Is there a way to only load the js for the tab currently open? When a new tab opens then the js reloads with just the js for the current tab?
You could keep click events on each of the main tabs that would dynamically load the appropriate javascript using something like jQuery.getScript().
$('div[id^="#maintabs"]').click(function(e){
var tabno = $( this ).index();
$.getScript("js/tab"+tabno);
});
The pitfall I'd imagine with this is that you seem to want to have all the previous javascript to be washed away once the latest JS file was loaded. I'm not sure if that's doable or if you'll have side effects from it.
Also this could totally be done with vanilla JS but well, time savings.
Is there a way to only load the js for the tab currently open?
Since you are using PHP you could manage to pass the number of the current page to view. Pseudo-code
View::factory('templateView')
->set('page_number', $page_number)
The $page_number variable now holds the page number that can be used in your scripts with ease
<script src="js/tab<?php echo $page_number; ?>.js"></script>
...
<div id="maintabs">
<ul id='mainTabNav'>
<li>Tab 1</li>
<li>Tab 2</li>
</ul>
<div id="maintabs-".<?php echo $page_number; ?>>
<p><?php require_once VIEW_DIR."somewhere/tab".<?php echo $page_number; ?>.".phtml"; ?></p>
</div>
</div>
Can't you just put this:
<script src="js/tab<num>.js"></script>
into your somewhere/tab*.phtml?
Using pure Javascript, I believe it is possible if you are loading the page using AJAX.
This tutorial, http://code.tutsplus.com/tutorials/how-to-load-in-and-animate-content-with-jquery--net-26, demonstrates a way of loading another page (I call them child pages) into the main page (which I call the index page). As far as I can tell, if you include associated script tags in the child pages rather than the index page, then they are dynamic in that they load when the child page loads, and unloads when he child page unloads.
I have used a modified version of this tutorial in my own projects before, where I don't create the child pages with the same content as the index page as the tutorial shows, and instead use the whole child html file solely for only the child page's content.
Here’s an example based off your code:
indexScript.js :
/* When index.html is loaded and ready */
$(document).ready(function() {
/* Handels on-click of menu buttons */
$('#mainTabNav a').click(function(){
/* Getting the linked page */
var toLoad = $(this).attr('href');
/* Hiding content and calling loadContent function - creates animation*/
$('#contentDiv').hide('slow', loadContent);
/* Injects content to contentDiv div tag */
function loadContent(){
$('#contentDiv').load(toLoad, '', showNewContent);
}
/* Shows contentDiv div */
function showNewContent() {
$('#contentDiv').show('normal');
}
demonstratePageChange(); //For testing - you can remove this
/* In order to stop the browser actually navigating to the page */
return false;
});
/* Initial Load - load first child page by simulation of clicking on it*/
$('#maintabs_1').click();
});
/* To demonstrate the respective JS script is loaded as needed */
function demonstratePageChange() {
setTimeout(function(){
alert(testMsg); //Alerts the message from resepctive child page script
}, 3000);
}
index.html :
<!DOCTYPE html>
<html>
<head></head>
<body>
<div id='maintabs'>
<ul id='mainTabNav'>
<a id='maintabs_1' href='childA.html'><li>Tab 1</li></a>
<a id='maintabs_2' href='childB.html'><li>Tab 2</li></a>
</ul>
</div>
<div id='contentWrapper'>
<div id='contentDiv'></div>
</div>
</body>
<script type='text/javascript' src='jquery-2.1.1.min.js'></script>
<script type='text/javascript' src='indexScript.js'></script>
</html>
childA.html :
<div id='maintabs-1' class='contentBody'>
<script type='text/javascript' src='childAScript.js'></script>
Child A - Page
</div>
childAScript.js :
console.log("childAScript has been loaded");
var testMsg = "This is Child A";
childB.html :
<div id='maintabs-2' class='contentBody'>
<script type='text/javascript' src='childBScript.js'></script>
Child B - Page
</div>
childBScript.js :
console.log("childBScript has been loaded");
var testMsg = "This is Child B!!!!";
However, there are few things to consider using this method:
This particular method requires jQuery
This method doesn't support reload, you'd have to code that in. i.e. if you're on tab 2, you need store that fact and on refresh, point back to tab 2.
Local testing - as far as I can tell, only FF supports this when testing it locally. If you want to test this on Chrome for example, you'd need to upload this onto a server and only then will this work. This is due to the "XMLHttpRequest cannot load" error, if you try this locally.
I hope this helps and resolves your problem.
The use of AMD requirejs can do this also. It is possible to use pure js although I prefer AMD modules [i.e. define()]. For my apps depending on user actions, code is downloaded on the fly reducing load. An onclick event fires on the tab control calling requirejs and the script get downloaded and you call it. PsuedoExample:
<script type="text/javascript" src="require.js"></script>
$(document).ready(function() {
//Assuming using jQuery, use document.getElementById and what not otherwise
$('#maintabs-1').click(function(e) {
require(['/js/tabnum1.js'], function (tab1) {
tab1(doStuff);
});
});
}
Use a for loop for multiple tabs. Also, I try and put as much processing [sans data storage and server validation (obviously)] into the client side.

Overriding a javascript function in a Wordpress Child Theme

I am writing a simple Wordpress child theme.
There is a portfolio feature which uses flexslider to display the thumbnail from the most recent posts and, when clicking on them, it uses ajax to open up the post content in a div on the page.
I have written a category page based on this, which pulls out all the post categories and displays the thumbnail for the most recent post. However, when I click on the thumbnail, I need the page to go to a new page and not open up in the content div.
The problem is, I am reusing code which looks a bit like this:
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
<div class="flexslider">
<ul class="slides">
<li>
<a href="http://the-url-here">
<img src="<?php echo $thumb[0]; ?>" />
</a>
</li>
</ul>
</div>
<?php endwhile; ?>
But there is custom js within the parent theme global footer as follows which handles the opening up of the content, rather than redirecting to the location specified in the tag as usual.
$(".flexslider ul.slides li a").live('click', function(e){ e.preventDefault();
/*Set Function Variables */
$this = $(this);
$selectedthing = $this;
$postId = $($this).attr('data-url');
// and so on...
return false;
});
So, I need to disable the javascript attached to .flexslider ul.slides li a on that one single page template only, preferably without having to change the classes, as I think thatwould open up another can of worms around the css. Remember the theme loads the javascript in the footer, so I assume any changes Imake in the page template will be overridden in the footer.
Any ideas on the best way to approach this?
Just remove click live listener in your child theme. Add this javascript only for that specific page template.
$(".flexslider ul.slides li a").die('click');

Running html code when page is index.php

I need to run this code:
<font size='3'><b>
<li class="icon-home">
{L_INDEX} <!-- BEGIN navlinks -->
<strong>‹</strong>
{navlinks.FORUM_NAME}<!-- END navlinks -->
</li>
</b></font>
when the site is at index.php.
I have tried this:
<script type="text/javascript">
$(document).ready(function () {
if(window.location.href.indexOf("index.php") > -1) {
document.write('//the above HTML');
}
});
</script>
I can't use php because I am using a html file. The above code just gave me the board links and nothing else. I need the links to show as well as the rest of the page.
Thanks for your help.
Instead of document.write you should use a div or another element as a placeholder
if (location.href.indexOf("/index.php") > -1 ) {
document.getElementById("myPlaceHolder").innerHTML = '<font size="3"><b><li class="icon-home">{L_INDEX}<strong>‹</strong> {navlinks.FORUM_NAME}</li></b></font>';
}
In you HTML just add a div where you want to display the content.
<div id="myPlaceHolder"></div>
Be sure your script runs after the div tag otherwise document.getElementById("myPlaceHolder") returns null
Your code contains Smarty-code, which is kind of PHP. You propably can use
{if $smarty.server.REQUEST_URI == '/index.php'}
//Your HTML stuff here
{/if}
Edit:
I should propably mention that the {stuff} is smarty-code. It is like php-code inside an html file. It is interpreted by php.
That means, inserting it with javascript cannot possibly work, since PHP (and thus, Smarty) is interpreted on the server, while Javscript is executed on the client-side, that is, you home PC.

How to Toggle post content within a "post" title in a page?

I'm trying to give all "posts" title in a specific page. So If someone clicks on that posts, it's content must be toggle below the title and if some clicks the title again then the content must hide.
I solved half of the problem with the help of WP-Archives Plugin. And my page is looking like this Check this image here.. So these are
"Archives" titles links. And if someone clicks on it, it will take to the that.. I want the content in the particular posts to be in the same page in the form of toggle (in abvoe image..). Is it possible?
It sounds like you're describing an accordion function. Wordpress offers a bunch of accordion plugins. Here are a few:
http://wordpress.org/plugins/tags/accordion
If you're looking for something with a little more control you might want to look straight into the jquery accordion widget. See information here: http://jqueryui.com/accordion/
EDIT
To add the accordion plugin to your list, you'll need to apply the following changes. Add the following to your head tag:
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
In your wp-archives plugin modify the following line:
echo "<div class='list'><ul>\n";
to this:
echo "<div class='list'><ul id=\"unique_id_of_your_choice\">\n";
As for the content that should follow each post title, You will need to update the plugin once again to include the archive post content(either the entire post or a snippet, whichever you choose). It should look something like this if the database field holding the content were named "post_content".
$arcresults2 = $wpdb->get_results("SELECT ID, post_date, post_title, post_content, comment_status FROM " . $wpdb-> posts . " WHERE post_date LIKE '$thisyear-$thismonth-%' AND $current_posts AND post_status='publish' AND post_password='' ORDER BY post_date DESC");
...
...
$arc_title = $arcresult2->post_title;
$arc_content = $arcresult2->post_content;
...
...
echo "<li class='list'>" . wptexturize($text) . "\n";
echo"<ul><li>".$arc_content."</li></ul></li>\n";
This is possible with an accordion script like jQueryUI Accordion, but if you want to apply this to your posts page, you will also have to edit your page template.
Here is one simple method (see source):
1) Add the following to your theme's functions.php
function add_accordion_script() {
wp_enqueue_script('acc', get_template_directory_uri() . '/acc.js', array('jquery-ui-accordion'));
}
add_action('wp_enqueue_scripts', 'add_accordion_script');
2) Create acc.js in your themes directory thus:
jQuery(document).ready(function($) {
$( "#accordion" ).accordion({
header: "div.accordion-header",
collapsible: true,
active:false });
});
3) Finally modify your theme page to something like this:
<?php if (have_posts()): ?>
<div id="accordion">
<?php while (have_posts()) : the_post();?>
<div class="accordion-header">
<h1><?php the_title();?></h1>
<?php the_excerpt();?>
</div>
<div><?php the_content();?></div>
<?php endwhile; ?>
</div>
<?php else:?>
<p><?php _e('No posts'); ?></p>
<?php endif;?>
Depending on your wordpress template this may be more complicated to implement than is outlined above... in which case you'd have to provide more information.
Another alternative would be to use some sort of plugin specifically designed for this purpose. I found three that might work for you, but they do not seem to be well supported/maintained... so the above method may still be your best option:
Wordpress jQuery Accordion Plugin
WP Post Accordion
Read More Right Here Plugin
Collapse-O-Matic Plugin for wordpress is another alternative for this which is working like a charm for my website but only if I'm changing it to default theme of Wordpress :(. Seems like there is any glitch in my theme. Anyways, thanks for all the responses posted above.

Categories

Resources