Updating a CSS file through jQuery is proving to be ineffective

After searching extensively on Stack Overflow and other websites, I have not been able to find a clear answer to my question regarding changing a CSS class (#navbar a) after a specific function is triggered. My understanding of jQuery and JavaScript is limited, so any help would be appreciated.

Here is the code snippet that I tried but did not work as intended:

$('link[href="Style.css"]').addClass('#navbar a').css('width', '20px');

This is the JavaScript / jQuery code in question:

<script>
window.onscroll = function() {myFunction()};

var navbar = document.getElementById("navbar");
var sticky = navbar.offsetTop;

function myFunction() {
  if (window.pageYOffset >= sticky) {
    navbar.classList.add("sticky")
        navbar.style.align = 'auto';
        navbar.style.width = '100%';
        $('link[href="Style.css"]').addClass('#navbar a').css('width', '20px');
  } else {
    navbar.classList.remove("sticky");
      navbar.style.width = '80%';
  }
}
</script>

This is the content of the CSS file:

#navbar a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  width: 25%;
  text-decoration: none;
  font-size: 35px;
  padding: 20px 0px;
}

Below is the complete HTML code for reference:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width;initial-scale=1;height=device">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="Style.css">
</head>
<body style="background:#101010">
<div class="header">
  <h2>FELLE</h2>
</div>
<div id="navbar">
  <a class="active" href="">Hjem</a>
  <a href="Historie.html">Historie</a>
  <a href="Hyttefelt.html">Hyttefelt</a>
  <a href="Annet.html">Annet</a>
</div>
<div class="container" align="middle">
    <img src="Bilder/Felle_Butikk.jpg" alt="Felle butikk"/>
    <object data="Tekster/Felle_Butikk.txt"></object>
    <img src="Bilder/Solhomfjell.jpg" alt="Solhomfjell i nissedal"/>
    <object data="Tekster/Solhomfjell.txt"></object>
</div>

<script>
window.onscroll = function() {myFunction()};

var navbar = document.getElementById("navbar");
var sticky = navbar.offsetTop;

function myFunction() {
  if (window.pageYOffset >= sticky) {
    navbar.classList.add("sticky")
        navbar.style.align = 'auto';
        navbar.style.width = '100%';
        $('link[href="Style.css"]').addClass('#navbar a').css('width', '20px');
  } else {
    navbar.classList.remove("sticky");
      navbar.style.width = '80%';
  }
}
</script>
</body>
</html>

Answer №1

$('link[href="Style.css"]').addClass('#navbar a').css('width', '20px');
<link href="Style.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

The code snippet above targets the link element but does not actually modify the stylesheet.

https://i.sstatic.net/Pa5a0.png

Since the element being styled is not initially visible, setting its width to 20px will have no visual impact.


If you want to apply styles directly to the actual elements (and include the stylesheet), you can use the following jQuery script:

jQuery('#navbar a').css('width', '20px');

Alternatively, you may refer to this question on Stack Overflow for more information on changing CSS rules dynamically.

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

jQuery not functioning properly when attempting to add values from two input boxes within multiple input fields

I am facing an issue with a form on my website that contains input fields as shown below. I am trying to add two input boxes to calculate the values of the third input box, but it is only working correctly for the first set and not for the rest. How can ...

Shifting the Ion Menu side dynamically based on screen size: A step-by-step guide

Working with Ionic 4, I encountered the need to dynamically change the side property of ion-menu. On larger screens, ion-menu is always visible or static, whereas on smaller screens, it remains hidden until the user clicks on the ion-menu-button. My goal i ...

Enhancing Layouts with Bootstrap 5: Implementing Space Between Rows

Can anyone help me figure out how to add a vertical gutter between two rows with Bootstrap 5? I've tried using g-* and gy-*, but as shown in this jsfiddle, it doesn't seem to be working. Any ideas on what might be causing this issue? From my und ...

Seamless Exploration with Google StreetView

Google uses a special effect on StreetView images to transition smoothly between them. You can see an example of this effect in the images below, with the second image showing it being applied. My question is: How can I incorporate this same effect into m ...

Dynamic website where each page is loaded based on the user's previous interaction

