Easy selector for choosing jquery css backgrounds

Here is a simple background selector that I created.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 <head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
    <title>jQuery Demo</title>
    <link rel="stylesheet" type="text/css" media="screen" href="Normal.css" />

    <script type="text/javascript">

    $(document).ready(function(){

        $("#StyleContrast").click(function() {
           $("link[media='screen']").attr("href", "Contrast.css");
         });

         $("#StylePrint").click(function() {
           $("link[media='screen']").attr("href", "Print.css");
         });

         $("#StyleNormal").click(function() {
           $("link[@media='screen']").attr("href", "Normal.css");
         });

     });

       </script>

 </head>
 <body>
    <h1>Select Your Style:</h1>
    <ul>
       <li><a id="StyleContrast" href="#">Contrast</a></li>
       <li><a id="StylePrint" href="#">Print</a></li>
       <li><a id="StyleNormal" href="#">Normal</a></li>
     </ul>
 </body>
 </html>

I have the following files in the same directory:

- Normal.css

- Print.css

- Contrast.css

All with a basic structure like this:

body {background-color:#000000;}

When you initially visit the URL, it displays the Normal.css style (as expected).

You can then switch between Print.css and Contrast.css styles correctly.

However, switching back to Normal.css doesn't work as expected.

Could you identify what might be wrong with the code?

Answer №1

 $("#StyleNormal").click(function() { 
       $("link[media='screen']").attr("href", "Normal.css"); 
     }); 

It is recommended to

 $("#StyleNormal").click(function() { 
       $("link[media='screen']").attr("href", "Normal.css"); 
     }); 

Additionally, I suggest updating your jQuery version to 1.4.2.

You utilized [@media='screen'] instead of simply [media='screen']

In jQuery 1.4.2 (and possibly in jQuery 1.3), the use of @ for attribute selection is no longer supported. You had it correct in the first two instances within your code, just not the last one. :D

Answer №2

To enhance the efficiency, consider including a designated class (e.g. "toggle") in your hyperlinks and modify your jQuery script as follows:

 $(function(){
    $(".toggle").click(function() {
       $("link[media=screen]").attr("href", $(this).text() + ".css");
     });
 });

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

Error: Unable to access property XXX because it is not defined

Upon trying to serve my application, I encountered errors in the console similar to the one below. It seems to be related to angular-animate. How can I resolve this issue in angular? Can someone assist me with fixing it? Uncaught TypeError: Cannot read pr ...

implement a night mode with a single click

I attempted to implement a dark mode using jQuery, but it is not working as expected. I am seeking assistance. I would like to enable the dark mode when clicking on the #btntheme ID, but for some reason, it is not functioning correctly. My goal is to be ...

How can we use response.render in Express.js to render HTML on the client side?

I have set up a simple Express.js application with the following routes: router.get('/', function(req, res){ res.render('login'); }); Everything is working fine - when I log into the main page on my localhost, the HTML fro ...

Error occurs in Typescript when attempting to store data in a record using a pointer

When working with nodes and organizing them into a tree structure, I encounter an issue: This is the definition of the interface: interface IDataObj { children: IDataObj[], frontmatter : { type: string, title: string, path: string}, name: str ...

Is there a way to make FullPage and Lightbox compatible with each other?

Currently utilizing Fullpage.js for my website, I am looking to incorporate a lightbox in one of the sections. However, upon attempting to load the script and CSS, my fullpage layout breaks and the sections collapse. I have experimented with placing the ...

Troubleshooting issues with JSON compatibility within the OnChange event

Initially, I wrote this code to retrieve a single data point. However, I realized that I needed more fields returned when the drop-down select menu triggered an onchange event. So, I switched to using JSON, but now it's not returning any data. The dro ...

Locating Undiscovered Users within mongodb

I have created a post collection where each user who marks a post as read has their user ID added to an array within the post document. Now, I am attempting to identify which users have not read certain posts by utilizing the $nin function while iteratin ...

When working with AngularJS and Karma-Jasmine, it is recommended to flush the $httpbackend only when there are pending requests present

Can I use $httpbackend.flush(); only when there are pending requests? This way, I can avoid receiving: Error: Unflushed requests: 1,2,3,...,n Or Error: No pending request to flush! ...

Issue with UseState causing a re-render not to be triggered

My orders list state works perfectly on the initial update. However, when an order in the database gets updated, the order list is updated but fails to trigger a re-render even with <...> const [orders, setOrders] = useState([]); useEffect(( ...

Check to see if a guest has shown support or followed an outside party

When you already follow a company on Twitter, the "Follow Us" button of that company will automatically turn grey, regardless of the domain. So, how can you determine if User-X is following companies A, B, and/or C based on their Twitter handles? The same ...

Issue with value not updating following second ajax request

My project involves making an ajax call to render out a shopping cart using jQuery. function showShoppingCart() { $.ajax({ url: 'functions/show-cart.php', type: 'POST', dataType: 'json', }) ...

What is the process for integrating CSS-styled text into CKEditor?

Currently, I am developing plugins that are designed to incorporate various elements like images and tables into the editor. My objective is to be able to view these elements in their final visual form within the editor itself. To achieve this, I plan on a ...

A pair of boxes sitting next to each other, both occupying 50% of the space but slightly longer in length and not aligned on the same level

My goal is to have two side-by-side boxes that fill the entire width of the screen. However, I'm facing an issue where each box exceeds 50% width by about 10 pixels. What could be causing this discrepancy? #sides { padding-top: 40px; padding- ...

Guide on linking a textarea with a boolean value in the child component

I have created a form component consisting of two components. The first component looks like this: <template> <div class="flex flex-col items-center justify-center gap-2"> <div class="flex w-[80%] items-center justify-ce ...

Determining if a date has passed using moment.js, focusing solely on the date

Is it possible to determine if a date has passed based solely on the date itself? Currently, I am using !moment(moment().format("LLL")).isBefore(moment.unix(data.dueDate._seconds).format("LLL")). However, this approach also takes into account the time. F ...

Is there a way to use getJSON to append divs and animate them one by one as they are displayed?

Hey everyone! I'm currently using a getJSON function to append some divs, but I want to make the display more dynamic. Is it possible for each div to appear milliseconds apart? For example, the first div fades in, followed by the second, and so on. H ...

The lower division remains static when the browser window is resized

Why does the div with class .lower not move to the bottom of the page when the screen is resized? Could this be because of its CSS property position:absolute;? Check out the code snippet here. #lower { width: 100%; position: absolute; bot ...

Tips for extracting links from a webpage using CSS selectors and Selenium

Is there a way to extract the HTML links per block on a page that renders in JavaScript? Would using CSS or Selenium be more effective than BeautifulSoup? If so, how would I go about utilizing either of those methods to achieve the extraction of the HTML ...

Grab and place to retrieve the ID of a table row

I am dealing with tables that have sub-tables. Here is a reference Fiddle. When I drag and drop rows from the sub-table, my code looks like this: $('.row_position>tr').each(function() { selectedData.push({'id':i,'key&ap ...

Assign a value to the <li> element and modify the prop when the user clicks using vue.js

I've been attempting to update props from child to parent using the $event in an @click event. I sent the data and $event from the parent to the child as shown below. in the parent component: <v-filter :sortTypePrice="sortTypePrice" :sort ...