Hello everyone, I have a BIG problem and I can't seem to find a simple solution to it in your forums.

I am inputing content from static HTML pages and have ANCHOR LINKS. The anchor links don't work.

I am looking for a simple solution to this because I am giving this site to somebody else.

Thanks for all your help
I really need it.
THANKS!
Anthony

Comments

chx’s picture

path.module and clean urls will solve your problem. Please do not use all caps, it's considered shouting.

--
Drupal development: making the world better, one patch at a time. | A bedroom without a teddy is like a face without a smile.

lockecole’s picture

thank you soooooooooooo much for your fast reply. I'm really sweating it here. THANkS! (sorry for shouting).

I really appreciate it :)
Anthony

dries’s picture

Anthony, we would appreciate it if you'd put some effort in the quality of your posts/writings. Really, I feel like deleting this forum topic.

lockecole’s picture

Sorry, I'll try harder. Just not sure what to ask. I don't know where to begin.
Anthony

lockecole’s picture

BTW: how do I do that with the path.module()?

I have something like this:
click here to jump down
...
..
..

but when I look at the browser i get:
http://www.mysite.ca/e/#jumptobottom

Any ideas?
Thanks again!
Anthony

chx’s picture

Ah! I misunderstood you. I thought you had static pages which you've imported and now the links inside does not work. Someone on the Hungarian Drupal support just had this problem, I've thought this being the same.

Nevertheless, what you are doing is called named anchor. Well, they won't work. Search for named anchor around this site, and you'll see that someone three days ago have filed a critical bug report on this topic. I will do some research on this problem, 'cos in the past I encountered this problem and the solution was not elegant. So, be patient, I or someone else will come around with a solution...

--
Drupal development: making the world better, one patch at a time. | A bedroom without a teddy is like a face without a smile.

christian_z’s picture

Accesskeys (for WCAG 2.0 valid) example like "alt+8" = "Content of page" (switch directly to the content) dont work full in Drupal 4.5, but in 4.6?

Steven’s picture

The problem is that Drupal uses a <base> tag to set the base URL to http://www.yoursite.com/. A link to #anchor will come out as a link relative to that, not to "node/xxxxx" or whatever page you are on.

The easiest solution is to write a filter module which searches for anchor links and replaces them. Something like:

$text = preg_replace('/(href="?)#/i', '\1'. $_REQUEST['q'] .'#', $text);

This should work if clean URLs are enabled (no ?q= in the address). Otherwise you need:

$text = preg_replace('/(href="?)#/i', '\1?q='. $_REQUEST['q'] .'#', $text);

There is an example of a filter module in CVS contrib:
http://cvs.drupal.org/viewcvs/contributions/docs/developer/examples/filt...

lockecole’s picture

Thanks Steven!

I followed the filter example but I'm not quite sure whats wrong with my code. I tried clearing the cache just in case, but it doesn't seem to do anything.

Thanks for your help!
Anthony

<?php
function fanchor_help($section) {
  switch ($section) {
    case 'admin/modules#description':
      // This description is shown in the listing at admin/modules.
      return t('FIX: This completes the URL so that page anchors work.');
  }
}


function fanchor_filter($op, $delta = 0, $format = -1, $text = '') { 
  switch ($op) { 
    case 'list': 
      return array(0 => t('Code filter')); 

    case 'description': 
      return t('FIX: This completes the URL so that page anchors work.'); 

    case 'prepare': 
      return $text; 

    case 'process': 
	// $pattern = '/(<[Aa]\s[^<>]*[hH][rR][eE][fF]\s*=\s*[\'"]?)#/';
	// $text = preg_replace($pattern, "\\1$_SERVER[REQUEST_URI]#", $text);
	$text = preg_replace('/(href="?)#/i', '\1'. $_REQUEST['q'] .'#', $text);
	return $text; 

    default: 
      return $text; 
  } 
}

?>
dr05’s picture

Can we fix this problem as fast as possible?

nevets’s picture

I made a module called fanchor out of the code above and it worked fine for me.

dr05’s picture

nevets’s picture

I just copied the code on this page, placed it in a file called fanchor.module, saved the file to the module directory then enabled the module

dr05’s picture

But the module create from a url
http://localhost/drupal/?q=node/12 or /node/12
anchor like: <a href="/node/12#1">1</a> and refresh the page.

And works only for "content" not for the whole website (navigation).

Example Wordpress create pages like
http://localhost/wordpress/?p=12
and anchor: <a href="#1">1</a> and no refresh!

schwong’s picture

Hi guys, here's an anchors.module I slapped together which seems to work:

