Tips for changing the style ID depending on the variable value

Currently, I am exploring the possibility of switching CSS styles using jQuery through a simple if condition. Is there an easy method to switch styles based on IDs? In my case, I have two CSS blocks each with different IDs.

Here is an example:

<style id="styleA">
.myDiv {
    display: none; 
}
</style>

<style id="styleB">
.myDiv {
    display: block; 
}
</style>


<div class="myDiv">Lorem</div>


<script type="text/javascript">

    $(document).ready(function()
    {
        var style = 4;

                if (style < 5)
                {
                    //apply css from styleA
                } 
                else
                {
                    //apply css from styleB
                }
    });
</script>

Answer №1

Your code has a multitude of errors that need addressing.

Start by familiarizing yourself with the style tag: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style

The style tag does not use any specific id (aside from generic behavior), but you can utilize the title for alternative styles or employ the scoped attribute and place the style tag within the element requiring formatting.

A more optimal approach would be to define additional classes in a single style tag for the same element. For example:

<style>
.myDiv.hidden {
    display: none; 
}

.myDiv.shown {
    display: block; 
}
</style>

This simplifies the process of switching styles by simply adding or removing class names from elements. Instead of using hidden/shown, consider using class names that include a number from your style variable.

Furthermore, the logic in your if/else block appears to be flawed.

Answer №2

To enhance the styling options, I suggest assigning a specific class to the body element based on the style value:

$('body').addClass('style'+style);

This approach allows for easy customization of styles for different types.
For instance:

body.style4 .myDiv{
    display:none;
}
body.style5 .myDiv{
    display:block;
}

Answer №3

Test out the following code snippet:

<style type="text/css>
    .custom-style1 {
        display: none; 
    }

    .custom-style2 {
        display: block; 
    }
 </style>


    <div id="myCustomDiv" class="">Lorem</div>


    <script type="text/javascript>

        $(document).ready(function()
        {
            var customStyle = 4;

                    if (customStyle < 5)
                    {
                        $('myCustomDiv').addClass('custom-style1').removeClass('custom-style2');
                    } 
                    else
                    {
                        $('myCustomDiv').addClass('custom-style2').removeClass('custom-style1');
                    }
        });
    </script>

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

Troubleshooting problem with divs overlapping in Internet Explorer 7

Check out this webpage: http://jsfiddle.net/aJNAw/1/ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta ...

Bootstraping Twitter with PHP session starting has become a standard practice in modern

Currently, I am developing a website using PHP and Twitter Bootstrap. The issue I'm encountering is that if I include session_start() first, the layout gets messed up because Bootstrap needs <!DOCTYPE html> to come before it. On the other hand ...

Utilizing AJAX to transmit data from an HTML page to a controller in Asp.net

Recently, I started using .net and encountered an issue where I'm attempting to transfer data from a .html file to the controller using AJAX. Here is my ajax call: var dataValue = { ID: 10, Name: 'Test' }; ...

How jQuery Autocomplete handles lowercase conversions in queries

