Anchor tags and Safari

I found an interesting “bug” in Apple’s Safari today while updating a page on Flood’s deprecating website (new version coming up in September). First of all, for the record, nobody on the team designed the template currently in-use (Aug, 2006).

I just needed to put an anchor near the end of the page… pretty standard stuff. The problem is that Safari wasn’t jumping down the page – only a couple lines. Odd because IE and FireFox jumped just fine. I’d never had that problem before, but I traced it down to something pretty simple (and maybe even conceivably reasonable). Safari jumps to the beginning of the paragraph or div that the named anchor resides in. The problem with the Flood page is that the original designers didn’t really use p tags, or divs, for that matter (in fact, simply adding a p tag will disrupt the page design… go figure). So Safari would simply jump down to just below the heading tag.

The fix? I put empty div tags around the a name tags. Problem solved!

Join the Conversation

33 Comments

  1. Nice solution, worked on a current project that i am working on.
    However though i am still faced with some anchor problems. after a certain point in the site the anchors decide to just give up and not go to where they are suppose to. I even tried taking anchors that did work and move them further along the design, in thier own div, and they just gave up.
    have you had the same problem and if so did you get it figured out?

  2. Honestly, I haven’t run into this problem very often. I would suspect there might be a problem with improperly nested tags, perhaps? I wouldn’t suspect Safari would have an issue with having too many nested levels, either. My best suggestion is to start with a bare-bones version of your page with just the necessary div and link tags to see if that changes anything…

    Keep us updated if you figure-out the problem!

  3. yeah the site was a horizontal site and we had some other issues so we are re designing the page due to clients budget and time wise and all. so no figuring out any solutions today.

  4. I was filled with hope for a minute there, but I couldn’t get div or p tags around <a> to work for me; it still won’t jump to the anchors, which are on another page-the link only goes to the top of that page. The pages are very simple; I’ve tried removing the div and ul tags which nest the <a< tags to no avail. Mozilla and IE work fine, only Safari has the problem. I can’t see Safari being a long-term survivor in this game…

    Sharyn

  5. Seems like this problem is hit or miss with a lot of people. As I mentioned above, perhaps it has something to do with improperly nested tags or even an unclosed tag somewhere. Try taking a look at an HTML validator, or even an app like Tidy to clean things up for you. There’s an online implementation of Tidy, which could be pretty useful for quick markup debugging.

  6. I’ve done my fair share of research and testing on this issue.

    Many people (we’ll call them group A) say “Safari is broken” while others (we’ll call them group B) make the argument that “no it’s not, it’s just unforgiving and people are using bad code.”

    To Group A: I’ve reviewed a few of the errors that group A has produced and, they do exist in some cases.

    To Group B: I’ve reviewed the Safari versions which are in question and discovered that some versions work and others don’t. The newest is problematic.

    ::: My Point Is :::

    Everyone is absolutely correct. What’s better is that I’ve come upon the cause and a solution.

    Now, none of us want to admit that Safari, who dances gracefully with the Netscape language and mixes a fine martini from the concepts of Explorer, could ever fail us.

    Quite frankly, it hasn’t. Safari kicks butt in a variety of ways, so when something like this pops up … we all scream louder about a bug than usual.

    Please note that the current “get anchor” javascript that is currently out there doesn’t quite work as far as I can tell. I respectfully thank the person for trying but I myself couldn’t make it happen.

    Here is my own javascript solution …

    function GetHash()
    {
    var hashtarget = window.location.href.substring(window.location.href.indexOf(‘#’), window.location.href.length);
    if (window.location.href.match(/#(w.+)/)) window.location.replace(hashtarget);
    }

    All that remains is to call the function however you wish. I use this in an external javascript which uses window.onload = GetHash(); in it’s own right.

    I hope this helps and if I’m way off base, my apologies.

  7. I forgot to mention …

    The cause of the problem is related to EXTERNAL .CSS DOCUMENTS.

    For whatever reason, when Safari is prompted to load the external css, it “pauses” the process of displaying the page until the css document has finished classifying how things are supposed to look.

    Safari does not, however, cease it’s attempt to load the anchor target on the page.

    So, while css is holding the page layout in it’s grasp, Safari aims to find something which doesn’t yet exist. Hence, nothing happens (but the page sure ends up looking pretty).

    Using window.onload, this script will get everything after the ‘#’ sign and refresh the page to that anchor tag after the tag DOES exist.

  8. and with me and my big fat mouth … my code turns out to be overkill.

    Be advised, I’m not a programmer.

    As it turns out, window.location.hash returns the hash value.

    So:

    function GetHash()
    {
    if ((navigator.userAgent.toLowerCase().indexOf(“safari”) != -1) && (window.location.href.match(/#(w.+)/))) window.location.replace(window.location.hash);
    }

    Will do the job on a Safari specific level. Or, if you don’t want to sniff out Safari, simply use …

    function GetHash()
    {
    if (window.location.href.match(/#(w.+)/))) window.location.replace(window.location.hash);
    }

    Sorry for being so wordy, folks. I’ll add more if anything comes up.

  9. Thanks Robin! I am so happy you published this fix as I would consider myself a backwards programmer (smile)…I use the tools to create websites and then fix their quirks! I was having this same problem with Safari and this worked very nicely. Thank you!

  10. OK, I’m using this in an external js file called “safarianchor.js” :

    function GetHash()
    {
    if ((navigator.userAgent.toLowerCase().indexOf(”safari”) != -1) && (window.location.href.match(/#(w.+)/))
    window.location.replace(window.location.hash);
    }
    window.onload = GetHash();

    …and I’m calling it in the usual way:

    …and my anchors are like this:

    ..but it’s still hit-and-miss: some links (page.php#anchor_name) will go down to an anchor, some won’t (and all the anchors are in identical surrounding structures).

    If the cause is the CSS stuff you mention, isn’t there a way round it in the external CSS file somehow, without needing js?

    It’s annoying!

  11. that post didn’t write some of my text!

    …calling the js in head like this

    script type=”text/javascript” src=”anchorsafari.js”

    …anchors are like

    a id=”anchorname” name=”anchorname”

  12. This problem is independent of CSS, which is really a way for formatting existing content in a page… or at least it shouldn’t have anything to do with the CSS styling. Most likely it has something to do with how Safari/Webkit renders everything, and for some reason some anchor tags just get “lost.”

  13. What’s the point of making abrowser that is so out of step with the other 98%. I’m never going to use special fixes for Safari, and if a client complains about it I’ll tell them to use a browser that is up to speed.

  14. @Steve:

    True, why bother? But maybe we should be asking ourselves first is whether or not we’ve actually used proper semantic, standards-compliant code. The reason the site I was working on didn’t quite work is because all the content was shoved into a very large table cell with no block-level elements inside to speak of, whatsoever. The second question is to ask: who’s paying your rent? If a client uses safari and complains that the anchors aren’t working (or anything else for that matter), shouldn’t that also be a concern of yours? In other words, you’re getting paid to make it work, right?

    Now, I’m not one to speak – I generally try to explain things how you do – that there’s no way to have 100% exact accuracy between browsers in how they display pages, but that doesn’t mean I should write-off their requests simply because I don’t feel like it or am frustrated with a browser. If that were the case I would have stopped making hacks and alternate stylesheets for IE6 a long time ago. The simple truth of it all is that not everybody is going to use Firefox or switch to IE7 without some significant reason to do so. Safari is still my “default” browser, but I don’t use it as much as I use Firefox because it just doesn’t have all the development tools I tend to use most on a day to day basis.

    So, yes it’s ok to be frustrated, but please consider what sorts of obligations we might have when running into problems like these. As far as the anchors are concerned, maybe it will be fixed in the next release of Safari. I haven’t toyed around with the beta much, but then again, I haven’t had much of a reason to switch since Safari is, after all, still the only Acid2-compliant browser.

  15. I’ve spent hours on this issue. I have manage to fix it one by chance (markup validation issue). But the problem appeared again on another project.

    My pages include a form that looks like .

    If I load the page directly, the anchor works properly.
    If I submit the form, the page is reloaded but the anchor is ignored !

    If I remove all external stylesheet elements in the header, it works in both case. It breaks either with link inclusion or @import inclusion.

    If I add an empty script , it works in both case. This is a very efficient script!

    (tests with Safari 3)

  16. Oups no markup in the previous message…
    My page have a form that call itself with action=”#myanchor”.
    The magic that solve the issue, for me, is a script tag in the header with src=””.

  17. Odd. I’m not sure why that is. Have you tested it with Safari 2? Likewise, how about posting instead of just to #myancor, post to page.ext#myanchor. I don’t necessarily think that will fix the problem, but Safari seems to behave strangely, so you never know!

  18. Was having the same problem and none of these solutions appeared to work. The page that needed refreshing was in an iframe of the main page, and the anchor to go to on each refresh was computed in php. So the iframe had these elements:

    <meta http-equiv="refresh" content="30;URL=iframe_page.php">

    <body onload="gotoanchor();">

    function gotoanchor()
    {
    this.location.hash='#<?php echo $currtag; ?>';
    }

    A little detective work determined that our gotoanchor code was not running on a refresh because the iframe was not actually being refreshed. Safari determined that the URL was the same, so no need to actually do a refresh. As a result, the onload ran only when the page was first loaded, but not on a refresh.

    The solution was to add a timestamp to the URL so that Safari thinks it is a different page on each refresh:

    <meta http-equiv="refresh" content="30;
    URL=iframe_page.php?t=<?php echo time(); ?>">

    Works like a charm.

  19. Wow, looks like Safari is still broken when it comes to anchor tags in July 2009. What the heck? Fast, acid2, acid3, but without support for such a basic element is pretty meaningless…

    1. It’s not that Safari doesn’t support it – it just doesn’t support it well. Honestly – I haven’t even tried it lately so I can’t verify if my particular issue – now long gone – is even a problem. I would like to point out that Firefox and the obvious IE have their own issues. For example, I just read a recently closed bug report for Mozilla/Firefox that has been open for SIX years – it just had to do with the carat not printing in a textarea contained within a scrollable div.

      Often minor annoyances.

      1. I realize with AJAX these days (and maybe other reasons as well), anchor tags don’t seem all that common, but I can confirm it is still an issue in Safari and Chrome as well. I’ve tried to see if maybe my anchor tag is malformed in some way, but I don’t see anything in the standard that my code violates. That recent javascript code out there to fix this problem in Safari exists is more confirmation in my mind that it really is a bug, and not a problem with my HTML.

        I personally really like anchor tags, because I think it really helps the user quickly navigate to what they want without network delay and loading onevent really creates an unnecessary delay even in the best cases. Sure, maybe you save a little bandwith, but it’s not a good tradeoff in many cases.

        Safari and Chrome really challenge the old ideas about browser UI, are largely standards compliant, and have wicked fast javascript engines. And they really gave Firefox a big necessary kick in the butt. But I think the anchor tag has been in the standards for so long and is so fundamental that it is inexcusable to not prioritize resolving any bugs.

        Still, your example is point taken. Peace.

  20. All the browsers are standards compliant except for when they aren’t, that is why the W3C is working on the HTML5 standard which I’m sure will be the best behaviors that were actually adhered to by the browser vendors.

    Safari’s behavior is not good. It is a bug. If Apple wants to dictate what pretty code looks like then I say we all calculate the time we spent figuring out a way around their browser’s apparent dysfunction and send Steve Jobs a bill.

    Okay, that was my turn to rant … I did find something interesting.

    I was helping with a site where we had a class assigned to a div tag with an anchor tag inside it. The behavior seen was what was seen above. I tried something that seemed to work ..

    Ditch the div tag, and apply the class to the a tag.
    HOWEVER, your a-tag has to be an opening and closing tag it can’t be a single tag or safari did wierd stuff (probably based on the class’s settings.

    Anyway, I didn’t have to resort to anything beyond that to get things working.

  21. Ok, here’s an interesting circumstance…

    I recently came across this anchor problem with an old page on my website that needed to be updated. I noticed that the anchors didn’t work so, I looked into it. I don’t think the problem is CSS related. On my website the anchors don’t work. (in Safari or Firefox). I was trying different methods to fix the issue, as recommended here and in other forums. None of them worked. BUT: In order to work on my code, I pulled it out of my website and threw it into a local HTML file. When I open the local HTML on my computer, the anchors work 100% in both Safari and Firefox. When I put the code back into my website (which is a PHP driven site) it doesn’t work again. Hmmmm… Any one have any ideas on that?

    1. There are some interesting ideas in the previous comments here. Have any of those come close to helping?

      Any difference between loading the URL then clicking the link to the anchor v.s. loading the URL with the anchor component (mydomain.com/index.php v.s. mydomain.com/index.php#myachor)? I’m thinking the latter might be more likely to trip up the browser on a remove version that loads relatively slowly compared to the immediate load times of local files.

  22. Have a problem relating to this in a new website I’ve just launched for a client: http://www.lawnfest.co.uk/

    Try clicking the ‘Music’ link.

    In every browser but Safari (4.0.5) it takes the user to the 2010 line-up page, starting with the music artists (http://www.lawnfest.co.uk/programme/lineup2010/#content-posts). In Safari the destination is the top of the page; disregarding the anchor tag.

    Is it possible to target an anchor tag on a another (new) page in Safari?

    Thanks,

    1. I take it back. There is an issue with the Music link. The one you provided in the comment above is formatted correctly, but take a look at how the link on the home page is formatted. totally different (/linueup2010/#content-posts v.s. /lineup2010#content-posts)

      1. Hi mate,

        Thanks for the reply. Can’t see it though myself? Could you perhaps re-check, or throw up a screenshot? I got all excited there for a second.

        This works in all the other browsers, so I’m still putting this one down to a bug.

        Thanks,

      2. What I’m looking at is this: http://screencast.com/t/MTBlOGU1
        which gets you to this: http://screencast.com/t/MTBlOGU1

        Basically I think it’s the link on “Music” that’s bad because by the time you get to the next page, the anchor has been lost. See what happens when you remove the slash between “linup2010” and “#content-posts” in http://www.lawnfest.co.uk/programme/lineup2010/#content-posts … you’ll see what I’m experiencing in the above screenshots. If you fix the link on the home page “Music” link to include the slash between the URL and anchor, I bet your problem will be solved.

Leave a comment

Hey there! Come check out all-new content at my new mistercameron.com!