Generate the hyperlinks with JavaScript

I have successfully implemented a boostrap 4 navbar, and I have a function that creates links. Is there a more efficient method to accomplish this using JavaScript? I currently have three functions that create links for each hyperlink. Would it be possible to use cookies or any other efficient method with JavaScript?

<script>
  function setAboutLink(lang){
    var url = lang+"/aboutus";  
    window.location.href= url; 
  }
  function setContactLink(lang){
    var url = lang+"/contact"; 
    window.location.href= url;
  }
  function setListLink(lang){
    var url = lang+"/list"; 
    window.location.href= url;
  }

</script>

<nav class="navbar navbar-expand-md navbar-light bg-light fixed-top pb-0">
    <a class="navbar-brand" href="/"+selectedLanguageName><img src="/images/logo.png" alt="" class="logoC mr-4"
            style="max-width: 100px"></a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse justify-content-between" id="collapsibleNavbar">
        <ul class="navbar-nav mr-auto">
            <li class="nav-item">
                <a class="nav-link" href="javascript:" onclick="setAboutLink(window.location.href)"
                   >About Us</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="javascript:" onclick="setContactLink(window.location.href)"
                    >Contact Us</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="javascript:" onclick="setListLink(window.location.href)"
                   >List</a>
            </li>
        </ul>       
    </div>
</nav>

Answer №1

Why is the discussion about cookies necessary? All that's required is an efficient method. You can create a generic function for this purpose, which can then be utilized throughout the entire website.

function navigateToPage(page){
   window.location.href = window.location.href + '/' + page
 }
<nav class="navbar navbar-expand-md navbar-light bg-light fixed-top pb-0">
    <a class="navbar-brand" href="/"+selectedLanguageName><img src="/images/logo.png" alt="" class="logoC mr-4"
            style="max-width: 100px"></a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse justify-content-between" id="collapsibleNavbar">
        <ul class="navbar-nav mr-auto">
            <li class="nav-item">
                <a class="nav-link" href="JavaScript:Void(0)" onclick="navigateToPage('aboutus')" >About Us</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="JavaScript:Void(0)" onclick="navigateToPage('contact')"
                    >Contact Us</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="JavaScript:Void(0)" onclick="navigateToPage('list')"
                   >List</a>
            </li>
        </ul>       
    </div>
</nav>

Answer №2

<script>
  var lang = 'en'; // default language is set to English
  if (localStorage.getItem('lang') === null){
    localStorage.setItem('lang', 'ch'); // If no language found in localStorage, set it to Chinese (ch)
  } else {
    localStorage.getItem('lang')
  }

  function setLink(path){
    // Check language variable in localStorage - if 'ch' use Chinese otherwise use English
    var url = window.location.origin + '/' + lang + '/' + path
    window.location.href= url;
  }

</script>

<nav class="navbar navbar-expand-md navbar-light bg-light fixed-top pb-0">
    <a class="navbar-brand" href="/"+selectedLanguageName><img src="/images/logo.png" alt="" class="logoC mr-4"
            style="max-width: 100px"></a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse justify-content-between" id="collapsibleNavbar">
        <ul class="navbar-nav mr-auto">
            <li class="nav-item">
                <a class="nav-link" href="javascript:" onclick="setAboutLink('aboutus')"
                   >About Us</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="javascript:" onclick="setLink('contactus')"
                    >Contact Us</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="javascript:" onclick="setLink('list')"
                   >List</a>
            </li>
        </ul>       
    </div>
</nav>

I have added functionality to store the user's selected language preference in localStorage. The default language is English and if not previously set, it will default to Chinese. The script now supports switching between languages based on this stored value.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

IE8 experiencing issues with jQuery live click event functionality

I have this code snippet that is working perfectly fine in all browsers except for IE8. The #cal_popup_table element is dynamically added to the page. $("#cal_popup_table tbody tr td a").live('click', function() { $('.da ...

ID of the Radio button that was most recently selected

My table contains multiple rows, each with a Radio button in the first column: <table class="table table-condensed span8" id="AllocationTable"> <thead> <tr> <th title="Entity to Allocate" style="width: 30%"> ...

Unable to display the response received in jQuery due to a technical issue with the JSON data

Hey there! I'm fairly new to JSON and web development, so please bear with me if I'm not explaining the problem in the most technical terms. I recently encountered an issue where I retrieved a JSON response from a website, but I couldn't di ...

