2

I'm creating navigation but I got a little problem, because I don't have an address for the page so I should be able to link to the content some other way. Here's the code I'm trying to work with:

$(document).ready(createNav);
function createNav() {

    var navItems = [
        {href: 'http://google.com', text: 'Google'},
        {href: 'http://bing.com', text: 'Bing'},
        {href: 'http://stackoverflow.com', text: 'StackOverflow'}
    ]; // So these addresses are just an example I tried when I wanted to see if the code works

    var navElem = document.createElement("nav"),
        navList = document.createElement("ul"), 
        navItem, navLink;

    navElem.appendChild(navList);

    for (var i = 0; i < navItems.length; i++) {
        navItem = document.createElement("li");
        navLink = document.createElement("a");

        navLink.href = navItems[i].href;
        navLink.innerHTML = navItems[i].text;

        navItem.appendChild(navLink);
        navList.appendChild(navItem);
    }

    navList.children[0].className = "current";

        var place = document.getElementById('first').getElementsByClassName('contentarea')[0];
        place.appendChild(navElem);

};

The code works well, but I don't know how to use it for my purpose. My HTML file doesn't have id's for the content that I'm trying to link to the menu. And there's so much content that it would be very impractical to do it that way.

  • 2
    [`$('#primarycontent .post').each()`](https://api.jquery.com/each/) – Pyromonk May 31 '17 at 12:01
  • 2
    @FooBar, his code is a bit too sophisticated for an entry level, I think he's being modest. It was hard for me to understand what exactly he wanted. The only thing I got out of the question was that the original poster wanted to iterate over objects without giving them id's, so I have provided him with a CSS selector that works in this scenario. As to what exactly he wants to do with the jQuery objects resulting therefrom - I don't quite understand. – Pyromonk May 31 '17 at 12:08
  • 1
    Okay thanks.. @Pyromonk, do you mean that I should put `var navItems = $('#primarycontent .post').each();` or what? – user7906611 May 31 '17 at 12:09
  • 2
    @user7906611, if `id="primarycontent"` is your navigation element, then `$('#primarycontent .post')` will create a collection of jQuery objects for each subsection within it, and `.each(function(index) { /*code*/ })` will allow you to specify a function to call on every one of them. That function takes in `index` as a parameter, so you can refer to each item within the collection by its index. – Pyromonk May 31 '17 at 12:12
  • 2
    jQuery uses CSS selectors to refer to items within the DOM. `#` finds an `id` and `.` gets a `class`. More information on CSS selectors can be found in the [documentation](https://www.w3.org/TR/css3-selectors/). – Pyromonk May 31 '17 at 12:18
  • Sorry for bad explanation. So briefly, I wanted to access the contents from `
    ` and link the menu to those. So when user clicks for example heading 3 in the navigation bar, the page scrolls to that point of the page. I know this could be done by giving them ids and linking to them, but there are so many posts and it would result in a lot of ids. Eventually it would be very impractical since it should also be easy to add new content. And thanks, I'll look into what you said @Pyromonk.
    – user7906611 May 31 '17 at 12:21
  • Here is an answer to your question that's using id's: https://stackoverflow.com/questions/6677035/jquery-scroll-to-element - except in your scenario you will have to use [`$('#primarycontent .post').eq()`](https://api.jquery.com/eq/) to uniquely identify an element. I hope this makes sense. – Pyromonk May 31 '17 at 12:26

1 Answers1

2

Here is a code snippet:

$(function() { createMenu(); }); //this is a jQuery shortcut for $(document).ready()

function createMenu() {
 var href, item, list; //href is <a> in the menu, item is <li>, list is <ul>
 var menu = $('<nav><ul></ul></nav>'); //this creates a <nav> with a <ul> child
 var posts = $('#primarycontent .post'); //this selects every class="post" that's a child of id="primarycontent"
 list = menu.find('ul'); //<ul> is selected from within menu and assigned to the list variable
 posts.each(function(n, x) { //this is a function run on every post, n is post index, x is current post
  x = $(x); //converting DOM node to jQuery object
  item = $('<li><a href="#"></a></li>'); //assigning a <li> with a child <a> to item
  href = item.find('a'); //storing a link to child <a> from <li> to the value of href
  href.text(x.find('h4').text()); //setting href text to be equal to the text of the header of the current post
  href.click(function(e) { //adding an event listener to href
   e.preventDefault(); //preventing default link behaviour (going to a URL)
   $('html, body').animate({ //adding an animation to the document
    scrollTop: x.offset().top //scrolling to the top border of the current post
   }, 2000); //animation speed, 2 seconds
  });
  list.append(item); //adding <li> with child <a> to <ul>
 });
 $('#receptmeny .contentarea').eq(0).append(menu); //appending <nav> to the 1st class="contentarea" inside id="receptmeny"
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="receptmeny" class="box">
 <div class="contentarea">
   <!-- the menu should come here -->
 </div>
</div><!-- Secondary content area end -->
<div id="primarycontent">
 <div class="post">
  <h4>Potatis, att imkoka.</h4>
  <div class="contentarea">
   <p>
    Bast ar att hartill hafva en sarskild bleckkastrull, som ar halig i botten och passar att satta ofver en kokande vattengryta. I denna kastrull lagger man ra, skalad potatis, hvilken da blir kokt fran den andra grytans imma. Men i brist af denna inrattning, sa lagges potatisen i en jarngryta med mycket vatten, att halfkoka, da vattnet afhalles, fint salt pastros; potatisen skakas i grytan tills den ser mjolig ut, hvarefter den, med lock pa, far sta pa varma spiselhallen en bra stund innan den ates. Den bor upplockas varsamt med en sked, ty annars gar den sonder. (Innan den skakas ar bra att afven stro fint socker ofver den.)
   </p>
  </div>
 </div>
 <div class="post">
  <h4>Potatisbullar.</h4>
  <div class="contentarea">
   <p>
    Stor potatis halfkokas och skalas. Da den blifvit val kall, rifves den, men aktas, att inga bitar komma med ibland det rifna. Till 12 decilit. (1 stop) rifven potatis tagas 3 hela agg, nagra skedblad gradde, ett skedblad socker, en tesked salt, litet muskot och 8 rifna bittermandlar; detta arbetas val med handerna, formas sedan i sma runda bullar, hvilka trillas i fint stotta skorpor och stekas gulbruna i flottyr. Serveras till rokt spickeskinka, kott eller stekt sill. Bullarna kunna vara utan agg, men da uteslutes gradden.
   </p>
  </div>
 </div>
 <div class="post">
  <h4>Potatismos</h4>
  <div class="contentarea">
   <p>
    Kokt potatis skalas ocn stotes sa varm den ar i en upphettad gjuten jarnpanna, men blott ett par potatis i sander. Da sa mycket potatis ar stott, som man onskar, ilagges en sked kallt smor och 2 a 3 skedar sot gradde, litet socker och muskotblomma efter smak; pannan sattes ofver elden att upphettas under flitig stotning ett par minuter, hvarefter moset brerdes pa en varm karott och ates med kottbullar eller spickemat.
   </p>
  </div>
 </div>
 <div class="post">
  <h4>Potatiskaka.</h4>
  <div class="contentarea">
   <p>
    Potatis, att imkoka.

    Bast ar att hartill hafva en sarskild bleckkastrull, som ar halig i botten och passar att satta ofver en kokande vattengryta. I denna kastrull lagger man ra, skalad potatis, hvilken da blir kokt fran den andra grytans imma. Men i brist af denna inrattning, sa lagges potatisen i en jarngryta med mycket vatten, att halfkoka, da vattnet afhalles, fint salt pastros; potatisen skakas i grytan tills den ser mjolig ut, hvarefter den, med lock pa, far sta pa varma spiselhallen en bra stund innan den ates. Den bor upplockas varsamt med en sked, ty annars gar den sonder. (Innan den skakas ar bra att afven stro fint socker ofver den.)
    Potatisbullar.

    Stor potatis halfkokas och skalas. Da den blifvit val kall, rifves den, men aktas, att inga bitar komma med ibland det rifna. Till 12 decilit. (1 stop) rifven potatis tagas 3 hela agg, nagra skedblad gradde, ett skedblad socker, en tesked salt, litet muskot och 8 rifna bittermandlar; detta arbetas val med handerna, formas sedan i sma runda bullar, hvilka trillas i fint stotta skorpor och stekas gulbruna i flottyr. Serveras till rokt spickeskinka, kott eller stekt sill. Bullarna kunna vara utan agg, men da uteslutes gradden.
    Potatismos

    Kokt potatis skalas ocn stotes sa varm den ar i en upphettad gjuten jarnpanna, men blott ett par potatis i sander. Da sa mycket potatis ar stott, som man onskar, ilagges en sked kallt smor och 2 a 3 skedar sot gradde, litet socker och muskotblomma efter smak; pannan sattes ofver elden att upphettas under flitig stotning ett par minuter, hvarefter moset brerdes pa en varm karott och ates med kottbullar eller spickemat.
    Potatiskaka.

    12 decilit. (1 stop) rifven potatis blandas med 3 skedblad fint stotta skorpor, tva skedar socker, litet muskot, peppar, salt, 45 centilit. (1 halft kvarter) gradde och tre hela agg, samt lagges i en med smor smord form, klappas tatt ihop och insattes i en bra nog varm ugn att sta en halftimme, men ofvertackes med en stekpanna, om den blir for mork. Denna kaka kan uppstjalpas och atas varm, eller ock, sedan den blifvit val kall, skaras i tjocka skifvor, som hvalfvas i hvetemjol och stekas gulbruna i flottyr. Ates med salt kott eller kottkorf.
   </p>
  </div>
 </div>
 <div class="post">
  <h4>Brynt potatis.</h4>
  <div class="contentarea">
   <p>
    Nyss kokt potatis, antingen mycket sma, da den stekes hel, eller ock stor, da den skares i skifvor, brynes i smor och socker, om den skall vara ratt fin. Men i hvardagslag kan tagas flaskflott samt ett skedblad brun sirap. Med en munkspade vandes potatisen ofta, att den ej brannes eller gar sonder; da den blifvit nara stekt, ofverstros ett skedblad fint stotta skorpor.
   </p>
  </div>
 </div>
 <div class="post">
  <h4>Brynt potatis pa annat satt</h4>
  <div class="contentarea">
   <p>
    Man skalar ra potatis, skar den i skifvor och lagger den i en gjuten jarnpanna med ett stycke smor och tatt lock ofver, hvarefter den insattes i ugnen men ses ofta efter, att den ej brannes. Nar potatisen borjar se brun ut, palagges en sked brun sirap; den insattes ater i ugnen att bli mor, da litet sot gradde sedan slas ofver och omskakas, hvarefter den ates till stekt flask eller oxstek. Sma, kokt, skalad potatis doppas i agghvitskum och trillas i finstotta skorpor, blandade med socker och kanel, samt stekas gulbruna i smor.
   </p>
  </div>
 </div>
 <div class="post">
  <h4>Potatis, stufvad.</h4>
  <div class="contentarea">
   <p>
    3 lit. (1 stop) sot mjolk uppkokas, i den lagges nyss kokad, skalad och i skifvor skuren potatis vid pass 1 lit. (1 stop), en sked smor, en tesked socker och litet salt, under bestandig omroring, att koka sakta, dock ej sa att potatisen gar sonder, utan man ror blott med en tunn stor trasked fran bradden och botten af grytan, att det ej lagger sig vid. Nar sasen ar simmig, aflyftes grytan och potatisen ates genast till rokt spickekott eller salt, kokt far- eller oxkott.
   </p>
  </div>
 </div>
</div>

I have explained every single step to the best of my ability. I hope this will help you.

Pyromonk
  • 634
  • 1
  • 10
  • 21
  • 1
  • @user7906611, I will rewrite my code to match your sample as soon as I get a chance to today if you don't mind. My apologies for making you wait. – Pyromonk May 31 '17 at 22:30
  • @user7906611, in the meantime, could you please explain to me why your navigation menu is created through Javascript and what the `navItems` array's purpose is? If all navigation links link to sections within the document, what's the point of having different `href` values? – Pyromonk May 31 '17 at 23:54
  • `navItems` isn't necessary but I just didn't know other way to do it. And also `href`is just something I found on the internet because as I said i'm quite a beginner with javascript.. And I'm creating it through javascript because I'm willing to learn it. The page is also kind of like a blog, so it has to be easy to add new posts and their headings should come in the menu. And the future writer isn't me so the menu should be "automatically" updated. And I think that's easy to do with javascript – user7906611 Jun 01 '17 at 08:14
  • @user7906611, sir, I'd like to ask you to be *very specific* about what exactly you want to achieve. Because the code I have already provided seems to fit your current description. To be precise, it would be best for you to have an `id` for each post and just use [HTML anchors](https://www.w3.org/MarkUp/1995-archive/Elements/A.html) to link to them (unless you really want the fancy jQuery scroll effect). – Pyromonk Jun 01 '17 at 08:43
  • The scroll effect isn't necessary. What code are you talking about that has already provided my previous description? I haven't been able to make it work. The page has already about 50 posts and there is going to be more so i don't want to do it with id's. And thank you so much for helping me! – user7906611 Jun 01 '17 at 08:55
  • @user7906611, I would like to have the full code for the page if possible or a live demo. – Pyromonk Jun 01 '17 at 09:01
  • @user7906611, thank you! I think I understand you now. You want to create a function that generates a menu based on the articles (posts) present on the page, where each menu item links to the corresponding article. – Pyromonk Jun 01 '17 at 09:17
  • Yes, exactly! @Pyromonk – user7906611 Jun 01 '17 at 09:27
  • @user7906611, please let me know if you have any further questions remaining, and good luck with gaining new skills! – Pyromonk Jun 01 '17 at 10:31