"Switching Bootstrap themes with the click of a link - a step-by-step

Is there a way to switch between bootstrap themes by clicking on a link with the theme name? Here is the HTML code snippet:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport"
    content="width=device-width, initial-scale=1, shrink-to-fit=no, maximum-scale=1.0, user-scalable=no">
  <title>Theme Changer</title>
  <meta name="description" content="" />
  <meta name="keywords" content="">
  <link id="theme" rel="stylesheet" href="css/bootstrap.css" />
</head>
<body>
    <nav class="navbar navbar-expand-sm bg-light navbar-light">
      <ul class="navbar-nav">
        <li class="nav-item active">
          <a class="nav-link" href="#">Active</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item">
          <a class="nav-link disabled" href="#">Disabled</a>
        </li>
      </ul>
    </nav>
    <div class="row">
        <div class="col-md-6">
            <a id="Cyborg" href="" class="btn btn-block">Cyborg</a>
        </div>
        <div class="col-md-6">
            <a id="Lux" href="" class="btn btn-block">Lux</a>
        </div>
    </div>
         <footer>
            <p>Theme Changer</p>
        </footer>
 <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script type="text/javascript" src="js/bootstrap.min.js"></script>
  <script>
$(document).ready(function () {
    $('#Cyborg').click(function () {
        $('#theme').attr('href', 'css/bootstrapcyborg.css');
    });
    $('#Lux').click(function () {
        $('#theme').attr('href', 'css/bootstraplux.css');
    });
});
  </script>
</body>
</html>

I've set up links for loading the initial CSS on page load and then dynamically changing the href attribute upon clicking a link using jQuery. Can anyone point out any errors in my approach?

Answer №1

There are a few solutions to consider, but I would suggest starting with the first one.

  1. In place of using a tags, utilize button elements without the href attribute.
<div class="col-md-6">
    <button id="Cyborg" class="btn btn-block">Cyborg</button>
</div>
<div class="col-md-6">
   <button id="Lux" class="btn btn-block">Lux</button>
</div>
  1. Add href="javascript:void(0)" or href="#" to your existing a tags.
<div class="col-md-6">
   <a id="Cyborg" href="javascript:void(0)" class="btn btn-block">Cyborg</a>
</div>
<div class="col-md-6">
   <a id="Lux" href="javascript:void(0)" class="btn btn-block">Lux</a>
</div>

OR

<div class="col-md-6">
   <a id="Cyborg" href="#" class="btn btn-block">Cyborg</a>
</div>
<div class="col-md-6">
   <a id="Lux" href="#" class="btn btn-block">Lux</a>
</div>

Take note that using '#' as href will scroll back to the top of the page when clicked.

Furthermore, according to https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a, this approach is considered bad practice.

Anchor elements are often misused as pseudo-buttons by setting their href to # or javascript:void(0), which can lead to unforeseen issues when interacting with links, such as copying/dragging, new tab/window opening, bookmarking, or accessibility concerns for screen readers.

In these situations, it's recommended to use a button element instead to ensure proper functionality and semantics.

  1. To prevent the default browser action upon click event, add an event listener.
$('#Cyborg').click(function (e) {
    e.preventDefault();
    $('#theme').attr('href', 'css/bootstrapcyborg.css');
});
$('#Lux').click(function (e) {
    e.preventDefault();
    $('#theme').attr('href', 'css/bootstraplux.css');
});
  1. If necessary, completely remove the href attribute from the anchor tag and adjust styling accordingly due to standard anchor styles being removed by browsers.

Rationale: Since #Cyborg and #Lux are anchor elements, clicking on them triggers the default browser behavior of navigation. By having an empty string as the href value, the browser will simply reload the page without any noticeable effect.

I hope this explanation aligns with your needs and provides clarity.

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

Ways to merge various input values