<?php // $Id: anchors.module,v 1.0 2005/11/04 15:33:10 schwong

function anchors_help($section = 'admin/help#variables') {
  switch ($section) {
    case 'admin/modules#description':
      return t('Replaces relative href anchors inside posts with full path anchors.');
  }
}

function anchors_filter($op, $delta = 0, $format = -1, $text = "") {
  switch ($op) {
    case 'list':
      return array(0 => t('Anchors filter'));
    case 'description':
      return anchors_help('admin/modules#description');
    case 'no cache':
      return TRUE;
    case "process":
      return preg_replace("/href=([\"']?)(\#\w+[\"']?)/i", "href=$1" . request_uri() . "$2", $text);
    default:
      return $text;
  }
}
?>

I've also posted a more verbose explanation of drupal anchors.

lucidcarbon’s picture

So I created a file called anchor.module with the code you posted and enabled it.

I get the following error when I both select it to apply in an input format and when I try to edit content using the input format that enabled it for:

warning: Cannot modify header information - headers already sent by (output started at /home/httpd/vhosts/secularstudents.org/httpdocs/drupal2/modules/anchors/anchors.module:22) in /home/httpd/vhosts/secularstudents.org/httpdocs/drupal2/includes/common.inc on line 192.

I've never written a filter before, so I don't know what might be causing the problem.

Any ideas?

rnsi’s picture

Check your anchors.module for any trailing spaces or returns after the closing php tag (?>).

David Foster’s picture

Thanks Schwong, the filter works really well for me but it took a while to figure out how to activate it, me being new to Drupal.
For anyone trying this filter, don't forget to not only activate the entry in 'admin/modules' but also in 'admin/Input Formats'.
Click on Configure for whichever html or php option you have selected and tick the Anchors filter option.

droopy’s picture

Is there some reason why this does not work on flexinode-based nodes?

M.J. Taylor’s picture

Hi schwong (et. all),

I've tried both the copy here and off your website. I've checked for trailing blanks/spaces and also mass replaced all blanks with spaces. I've uploaded the file as both ASCII and binary. I get nothing. . . (still getting [Base href]/#Foot1 results and no error messages.)

The module shows up in the admin/modules (and can be enabled), but it does not populate it's help text (I even checked it against one of our inhouse Adsense module changes and the coding seems to be the same, but the Adsense does populate help text in admin/modules).

Our coding test bed is running v. 4.6.3 (which we'll upgrade before going live)
Browsers tested, Opera v 7.11, 7.54, 8.02

David Foster mentions that one must "tick the Anchors filter option." in admin/Input Formats (admin/filters), but I don't see anything there related to Anchors (tried configuring all three existing input formats and even tired adding a new one called "Anchor"). Besides which I'm under the impression, that people don't want this (well I don't) as an input filter, but as a _output_ fix for a drupal bad behavior. (The thought of having to manually go through hundreds of nodes to re-select the proper input filter so page anchors work the way they should work to begin with is mind boggling.)

Addendum: While logged in as Admin, page anchors are working, but. . . Logged in as a different user or not logged in at all still corrupts page anchors from functioning properly.

See http://tst2.reasontofreedom.com/Bill_of_Rights.html [Thomas Jefferson(1)]

Can anyone give a detailed explanation on how to get schwong's anchor.module to work correctly (especially for guest visitors)?

Thanks,

M.J. Taylor
Publisher
from Reason to Freedom
Weekly libertarian magazine: Reason is a natural life-giving activity of the mind. We regard independent thinking as the most important virtue.

schwong’s picture

Make sure your module file is named "anchors.module" and not "anchor.module" as stated in your post above. Drupal is picky about stuff like that.

BTW, I hear as of 4.7 Drupal is removing the base element, so this module should no longer be necessary.

schwong’s picture

The new Relative Link Filter module will do the same job as my code above, and more! It also comes with documentation on how to apply it to an input format.

The Relative Link Filter module "fixes" anchors in pre-4.7 versions of Drupal by rewriting all relative links as absolute links. If you'd like to change it to only handle anchors, and leave the rest of your links alone, edit rellinkfilter.module, and change the following code:

       // Fix links
      $text = preg_replace('( (href|src)="(/|http:|https:|ftp:|mailto:))',
                           ' \1not="\2', $text);
      $text = preg_replace('( href="#)', " hrefnot=\"$uri#", $text);
      $text = preg_replace('( (href|src)=")', " \\1=\"$uridir", $text);
      $text = preg_replace('( (href|src)not=")', ' \1="', $text);
      return $text;