Currently, I am utilizing the jQuery Autocomplete plugin 1.1 for a project. Below is my calling code: $("#txtCombo").autocomplete("http://www.example.com/autocomplete.php", { autoFill: false, width: 550, minChars: 3, ...

Make a <div> element that has a fixed size, but allows for scrolling text inside

I have tried searching the forum for a solution to my problem, but haven't found one yet. I am trying to create two "divs" with fixed height and internal scrolling. However, whenever I add text inside one of them, its height increases accordingly. Wha ...

Why is Django not recognizing my ajax request when using the `is_ajax()` function?

After sending a GET request and processing the data to obtain a redirect link, the function seems to be having trouble entering the is_ajax() block. $(document).on('click', '.top_up_pay', function (e) { var post_data; e.preventDefa ...

The CSS property 'clear:both;' is not functioning properly on IE7 browsers whereas works fine on IE8/IE9, Firefox, Chrome, and other browsers

I have been receiving feedback from visitors about some issues on one of my websites. Those who reached out to us are using IE7 on Windows XP. I was able to recreate the problem by using IE7 or by mimicking it in compatibility mode with IE7 document mode o ...

Prevent IonContent from scrolling to the bottom or top when using Ionic framework

In my Ionic app, I have a long text page with 2 buttons that trigger the actions scrollToBottom and scrollToTop. Due to the length of the page, I have set the scroll duration to be 30 seconds. I am facing two issues here: How can I stop the scrolling ...

What is the best way to save the city name received from geolocation into a variable and then make an AJAX request?

<script> new Vue({ el: '#fad' , data: { data: {}, }, mounted() { var self = this; navigator.geolocation.getCurrentPosition(success, error); function success(position) { var GEOCO ...

Can we access an element within the document using its context?

One common method to access an element is by using its id: <div id="myId"></div> <script type="text/javascript"> $(document).ready(function(){ $('#myId').something(); }); </script> However, there are inst ...

retrieve the value of a text form using jQuery and its corresponding id

I need help with a basic HTML form that includes jQuery. My goal is to: 1) Retrieve the value into a JavaScript variable. 2) Send it as JSON to a server. Here is the form: <div data-role="main" class="ui-content"> <data=role "form" ...

Struggles with Managing 5-Digit Unicode Characters with jQuery

I need some assistance with using larger Unicode images in JQuery, as I am encountering difficulties that I cannot seem to resolve. For example, when I use the following line of code: if ( IsItOverFlowing() ) { $HM.text("\u2302"); } a charming litt ...

Error with the jQuery scrolling plugin

Currently, the script is set up this way: jQuery(document).ready(function(){ var windheight = jQuery(window).height(); var windTop = jQuery(window).scrollTop(); var windbottom = windheight + windTop ; jQuery.fn.revealOnScroll = function(){ return this.e ...

Unwillingness of Ajax to accept Names containing apostrophes as a parameter

$(".loadingPnl").removeClass('hdn'); var siteurlA = window.location.protocol + "//" + window.location.host + _spPageContextInfo.siteServerRelativeUrl; var callUrl = siteurlA + "/_layouts/15/SynchronyFinancial.Intranet/CreateMySite.aspx/S ...

Canvg | Is there a way to customize canvas elements while converting from SVG?

Recently, I encountered an issue with styling SVG graphics dynamically generated from data. The SVG graphic appears like this: To address the problem, I turned to Canvg in hopes of converting the SVG into an image or PDF using a hidden canvas element. How ...

Traversing JSON Data using Vanilla JavaScript to dynamically fill a specified amount of articles in an HTML page

Here is the code along with my explanation and questions: I'm utilizing myjson.com to create 12 'results'. These results represent 12 clients, each with different sets of data. For instance, Client 1: First Name - James, Address - 1234 Ma ...

jQuery event.preventDefault not functioning as expected

I am attempting to use jQuery's preventDefault() method, but when I submit the form, it still displays the default behavior and reloads the page. Here is the code from index.html: <body> <script src="/socket.io/socket.io.js"></script& ...

When displaying content within an iframe, toggle the visibility of div elements

I'm attempting to toggle the visibility of certain page elements based on whether the page is loaded in an iframe. <script>this.top.location !== this.location && (this.top.location = this.location);</script> The above code succes ...

Altering documents post Bower installation

I took the initiative to manually download the css and js files for an angular module (here). In order to make a small adjustment, I modified the css (specifically changing max-width in the media query): Original: @media only screen and (max-width: 800px ...

Issues with FullCalendar.js failing to consistently fire when used in conjunction with JS/Ajax/ColdFusion

Attempting to troubleshoot an issue with FullCalendar.js integration on an external page called "calendar_summary.cfm", which is part of a series of pages reloading on a main page. The data from calendar_summary.cfm is transferred into FullCalendar.js thro ...