简体   繁体   中英

JavaScript and CSS Website Navigation Bar

Is there any method to have one navigation bar that is used on two pages but the links on both pages are different? For example if it was about animals: Page 1 = Dogs, Page 2 = Cats. Both have a navigation bar item that consists of "Food Store", "Grooming", and "About". I want one Food Store to link to www.DogsFood.com for when on the Dog page, and the other Food Store to link to www.CatFood.com for cats. If you have any resources for how to go about that, it would be greatly appreciated! Thanks!

One way is to use reusable components from Angular. I don't think this is what you were expecting for an answer (perhaps your instructor is forcing you to use javascript if you are doing a graded project). But I strongly recommend you to learn Angular, even if at first it's a bit too hard to understand, but it solves all the problems found while developing with Javascript.

Another way is to load your HTML via javascript on load, which is bad practice, and set the url variables inside the parameters of the function.

Yes, this is definitely possible, and the good news is that there are many different ways you could achieve such a setup!

My preferred way to implement this sort of nav bar would be to serve up the correct links on the server-side so that the code the end-user's browser actually receives from your server already includes the full navbar with the correct links in it. This can be achieved relatively easily using some PHP or Node.js depending on your server setup. I'd be happy to dive into how to do this on the server-side if you're interested in going that route, but because you asked how to go about doing this using JavaScript (and I presume you mean front-end JS), I'll explain that second, non-server-side method in my answer now.

To implement this using all front-end JavaScript, I see two main directions we can go from here. I'll explain both soon. First, we need to use JavaScript to get the current page's path from the URL. We can do that using this code (explained below):

const pageName = window.location.pathname.slice(1).split("/")[0];

We retrieve the path of the current page. For this example, I use .slice(1) to remove the starting slash character ("/") from the URL path window.location.pathname (after the domain). This will be used for both examples. From here, I split the URL path string into different array values by splitting the string everywhere another slash character appears using .split("/") . Now, we use [0] to get the first value from that array, which will be equal to the very first directory in the path after the domain in the page's URL. This method will work for this page as well as any sub-pages under the same directory (eg /path-1/ , /path-1/path-1-subpath/ )

1. If / Else Method

The first and more simple method would be to check the current page's URL path using the value we extracted above and then inject the HTML code for whichever nav items you would like to display for that page.

 const pageName = window.location.pathname.slice(1).split("/")[0]; const nav = document.getElementById('navigation'); if (pageName === "dogs") { nav.insertAdjacentHTML('afterbegin', '<a href="#">Dog Link 1</a><a href="#">Dog Link 2</a><a href="#">Dog Link 3</a>'); } else if (pageName === "cats") { nav.insertAdjacentHTML('afterbegin', '<a href="#">Cat Link 1</a><a href="#">Cat Link 2</a><a href="#">Cat Link 3</a>'); } else if (pageName === "js") { nav.insertAdjacentHTML('afterbegin', '<a href="#">JavaScript Link 1</a><a href="#">JavaScript Link 2</a><a href="#">JavaScript Link 3</a>'); } else { nav.insertAdjacentHTML('afterbegin', '<a href="#">Random Link 1</a><a href="#">Random Link 2</a><a href="#">Random Link 3</a>'); }
 body { margin: 0; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; font-family: arial, sans-serif; } nav { display: flex; align-items: center; justify-content: flex-start; gap: 15px; padding: 10px 15px; background-color: #03a9f4; } nav > a { display: inline-block; padding: 5px 10px; border-radius: 100px; font-weight: bold; color: #fff; text-decoration: none;important: transition. all 0;15s ease-out: } nav > a:hover { background-color; #283593; }
 <nav id="navigation"></nav>

2. The Object-Oriented Method

In my opinion, this is a far better method. At its core, JavaScript was built as an object-oriented language, and it can be very powerful when those object-oriented functions and properties are understood and utilized. There's also a methodology in programming called "DRY" which simply stands for "Don't Repeat Yourself." By populating the navbar using objects and arrays, we have a much clearer organization of our navigation links. By doing this, you can simply loop through the array of navigation links for the appropriate page and only touch HTML once, in the loop.

We can build out the object like this:

const navLinks = {
  dogs: [
    { label: "Dog Link 1", href: "#" },
    { label: "Dog Link 2", href: "#" },
    { label: "Dog Link 3", href: "#" }
  ],
  cats: [
    { label: "Cat Link 1", href: "#" },
    { label: "Cat Link 2", href: "#" },
    { label: "Cat Link 3", href: "#" }
  ],
  js: [
    { label: "JavaScript Link 1", href: "#" },
    { label: "JavaScript Link 2", href: "#" },
    { label: "JavaScript Link 3", href: "#" }
  ],
  default: [
    { label: "Random Link 1", href: "#" },
    { label: "Random Link 2", href: "#" },
    { label: "Random Link 3", href: "#" }
  ]
};

Similar to the if/else method, this method also provides a way of including a default/fallback list of URLs in case one of your users happen upon a page that doesn't match any of the paths you specify. In order to achieve this, we first query the navLinks object using the variable pageName which we gathered from the URL path, which requires bracket object[variable] notation since we are using a variable value or the property name. If this doesn't work, we use the fallback property, navLinks.default . We can do this all in one line like this: (navLinks.pageName || navLinks.default) . This will return an array of links for the specified property (dogs/cats/etc.). Once we know this, we can immediately run the .forEach() array prototype method on the returned array allowing us to loop through each of the links that array holds. From here we just inject the values where we'd like them to be like this: <a href="${link.href}">${link.label}</a> .

Now let's put it all together. As you can see in the snippet below (click "Run"), this produces the same final result as the first method.

 const pageName = window.location.pathname.slice(1).split("/")[0]; const nav = document.getElementById('navigation'); const navLinks = { dogs: [ { label: "Dog Link 1", href: "#" }, { label: "Dog Link 2", href: "#" }, { label: "Dog Link 3", href: "#" } ], cats: [ { label: "Cat Link 1", href: "#" }, { label: "Cat Link 2", href: "#" }, { label: "Cat Link 3", href: "#" } ], js: [ { label: "JavaScript Link 1", href: "#" }, { label: "JavaScript Link 2", href: "#" }, { label: "JavaScript Link 3", href: "#" } ], default: [ { label: "Random Link 1", href: "#" }, { label: "Random Link 2", href: "#" }, { label: "Random Link 3", href: "#" } ] }; (navLinks[pageName] || navLinks.default).forEach(link => nav.insertAdjacentHTML('afterbegin', `<a href="${link.href}">${link.label}</a>`));
 body { margin: 0; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; font-family: arial, sans-serif; } nav { display: flex; align-items: center; justify-content: flex-start; gap: 15px; padding: 10px 15px; background-color: #03a9f4; } nav > a { display: inline-block; padding: 5px 10px; border-radius: 100px; font-weight: bold; color: #fff; text-decoration: none;important: transition. all 0;15s ease-out: } nav > a:hover { background-color; #283593; }
 <nav id="navigation"></nav>

I sincerely hope this helps, and do let me know if you'd like some help with achieving this on the server-side. Cheers!

You can make the navigation bar and style it in CSS and just change the href="" of the anchor tag

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM