CSS not reflecting changes after the href of the <link> tag has been updated

Hey there, I'm a beginner in the world of programming and currently facing an issue that I need help with. My goal is to dynamically update the CSS of my webpage by using JQuery to change the 'href' value in the link tag.

In order to test this functionality, I am working on a simple testcase while utilizing Less for CSS. Within my project, I have 2 .less files ('test.less' & 'testTwo.less'). Below is the code snippet:

$(function() {

    $('#changeButton').click(function() {
    $('#style').attr('href', '../testfiles/testTwo.less');
    console.log($('#style').attr('href'));
    })

    })

During testing, I verify if the href value actually changes, which it does successfully. However, the styling of the page remains unaffected.

<!DOCTYPE HTML>
<html>
<head>
    <link rel="stylesheet/less" type="text/less" href="../testfiles/test.less" id="style">
    <script type="text/javascript" src="../jquery/jquery.js"></script>
    <script type="text/javascript" src="test.js"></script>
</head;

<body>
    <div id="changeButton">click me</div>

    <script src="../bower_components/less/dist/less.js"></script>
</body>

</html>

I understand that there might be something crucial missing from my approach, possibly related to CSS rendering. Any guidance or assistance would be greatly appreciated. Thank you!

Answer №1

Make sure to incorporate the changes into your code as shown below

$(function() {

    $('#changeButton').click(function() {
        $('#style').attr('href', '../testfiles/testTwo.less');
        console.log($('#style').attr('href'));
        $('style[id^="less:"]').remove(); // don't forget to remove the less
        less.refresh(); // make sure to refresh the files
    })

})

Important Notes

  1. Consider using css in html instead of less for better performance. You can use pre compilers and have html refer to css.
  2. Remember that Less compiler does not automatically compile dynamically added files. You must manually trigger the refresh to apply changes.
  3. Removing the less file is necessary due to how LESS operates. It processes the less file, then adds a style attribute with id like
    id='less:<<NAME OF YOUR LESS FILE>>'

Answer №2

When utilizing less.js, it is necessary to ensure that all less files are loaded before it can compile them into css during the page load process. If the less file is added dynamically, it will not have the opportunity to be compiled.

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

Exploring the potential of utilizing records within deepstream.io

Lately, I've been delving into the world of records and I find myself pondering on the practical limitations when it comes to the size of a json structure. Is there a recommended maximum length? Can you store an entire chat history as an (anonymous) r ...

What is the process for uploading a file using the client's file path?

I'm fascinated by the way Sonic Living is able to identify and upload your iTunes library XML file with such ease. Unlike other upload libraries I've explored, it prompts user approval before automatically uploading the XML file based on client O ...

Updating data scope in AngularJS using $http request not functioning properly

I am facing an issue where the $scope.user_free_status is not updating when I set a user free, but works perfectly fine when I unset the parameter. It's strange that I need to reload the page in one case and not the other. The data fetched is stored i ...

Retrieve all documents from a Firebase User's collection

Recently, I created a Firebase cloud function where my goal is to access every user's internal collection named 'numbers' and examine each document within that collection for some comparisons. Do you have any insights on how I can achieve t ...

In JavaScript, the function is unable to access elements within an iteration of ng-repeat

I am using ng-repeat to display datepickers that are powered by flatpickr. To make this work, a script needs to be added on the page for each input element like so: <script> $('[name="DOB"]').flatpickr({ enableTime: false, dateForm ...

Combining arrays of objects that contain nested arrays of objects using JavaScript along with libraries such as lodash or Underscore

Attempting to combine two arrays of objects using the lodash JavaScript library, however, encountering an issue where the Subcategories property containing another array is not being merged. Here are the arrays to be combined: var menu1 = [ { "PageNa ...

How can I create a responsive design for my div elements?

I am facing an issue with responsiveness in my div container. Inside the square-shaped frame, I have a h2 tag that does not adjust properly when viewed on different devices such as mobile and browsers. Despite setting up media queries to make it responsive ...

Unable to process image upload due to setState not being recognized as a function in ReactJs

Attempting to implement an upload function using the cropper component. However, encountering an error when trying to set the state: Uncaught TypeError: this.setState is not a function at FileReader.reader.onload Component import React, { Component, P ...

Using a JavaScript function, transmit information through an Express response

I am working on sending an application/javascript response from my Express server, utilizing data retrieved from MongoDB. This response is intended for loading content on a third party website. All components of the process have been developed, and now I ...

Enhance the angular 2 dependencies within the angular2-cli project

After experimenting with Angular 2 and following the guide on their website, I attempted to switch to Angular 2 CLI. However, the Angular 2 CLI project does not have the latest dependencies, resulting in errors from the compiler related to certain commands ...

Interactive text animation triggered by a click

jQuery ( function ( $ ) { console.log(">>Testing animation"); $('a.loveit').on('click',function(event){ event.preventDefault(); var text = $(this).find('div.love-text'); ...

Generating VueJS Syntax from JSON Data

My goal is to retrieve locale language variables from a JSON Request generated by Laravel and load them into VueJS. VueJS does not natively support locales, so I am facing issues with the ready function alert not working while the random text data variable ...

What is the best way to duplicate a value and save it in an array?

I have a calendar and I want to be able to copy the selected day's value and store it in an array. Then, if another day is clicked, I would like to add the current day's value along with the previous day's value to the array. Users should be ...

Extract a value from a json document

Hey there! I'm looking to create an unwhitelist command. When a user is mentioned or their ID is provided, I want it to be removed from the JSON file without checking if the ID exists. Do you have any suggestions on how to accomplish this? Here is my ...

Using JavaScript to Transmit URL

Imagine I have a URL similar to this: http://localhost:8000/intranet/users/view?user_id=8823 All I aim to achieve is to extract the value from the URL using JavaScript, specifically the user_id (which is 8823 in this instance), and transmit it through an ...

A guide on accessing Kendo Dropdownlist values in jQuery from a controller action

I am facing an issue where I am trying to fetch data from a Kendo Dropdownlist in the controller action using Jquery. Below is the code snippet: $("#CountryName").kendoDropDownList({ dataTextField: "Description", dataValueField: "Id", dataSour ...

Creating Tailored Breakpoints with Bootstrap for a Unique Design

Currently, I am delving into the world of front-end web design and taking advantage of Bootstrap for creating a responsive layout. However, I have noticed that Bootstrap only offers 5 predefined breakpoints. I am curious to know if there is a way to cust ...

What could be causing my application to not locate the jquery module? ERROR: ENOENT: The specified file or directory cannot be found

I've decided to bring over an Angular project that already has a bootstrap template integrated into my own project. (Still unsure if this was the right move) One of the steps I took was adding these lines to the angular.json file: "styles": [ ...

Issue with draggable div containing gmap not functioning on mobile browsers

Is it possible to make a specific div draggable without dragging the content inside, such as a gmap widget? I have tried implementing this functionality in my code and it works on a computer browser but not on a mobile browser. Here is the simplified versi ...

How exactly does this JavaScript code determine the index of the maximum value within an array?

Examining the specific line of code: let largest = arr.reduce((a,v,i) => v > a[1] ? [i,v] : a, [-1,0]); I find this part a, [-1,0] particularly perplexing, as I am unsure of its syntax. How does a function before the comma? ...