I need help combining input values in my code. Below is the code I have so far: getCodeBoxElement(index) { return document.getElementById("codeBox" + index); } onKeyUpEvent(index, event) { const eventCode = event.which || event.keyCode; console.lo ...

Is JSON utilized to execute the necessary JavaScript code?

Is there a way to make an ajax call that returns JavaScript code which can be executed? Can JSON be used for this purpose? ...

Guide to implementing a real-time countdown timer for days, hours, minutes, and seconds leading up to a specific date and time with JavaScript

Implement a dynamic countdown timer in JavaScript that counts up to a specific date. See the example image for reference: here ...

Issue with floating the navbar to the right in Bootstrap 4

I am trying to reposition the navbar (without logo) to the right side using code. To achieve this, I included the class "float-right" like so <div class="collapse navbar-collapse float-right" id="navbarSupportedContent">. However, this modification ...

Making jQuery work: Utilizing tag replacements

My current code is: this.html(this.html().replace(/<\/?([i-z]+)[^>]*>/gi, function(match, tag) { return (tag === 'p') ? match : '<p>'; return (tag === '/p') ? match : '</p& ...

Obtaining a document through an Anchor Element

I am currently implementing a feature to allow users to download a zip file using an anchor tag. Here's how it's set up: <a href="download/sample.zip">sample.zip</a> When the file exists in the download directory, everything works s ...

Explore all attributes of a specific tag in BeautifulSoup to locate a particular word

As I was working on a web scraping project to extract prices from a specific website, I encountered a coding challenge. Here is the code snippet I used: price = soup.findAll(['div'],{'class':re.compile(r'(.*?price.*?)',re.IGN ...

Troubleshooting issue: JSON.stringify function returning 'undefined'

Having some trouble with JSON in JavaScript. I've been using JSON.stringify without issue until now. But suddenly, when I try to use it in my application, I keep getting this error in the console (Google Chrome): Uncaught TypeError: undefined is not ...

What is the best way to update an existing array with a new array following an AJAX call?

I currently have a collection of 3 objects stored in an array. Recently, I initiated an ajax request to fetch a brand new array to substitute the current one. console.log('initiating process'); console.log(existingData); jQuery.ajax({ url: ...

How to Use Jquery to Choose Parent Elements Beyond the Immediate Parent in the Hierarchy

Is there a quicker way to select the parent element of a child using jQuery rather than going through multiple .parent() calls? For example: <div> <div> <div class="child"> </div> </div ...

Adjusting data points on a radar chart.js through user interaction

I have a radar map generated using chart.js, along with some input fields where users can enter values that I want to reflect in the graph. I am exploring ways to update the chart dynamically as the user types in the values. One option is to have the char ...

Differences in divider line width when viewed on Chrome only

While working on a multi-format editable date/time widget, I happened to notice that the divider line in one of the widgets appeared thicker when compared to others (particularly thicker in the one with the red text): https://i.sstatic.net/BVNiT.png Here ...

Is it possible to retrieve real-time data from a database using AJAX technology?

The information I am retrieving is stored in a specific database. By using an arduino-box, the data is transmitted. The data is then presented using the following CSS & HTML code: <div class="event"> <img src="http://dummyimage. ...

Struggling to make jQuery code function in an external file without causing clashes with additional jQuery code

When incorporating this simple code into its own separate file, I encounter some jQuery conflicts with another piece of code. jQuery(function ($) { $(".tabContents").hide(); $(".tabContents:first").show(); $("#tabContainer ul li a").click(fun ...

What could be the reason that the image-changing feature is not functioning properly?

Here is the code snippet I created: var currentImage = 0; var image0 = new Image() image0.src = "img/image_centrale/1_house_0.jpg" var image1 = new Image() image1.src = "img/image_centrale/1_house_1.jpg" var image2 = new Image() image2.src = "img/image_ce ...

event triggered when the values of dynamically added rows change

I am trying to calculate the product of two input fields and display it without submitting the form. I have incorporated an array and included functionality to add/delete rows, with an onchange function to calculate the product. This solution works well ...

What is the most efficient way to loop through nested JSON using jQuery in one go?

I have a substantial JSON file containing a snippet of the data shown below. The values used in the snippet are placeholders for this specific query. "restaurants":[ "name": "Burger King", "location": "Seattle, WA", "la ...

Navigating or focusing on the next item in Angular2: A comprehensive guide

Is there a better way to navigate to the next item using Arrow keys in JQuery? <ul> <li *ngFor = "let work of works" tabindex="-1" (keydown.ArrowDown)="handleKeyEvent( $event, 'Arrow Down' )"> <div class="guid ...

Using jQuery, you can easily deactivate the form submission button for both text and checkbox input fields

I have a form consisting of three input fields (type=text, multiple checkboxes, and a disabled submit button). I need the submit button to become enabled only when the user has filled out all three text inputs and selected at least one checkbox. While I f ...

Transmitting data from JQuery to PHP script

In my current setup, I am utilizing JavaScript to retrieve a JSON array from a PHP file: <script type="text/javascript" language="javascript" > $(document).ready(function() { var dataTable = $('#employee-grid'). ...