Can I get your opinion on something? I'm currently working on an ajax webpage. The links on my page make a GET request to the URL they are linked to, extract the div.content, and then update the content of the current div.content. Strangely, this GET ...

Show a webpage depending on specific JavaScript criteria

I have a condition in my JavaScript code that determines whether or not a user should be granted access to a specific page. However, I don't want users to be able to directly access this page even if they know the URL. This page contains both HTML and ...

CSS3 rotation animation - begins to rotate and then halts at a specific angle

I attempted to develop a function that initiates a spin, replaces an image, and then stops the spin. However, when I remove the spin class, it jerks abruptly. How can I halt the spinning smoothly at a specific frame? setTimeout(function() { $('. ...

"Exploring the concept of odd and even numbers within the ng-repeat

Can anyone help me with detecting odd or even numbers in an ng-repeat? I have created a fiddle that displays some dots randomly showing and hiding. Now, I want to change the background color so that odd numbers are green and even numbers are red. function ...

tips for expanding the size of your images

Hey there, I'm looking for some help with the code below. I need to increase the width of the images and remove the border of the slider div which is currently showing a white border that I want to get rid of. I am using JavaScript to display the imag ...

Can anyone explain the meaning of (0, _jquery["default"]) in relation to jQuery selectors or functions?

Trying to implement jQuery on an offline page can be challenging when dealing with EmberJS, RequireJS, and other technologies. My goal is to replace complex code with simple jQuery. The HTML below should respond to user interaction: Loading i ...

tips for linking my webpage with the database

While working on a registration page, I encountered an issue where the entered information was not being stored in the database. Instead, an error message appeared: Notice: Undefined variable: sql in C:\xampp\htdocs\Bawazir\Untitled-1. ...

Ensuring full height on Bootstrap 4 columns without triggering a scrollbar in the browser

I'm currently working with Bootstrap 4 and attempting to make 3 columns on the page fill 100% height, only displaying scrollbars within the columns and not on the entire page. I have experimented with applying h-100 to the row div, as well as implemen ...

Display a preloader image while waiting for the content to load using jQuery or AJAX

Hey there, I could really use some help with a little issue. I've been trying to use the click() and load() functions to bring my content into a specific CSS class. $("#feed").click(function(){ $(".homefeed").load("feedcontainer.php"); ...

Is the text in the React chat application too lengthy causing a bug problem?

In my chat application built with React, I am facing an issue where if a user types more than 100 characters, the message gets cut off. How can I fix this problem? Please refer to the image below for reference. https://i.sstatic.net/DLNyH.png {Object.keys ...

Using Jquery Ajax with jsonp for dynamic data retrieval

Hey everyone, here's the code snippet I'm working with: $.ajax({ 'url': 'myUrl', 'dataType': 'jsonp', crossDomain: true, 'data': { // sample data }, 'success&ap ...

jQuery function to display character count updating with each keystroke, indicating 1 character is remaining when none

I have implemented a feature using jQuery to display the remaining characters in a text input field. The functionality is working well, but I am encountering an issue where it shows 1 character remaining when it reaches 0, even though it doesn't allow ...

Transferring radio button selections from a form to Google Analytics upon submission

I have a form where I can capture user selections from radio buttons and a drop-down element using the .blur() event. However, I am struggling with pushing this data to Google Analytics (GA) when the user clicks the submit button. Currently, my script loo ...

Can the html content provided by the user be extracted and highlighted?

When utilizing the onClick function in ReactJS, I am receiving the entire property which includes Lorem Ipsum is simply dummy text. However, I only require the highlighted content like "is simply dummy". Is there a way to achieve this?</p> ...

A sporadic glitch in IE10 appears while attempting to translate text with a border-radius feature

I need some advice regarding a rendering issue I am experiencing in IE10. I have created an animated-flip effect that works perfectly in all the browsers I need it to. However, during testing, I noticed random border-like lines appearing for no apparent re ...

Is it feasible to modify a JavaScript value through the PHP GET method?

My HTML file contains the following JavaScript code: var a=["","#"] I want to append a value after the # symbol by specifying that value in the website URL. For example: site.com/#value Therefore, the updated JavaScript code will be: var a=["","#va ...