Having trouble getting jQuery css() function to work properly?

<a href="https://www.timeatthebar.co.uk" target="_blank"><img id="icon-img" src="assets/img/tabicon2.png" class="position-absolute top-50 start-50 translate-middle" style="max-width:113px; top: 43%!important; z-index:0;" alt=""></a>
<a id="savethepub" class="tab-base navbar-brand navbar-brand position-absolute top-50 start-50 translate-middle" style="top: 84%!important; font-size:22px;" href="#">Save The British Pub</a>

Encountering a JQuery problem, the provided HTML code appears to be correctly set up. The script below is meant to interact with a button on the webpage. Testing indicates that the button functionality works as intended, although some CSS styles are not being applied.

var button = $( "#collapser" );
var tabimg = $( "#icon-img" );
var stp = $( "#savethepub" );

var bntclicked = false;

button.click(function() {
    if (bntclicked === false) {
        tabimg.css({"max-width":"70px", "top":"8%!important", "left":"21%!important", "z-index":"0"})
        stp.css({"font-size":"22px", "top":"7%!important"})

        bntclicked = true;
    }
    else if (bntclicked === true) {
        tabimg.css({"max-width":"113px", "top":"43%!important", "left":"50%!important", "z-index":"0"})
        stp.css({"font-size":"22px", "top":"84%!important"})

        bntclicked = false;
    }
});

Code for the Button:

<button id="collapser" class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>

Answer №1

The problem arises from the use of the !important flag in the CSS properties within the object passed to the css() function. These flags are invalid and should be removed.

Similarly, any !important flags added inline in the HTML should also be removed as they serve no purpose. Inline styles take precedence over everything else, rendering the !important flag redundant unless used elsewhere in the stylesheet.

It is recommended to minimize the use of the !important flag and rely on selector precedence instead. The only justifiable scenario for its use is when overriding styles from an external source beyond your control, even then prioritizing rule precedence is preferred.

You can simplify the logic by utilizing classes for styling in the following example:

var $button = $("#collapser");
var $tabimg = $("#icon-img");
var $stp = $("#savethepub");

$button.on('click', () => {
  $tabimg.add($stp).toggleClass('active');
})
#icon-img {
  position: absolute;
  max-width: 113px;
  top: 43%;
  z-index: 0;
}
#icon-img.active {
  max-width: 70px;
  top: 8%;
  left: 21%;
}

#savethepub {
  position: absolute;
  top: 84%;
  font-size: 22px;
}
#savethepub.active {
  top: 7%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="collapser">Collapser</button>

<a href="https://www.timeatthebar.co.uk" target="_blank">
  <img id="icon-img" src="assets/img/tabicon2.png" class="position-absolute top-50 start-50 translate-middle" alt="">
</a>
<a id="savethepub" class="tab-base navbar-brand navbar-brand position-absolute top-50 start-50 translate-middle" href="#">Save The British Pub</a>

Answer №2

The issue at hand is the failure occurring when attempting to include !important in the CSS function, which is not permitted. To achieve the desired outcome, there are a few options available. One approach involves placing the desired CSS within a class and toggling that class (my preferred method). Alternatively, you could utilize the .attr() function to modify the style attribute entirely. Another possibility is using the cssText selector, enabling the addition of multiple CSS rules with one key. See example below:

// Adjust width
$('#txt').css({
    'cssText': 'width: 220px !important; font-size: 12px;'
});

For further assistance, refer to this link:

Below is your code without the use of !important:

button.click(function() {
    if (bntclicked === false) {
        tabimg.css({"max-width":"70px", "top":"8%", "left":"21%", "z-index":"0"})
        stp.css({"font-size":"22px", "top":"7%"})

        bntclicked = true;
    }
    else if (bntclicked === true) {
       tabimg.css({"max-width":"113px", "top":"43%", "left":"50%", "z-index":"0"})
       stp.css({"font-size":"22px", "top":"84%"})

       bntclicked = false;
   }
});

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

As the user types input in real time, automatically adjust the form's value before submission

I'm looking for assistance in dynamically updating the value of a form submit button as the user types into an input field. <form> <input type="text" name="number" id="number" value = 0 /> <input type="submit" id="submit"> ...

Insert an element into a JSON collection

