1

I have a one-pager style page in which the top nav links to an anchor within the same page with a smooth scroll effect.

The problem is that that same nav snippet is used in other internal pages, so I want to know:

How do I create the condition of going to the one-pager if the current page is not the one-pager.

This is what I have so far, maybe reading the code makes it easier to understand what I want to achieve.

<ul id="main_menu">
<li><a href="#start">Start</a></li>
<li><a href="#overview">Overview</a></li>
<li><a href="#gift">Make a Gift</a></li>
<li><a href="#activities">Activities</a></li>
<li><a href="#resources">Resources</a></li>
</ul>

This works fine in my home page which is sample.com/start

But if I am in let's say sample.com/overview, when I click on "Resources" on the main menu links, I should be taken back to sample.com/start#resources instead of sample.com/overview#resources

Any ideas?

user3389286
  • 33
  • 2
  • 4

2 Answers2

0

On your start page use your code as it is and on other pages put the start#resources into your URL instead of the #resources only.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • Right, but the problem is that I can not change that menu in the other pages, the code for the menu has to be exactly the same across pages. – user3389286 Mar 25 '14 at 14:05
  • You can use an if in your server-side code where you check whether you are at the start page. If so, you use the code shown in the question. Otherwise, you use the code suggested in my answer. It is common to have the same menu across all pages and the little nuances are handled with ifs. My answer was suggesting to use a conditional which is my general approach when I create reusable templates. – Lajos Arpad Mar 26 '14 at 11:46
0
    <li><a href="
                <?php if(!strpos($_SERVER['SCRIPT_NAME'], 'start.php')): ?>
                    start.php
                <?php endif;?>
                #start">Start</a>
    </li>
    <li><a href="
                <?php if(!strpos($_SERVER['SCRIPT_NAME'], 'start.php')): ?>
                    start.php
                <?php endif;?>
                #overview">Overview</a>
    </li>

    <!-- etc.. -->

This checks if the current page is start.php: if it is, do nothing; if it isn't, add start.php to the href attribute before the #anchor.

I've indented like this to make it easier to read and understand what's going on, but in practice you'll want to take out the indentation inside the href attribute, because whitespace will mess up the resulting url with loads of %20s.

Related questions:

If index.php, show "this", if not, show "this"

How can I echo HTML in PHP?

Also:

http://php.net/manual/en/language.basic-syntax.phpmode.php

Community
  • 1
  • 1
andydavies
  • 3,081
  • 4
  • 29
  • 35