Switching between different CSS files based on the URL using jQuery or another method

Is it feasible to apply specific styles based on the ID or load various CSS files depending on the URL you are visiting?

For example:

<script>
 if(location.href == 'http://jpftest2.tumblr.com/about'){ 
document.write('<style type='text/css'>
.social {
  display:none;
}

</style>'); 
} 

</script> 

So when a user navigates from the root URL to the "/about" page, I want to implement the style:

   .social {
  display:none;
}

It would be ideal if it was also possible to load an entirely different CSS file based on the URL?

The pages on Tumblr all share the same head, so introducing different CSS for each page is not straightforward.

Answer №1

If your website is leveraging AJAX functionality (is it?), then you could consider the following approach in order to dynamically add style-sheets:

window.onpopstate = function() {
    if(window.location.path == '/about'){ 
        var css = document.createElement('style');
        css.type = 'text/css';
        css.rel = 'stylesheet';
        css.innerHTML = '.social{display:none;}';
        document.getElementsByTagName('head')[0].appendChild(css);
    }
} 

However, I would advise against this method.

Answer №2

Here is a suggested approach for you to consider

<script type="text/javascript>
    $(document).ready(function(){
        
        if(your_url_condition){
            //to ensure compatibility with IE
            if (document.createStyleSheet){
                document.createStyleSheet('style.css');
            }
            else {
                $("head").append($("<link rel='stylesheet' href='style.css' type='text/css' media='screen' />"));
            }
        }
    });
</script>

Give this method a try as it could be beneficial.

Best wishes!

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

Achieving Vertical Center Alignment in CSS

I'm having trouble understanding what's happening here: My goal is to vertically center an iframe and another div, both positioned alongside each other horizontally. What I've attempted is placing the iframe and div inside a new div called ...

Using regex in PHP to wrap the <ul> tag with <div> is a useful technique

My html snippet looks like this. <ul style="margin-left: 240px;"> <li>One</li> <li>Three <ul> <li>dfdf</li> </ul> </li> <li>dfds</li> </ul> ...

Creating consistent indentation in HTML code can be achieved without the presence of any unnecessary

When I add indentation to my HTML code, it results in extra whitespace between elements on different lines. <div id="nbcntcnt"> <a href="notset.html" class="nbcntbutton" id="snbb">Overview</a> <a href="notset.html" class="nbcntb ...

Issue with React nodemailer: net.isIP() is not a valid function

I'm currently working on a contact page in React and facing difficulties with the email functionality. My attempt involves using nodemailer and here is the snippet of my code: var nodemailer = require('nodemailer'); var xoauth2=require(&ap ...

The setInterval function does not function properly in IE8 when set to 0

I have a function called changeColor that updates the styling of certain elements in my HTML. In order to apply this function, I am using a timer like so: var timer = setInterval(changeColor,0); The issue I am encountering is that setting the time interv ...

Iterating through a JSON object to verify the presence of a specific value

I have a JSON Object and I am looking for a way in Angular 6 to search for the value "Tennis" in the key "name". Can you provide guidance on how to achieve this? { "id":2, "name":"Sports", "url":"/sports" "children":[ { "id":1, ...

Creating Angular Modal on ng-click

I'm facing a challenge with a seemingly simple task. Within an ng-repeat, I have a table of events. My goal is to enable users to click on the event name and view detailed information in a modal window. To achieve this, I have set up an ng-click="ev ...

Steps to assign a value to an input element using the state in a React application

Hey there, I hope everything is going well for you! I have a question regarding setting the value of an input field based on the state received from props. I've tried to populate the input with data from the "profile" state using placeholders, but it ...

Tips for implementing a "loading spinner" for each new ajax call using jQuery

Each time an ajax call is made, I want to display the loading icon/image. However, in my current code, the image only appears once and then disappears. Even when there are multiple ajax calls within a for loop, the image only shows once and vanishes after ...

There are two borders in place, with the second border present only on the right and bottom

Can someone help me achieve borders like the ones in this image? https://i.sstatic.net/qZHbK.png I tried using the after pseudo-element as shown below, but after learning from this discussion: Why can't an element with a z-index value cover its child ...

Enabling a download through PHP and jQuery

Although there are already numerous inquiries regarding how to force a download using PHP, I am struggling to pinpoint my mistake and determine the correct course of action. I have a list containing filenames, and my objective is to enable users to downlo ...

Replace the function if it is specified in the object, otherwise use the default functionality

Having a calendar widget written in TypeScript, I am able to bind a listener to a separate function. However, I desire this separate function to have default functionality until someone overrides it in the config object passed to the constructor. Within th ...

Can you point me in the direction of the Monaco editor autocomplete feature?

While developing PromQL language support for monaco-editor, I discovered that the languages definitions can be found in this repository: https://github.com/microsoft/monaco-languages However, I am struggling to locate where the autocompletion definitions ...

Leverage Vue's ability to assign data from a parent component to

I am struggling to bind the data (inputData) from the parent component to my child component. I have checked my code multiple times but cannot find where the mistake is. MainApp.js let vm = new Vue({ el: "#app", components: { &ap ...

Create a CSV document using information from a JSON dataset

My main goal is to create a CSV file from the JSON object retrieved through an Ajax request, The JSON data I receive represents all the entries from a form : https://i.sstatic.net/4fwh2.png I already have a working solution for extracting one field valu ...

Leverage the power of PHP files within your JavaScript code

I have a PHP file with some calculations that I want to integrate into another JavaScript file. How can I pass variables from JavaScript to perform calculations inside the PHP file? Here is my JavaScript code: $("#upload").on("click", function(){ var ...

The issue persists as the Ajax request continues to return false

I have created a verification program using an ajax request: $("#codeSbmt").click(function(){ var $input = $("#fourDigit"); codeCheck("codeTest.php?q=" + $input); }) function codeCheck(url) { var xh ...

Developing an interactive website utilizing AngularJS, WCF Service, and SQL Server

Exploring the possibilities of creating a web application, I stumbled upon AngularJS. With plans to incorporate WCF Service and SQL Server into my project, I am intrigued by what these technologies can offer. I want to ensure that AngularJS aligns with my ...

What is the best way to combine data from two rows into one row?

Can someone help me with merging 2 sets of Line data into a single row for each entry? For example, the 'Green Bay Packers @ Chicago Bears' row should display '+3.5000 and -3.5000', while 'Atlanta @ Minnesota' should show &apo ...

The JQuery chosen dropdown experiences a visual issue when placed inside a scrollbar, appearing to be "cut

Good day, I've been using the jQuery "chosen" plugin for a dropdown menu, but I encountered an issue with it being located in a scrollable area. The problem is that the dropdown items are getting cut off by the outer div element. I have provided a si ...