I am currently working on a JavaScript function that utilizes an ajax call to retrieve data from an API in the form of a JSON array. Here is a snippet of the array structure that I receive: [ { "ErrorType": "Errors", "Explanations": [ { ...

Is there a better alternative to using nested async callbacks?

Imagine I need to execute asynchronous actions like sending an email and updating the database. Usually, I would write code like this: send_email(function(err, id){ if(err){ console.log("error"); }else{ update_database(id,function( ...

storing data in a nested child object within an array

I am attempting to include variables into the existing JSON data that is received from an API whenever a user clicks on the add button. However, I encountered this error message: Cannot find a differ supporting object '[object Object]' of type & ...

Unlocking the Secrets: Adding Multiple Contents to Your Master Page in ASP

I need some clarification on a dilemma I'm facing. My master page has a content placeholder that is used by all subpages: <%@ Master Language="C#" AutoEventWireup="true" CodeFile="Site.master.cs" Inherits="SiteMaster" %> <!DOCTYPE html> ...

"Unleashing the Power of Effortless Object Unwr

Looking for a better way to convert a raw json snapshot from Firebase into a JS class. My current method is lengthy and inefficient. Does anyone have a more optimal solution? Class: class SuggestedLocation { country_slug region_slug slug marker_ty ...

typescript mock extending interface

I'm currently working with a typescript interface called cRequest, which is being used as a type in a class method. This interface extends the express Request type. I need to figure out how to properly mock this for testing in either jest or typemoq. ...

flexanimate functioning only on the first attempt

I've been attempting to use jQuery and AngularJS to control the movement of a flex slider using keyboard input. However, I am finding that it only works once with FlexAnimate and then stops working. Can anyone offer insight as to why it is not functio ...

unable to choose an option if more than one radio button is being used

I am having trouble with two radio buttons that are supposed to select the gender of an applicant and the gender of the applicant's child. Both buttons are not functioning properly. Can someone assist me with this issue? Here is the code I am using: ...

Chrome runs requestAnimFrame at a smooth 60 frames per second, while Firefox struggles to keep up at

I recently developed a canvas animation using requestAnimFrame and saw great results in Chrome. However, when I viewed it in Firefox, it seemed like a slideshow was running instead of a smooth animation. I'm unsure what could be causing this issue. F ...

Send a Symfony form between different views using ajax

I am currently working on creating a tabs navigation system with a central block that displays a Symfony form. Whenever I click on a tab link, I want to reload the block with the form and data related to that tab. The challenge I am facing is how to pass ...

Implementation of cascading selects using JQuery

As a newcomer to JQuery, AJAX, and PHP, I am attempting to create a form with linked dropdowns that will populate initial data for a new MySQL record. Despite using the JQuery chained select remote plugin, I am struggling to retrieve the data for the secon ...

How can I quickly duplicate the design of a JSON Object?

Perhaps the title is a bit basic. Essentially, I am looking for something similar to mysqldump ... --no-data .... For instance, I have a JSON object structured like this: { "key1" : "value1", "key2" : "value2", "key3" : { "key3a" : 1, "key ...

Issue encountered when trying to integrate a CSS sticky footer with a liquid/fluid layout

I've been attempting to incorporate the CSS Sticky Footer technique demonstrated at cssstickyfooter.com. (I also experimented with Ryan Fait's solution without success). I believe I've followed all the instructions correctly. I have a conta ...

What is the best way to create a sign-up box that appears on the same page when you click on the sign-up button

I am interested in implementing a 'sign up' box overlay at the center of my index page for new users who do not have an account. I would like them to be able to easily sign up by clicking on the 'sign up' button. Once they complete the ...

web browser freezing when trying to open bigger files

I have a project where I need to download multiple JSON data files and visualize them using D3 data charts. However, when the page loads, it takes around 2-3 minutes to download and visualize the files, especially on mobile devices. This causes the browser ...

Differences between Global and Local Variables in Middleware Development

While exploring ways to manage globally used data in my research, I stumbled upon this question: See 2. Answer After integrating the suggested approach into my codebase, I encountered a problem that I would like to discuss and seek help for. I created a ...

Just systems that have been positively identified

Greetings! I am currently in the process of creating a small online stock management system using PHP. However, my goal is to restrict access to this web app to only certain systems that I designated. I want to ensure that only the systems under my contro ...

What is the best way to utilize a JavaScript for loop to translate ASCII code into a word?

I am attempting to solve this code in order to determine the name associated with the array below: let numbers=[42,67,74,62,6A,1F,58,64,60,66,64,71]; for(let i=0;i<numbers.length;i++) { numbers[i] = numbers[i]+1; } Any guesses on what the resultin ...

Retrieve an element by its index using jQuery

I need to change the background color of a specific li element in an unordered list based on its index. Is there a way to do this without having to loop through the entire list? Are there any methods available to achieve this functionality? Below is my co ...