To

       // Fix links
      $text = preg_replace('( href="#)', " hrefnot=\"$uri#", $text);
      return $text;

Good luck, everyone.

urbanfalcon’s picture

I also put this in the module's issues list, but don't forget that if you have any dot-format relative paths (eg., href="../files/path.htm"), you need to make the following change:

$text = preg_replace('( (href|src)="(/|http:|https:|ftp:|mailto:|.))', ' \1not="\2', $text);

Also, in 4.7 (yes, my pages created in 4.5 and 4.6 didn't pick up the spiffy new 4.7 way of dealing with relative paths), I had to add a forward slash in the middle replacements to keep from getting duplicated paths (eg., http://domain/node/node/1234):

$text = preg_replace('( href="#)', " hrefnot=\"/$uri#", $text);
$text = preg_replace('( (href|src)=")', " \\1=\"/$uridir", $text);
eugsadhu’s picture

You will need to add this code to the code that runs on body load:
function esFixAnchors(){ for(i=0;i<document.links.length;i++){ var temp=document.links[i].href; if(temp.indexOf("#")>0){ document.links[i].href=document.URL+temp.substr(temp.indexOf("#")); } } }
The code will cycle through all of the links on the page, replacing those with # with the correct URL.

iamalive’s picture

Hi

I'm stuck with this anchor tag problem. I've tried the other solution with no luck.

Which file do I have to add your code and where, roughly. I'm not a programmer.

Thanks for your help

Update: I've got the other script to work. I just needed to change the settings in the Input Formats module.

Reagrds

marcopanichi’s picture

i think the javascript proposed by eugsadhu is the best solution.
but i've corrected it, beacuse the function doesn't consider eventual anchor pre-existent on url.
here my version:

function esFixAnchors()
{ 
	var lenght = document.links.length;
	for(i=0;i<lenght;i++)
	{ 
		var url = document.URL.split('#'); url = url[0];
		var temp=document.links[i].href; 
		if(temp.indexOf("#")>0)
		{ 
			document.links[i].href=url+temp.substr(temp.indexOf("#")); 
		} 
	} 
}
M.J. Taylor’s picture

Disregard my post above. Fixing page anchors problems for prior 4.7 versions are a much larger problem than expected. Please see the thread http://drupal.org/node/13148 (last 20 comments or so) for a fuller explanation.

chdom’s picture

Hie everyone,

I needed HTML anchors, and I was very surprised to see that the "l" function added a "#" at the very end of the URL causing my anchors not to work.
Having a look at the code of the "l" function, I discovered that the "url" function was responsible of adding the trailing "#".
This quite complex function (which I did not read any further) contains 7 returns depending on several cases.
Well, to circumvent the problem of the trailing "#", I just added :
ereg_replace("#$","",$string_returned)
to every return string and it works fine now.
Hope it can help.
Cheers

chdom’s picture

Hie everyone,

I forgot to say the "url" function is found in the file : includes/common.inc
Cheers

chdom’s picture

Still being a newbie in Drupal, I did not notice that the fifth argument (fragment) was dedicated for the anchor name. I thought the fourth argument (query) had to take all the query string of the URI into account.
So forget about my last two posts and use the fifth argument without the "#", it works fine. Nevertheless, why is there a trailing "#" at the end of the URI, then ?
Cheers
Dom

mnshyn’s picture

anchors will work with non-clean url's if you just add an extra "/"

http://www.yourwebsite.com/index.php?q=node/6/#anchor

put a "/" after your nid before the anchor.

coryj’s picture

I had a short list of comments which was linkable to a much larger list. My goal was to send the user to the exact comment the clicked on for more information. At first my links looked like http://www.yourwebsite.com/all_comments#comment-1094. Although the link went to the proper page, it would not jump to the proper anchor. So like mnshyn said, i added an extra slash to the url: http://www.yourwebsite.com/showhome/#comment-1094. When you click this link, the clean url module cuts off the /#comment-1094 but it works none the less!

1websitedesigner’s picture

Hi,

I know this post is old, however it came up first for 'Drupal anchor' on Google, so I thought I'd say to anyone wanting to know how to add anchor links on a page, there's a useful end-user guide on:

http://www.1websitedesigner.com/drupal-anchor-links

It does assume you have the FCK Editor or another WYSIWYG editor installed.

Martin

crosshairs’s picture

I'm unable to link to a named anchor. The 'insert link' popup window doesn't include a "link to anchor" option.
Using WYSIWYG API 6.x-2.1 with tinyMCE on Drupal 6.18

Anyone have any pointers?