Grunter
Grunter

Reputation: 73

Linking to another location on the same page

i have a problem with linking my list elements with method (href, #) to the post elements in the html. ive goten so far to create clickable links for every h4 element in the primarycontent div. But i cant make the links work so that when i click on a listelement i whant the page to scroll down to the right place on the page for that specific list element.

the Html code, short version, showing where i whant the href to direct me to:

<div class="divider1"></div><!-- Primary content: Stuff that goes in the primary content                  column (by default, the left column) -->
<div id="primarycontainer">
    <div id="primarycontent">
        <!-- Primary content area start -->
        <div class="post">
            <h4>
                Potatis, att imkoka.
            </h4>
            <div class="contentarea">
                <p>
                    Bäst är att härtill hafva en särskild bleckkastrull, som är hålig i 
                </p>
            </div>
        </div>
        <div class="post">
            <h4>
                bleeeeeeh
            </h4>
            <div class="contentarea">
                <p>
                    Då ärterna äro spritade, skrapas och skäras i tär
            </div>
        </div>
        <div class="post">


    the javascript:

    $(document).ready(generateMenu);

    function generateMenu() {

    var statusListDiv = document.getElementById('receptmeny'); 
    var ulElement = document.createElement("ul"); //skapar <ul> element
    var recept; 
    var div = document.getElementById("primarycontainer"); 
    var rubriker = div.getElementsByClassName("contentarea").length; 



    for (var i = 0; i < rubriker; i++) {


    var liElement = document.createElement('li'); 
    var aElement = document.createElement("a");  

    recept = div.getElementsByTagName("h4")[i].innerHTML;
    aElement.setAttribute("href", '#'+recept); 


   aElement.appendChild(document.createTextNode(recept)); 
   liElement.appendChild(aElement); 
   ulElement.appendChild(liElement);

   statusListDiv.appendChild(ulElement);

   }
   }

Upvotes: 1

Views: 71

Answers (1)

Spock
Spock

Reputation: 4900

The way linking works is to set the href of the anchor to the id value of the element you want to link to.

There's an explanation here. http://www.yourhtmlsource.com/text/internallinks.html

I think your problem is here...

recept = div.getElementsByTagName("h4")[i].innerHTML;
aElement.setAttribute("href", '#'+recept); 

You're setting the href equal to the innerhtml of the H4, when you should be setting the href equal to the id of the h4...

var id = 'div_' + i;
div.getElementsByTagName("h4")[i].id = id;
aElement.setAttribute("href", '#'+ id); 

For this to work, each of your h4 must have a unique id, or you have to assign a unique id when creating the anchor dynamically.

Hope that helps

Upvotes: 1

Related Questions