Creating a scrolling effect similar to the Nest Thermostat

After researching countless references, I am determined to achieve a scrolling effect similar to the Nest Thermostat. I came across this solution on this JSFiddle, but unfortunately, the parent element has a fixed position that cannot be utilized within my ...

Pausing for the completion of AJAX calls within a $.each loop before proceeding with the function execution

I am looking to trigger a function only once all of the AJAX calls within my $.each loop have finished executing. What is the most effective approach to accomplish this task? function recalculateSeatingChartSeatIds() { var table_id = $(".seatingChar ...

Grid element's height does not correspond to the responsive square child dimension

In my latest project, I am developing a web application using React and Material-ui. One of the challenges I have encountered is creating a responsive square div for a map component. Unfortunately, attempting to implement a solution from a trick on iamstev ...

Discover the possibilities of setting the dimensions of your anchor tags using only inline-block spans

Can anyone help me understand what is happening with this small piece of HTML code? http://jsbin.com/akome5 When viewed on various browsers such as FF4, Chrome10, IE9, IE8, Opera 11, the layout of the element appears like this: Hmm, why is this happenin ...

`Enhancing Navigation Links with Scroll-Activated Styling`

I'm attempting to recreate a visual effect that is similar to: Specifically, I am trying to achieve a style where the links in the navigation bar change color when the corresponding section is displayed, such as having the gallery link in the navbar ...

Step-by-step guide to activating vertical scrolling for select tiers in a multi-layered fly-out navigation

Currently working on a multi-level flyout menu to be integrated into a daterange picker for selecting time periods. Check out the jsfiddle link here: https://jsfiddle.net/6t72hd4x/1/ I attempted to set overflow-y: auto; in the .inner-list class to handle ...

Participating in a scheduled Discord Voice chat session

Currently, I am in the process of developing a bot that is designed to automatically join a voice chat at midnight and play a specific song. I have experimented with the following code snippet: // To make use of the discord.js module const Discord = requ ...

Creating a loop in a column-based carousel without using JavaScript

I'm currently working on developing a carousel using JavaScript or jQuery. I've attempted the code snippet below, but I'm having trouble getting it to display in 3 or 4 columns. While I understand that Bootstrap can handle this easily, I&apo ...

I am curious to see the number of people who have made their selection

I am currently using JavaScript to alter the text value from "select" to "selected". My next step is to include the selected text in a cart. Can you please provide some guidance? Thank you in advance. PHP CODE : <a class='btn slct' href=&ap ...

Transferring UTM parameters to a different page via a button click

Is there a way to extract parameters from a URL after the "?" and add them to a button's href in order to redirect to another landing page? I want to transfer UTM parameters to another page using JavaScript within the button. Original Homepage: Dest ...

Tips for integrating a logo into router view animations

How can I incorporate a logo into the white fade-in screen that appears when navigating between subpages using <router-view> within App.vue? Here is a simplified version of my App.vue code: <template> <div id="app"> <div ...

Can you explain the significance of the visitFunction error message?

When running [email protected] + [email protected] + [email protected] + [email protected], I encountered an error message. Can anyone help me understand what this error means? I am simply executing: res.render(view, response); Proper ...

What could be the reason for the unexpected behavior of position sticky?

I am encountering an issue while trying to figure out why the container__item--special element behaves as a sticky element in this code snippet <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> ...

Creating a repeated design using linear gradients in CSS

As I venture into the realm of Photoshop patterns for the first time, I am working on a webpage where I plan to incorporate these patterns to enhance the background. The pattern I have discovered measures 120x120 px. If I were to stop here, I would simpl ...

What could be causing my 3D Model to fail to load in three.js when using the glTF loader?

I'm trying to load a 3D object into my three.js project for the first time. I have the object downloaded on my computer and have connected the three.js library and the glTF loader to my HTML document. However, every time I run the code, I encounter th ...

What are some techniques for styling a label element with an empty for attribute using CSS?

Here is what I currently have: <label class="filter-label" for="pv[]181"> ::before white <span class="count">5</span> ::after </label> My goal is to modify the ::after element within that label, but so far my attempts ...

What is the best way to filter out and combine one array from two arrays in lodash based on their unique properties?

Lodash v 4.17.15 Consider the scenario where two arrays are involved: var users = [{ id: 12, name: Adam },{ id: 14, name: Bob },{ id: 16, name: Charlie },{ id: 18, name: David } ] var jobs = [ ...