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

Another option instead of sending back a JavaScript tag in the Ajax response

After making an ajax request in my code, I receive some HTML that contains specific elements requiring custom event handling. For example: <div> <!--some html--> <button id='specialbutton'></button> </div> <scr ...

Flexbox problem - uneven heights

I have set up a flex box layout and you can view the codepen link here:- https://codepen.io/scottYg55/pen/zYYWbJG. My goal is to make the pink backgrounds in this flexbox 50% of the height, along with the background image so it resembles more of a grid sy ...

css - Tips for reducing the speed of inertia/momentum scrolling on mobile devices

I have been working on creating a scrollable card gallery using a CSS grid layout. The structure I am following is similar to this: <div class="gallery-wrapper"> <div class="gallery-container"> <div id="card-1" class="gallery-ca ...

Accessing the current window dimensions using CSS

I'm experimenting with a way to set the background of the entire body element. <html> <head><head/> <body> <div class="wrapper"></div> </body> </html> How can I determine the height and width of the cu ...

The navigation bar fails to display correctly on Internet Explorer 10

Encountering problems with IE 10. View the code here. While on the latest Chrome and Firefox, all text appears in a single line, IE displays it differently. Other modern browsers produce a different result altogether. ...

Increase the value of count (an AJAX variable) by 4 upon clicking the button, then send it over to the PHP script

I'm facing an issue where my AJAX variable is only updating once by +4 each time a button is pressed. I need assistance on how to make it continuously work. index.php - AJAX <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.m ...

Monitor the number of ng-repeat items altering within a directive

I am using the angular-sly-carousel directive to display some data. The data is dynamically added as the user scrolls down, so I need to reload the sly carousel options after scrolling. Is there a way to detect when the length of ng-repeat elements change ...

Incorporating JSON objects into MySQL through a For Each loop - Checkbox Selections

My attempt to update the table (auth_users) with checkbox values using QueryBuilder and the provided code is not functioning correctly for the checkboxes on my form. I suspect that the issue lies in $key, "'".$value."'" not matching the DB field ...

Ways to deactivate a button within a Kendo Grid cell

I am trying to include 2 buttons in a cell, where one button calls a specific function and the other button disables the previous button that calls the function. In my template column, I have implemented the following: return '<button kendo-button ...

jQuery class toggle malfunction

I have a series of list items with specific behavior when clicked: Clicking a list item will select it and add the class .selected If another list item is clicked, the previously selected item becomes unselected while the new one becomes selected If a se ...

Dealing with currency symbols in Datatables and linking external sources

I'm having trouble linking an external link to the "customer_id" field. The link should look like this: /edit-customer.php?customer_id=$customer_id (which is a link to the original customer id). I am creating a detailed page with most of the informati ...

Refresh the pagination in a jQuery DataTable

I have incorporated DataTable for pagination within my table. The data in the table is loaded through ajax requests, and I am utilizing my custom functions to populate the table manually by interacting with its DOM elements. However, I am facing an issue ...

Is it possible to maintain tab focus instead of visual focus when navigating past the skip navigation menu for improved accessibility?

My website features an accessibility skip navigation menu that utilizes named anchors to navigate to different content areas. These content areas, including the top menu, left menu, main body content, and footer menus, contain links within them. When I u ...

is it possible to adjust the height of a tableRow in mui?

I recently created a table component using Mui. I've been attempting to adjust the height of the tableRows, but so far I haven't had any success. Below is my code snippet: import React, { memo } from "react"; import { ActionItemType, ...

What is the proper way to define the routes for an ajax button_to?

I have successfully integrated an ajax-powered button to manage adding and removing a calendar event from a user's "wish list". The button performs as a toggle-switch, allowing users to add events if they are not already on the wish list, and remove t ...

Managing the jQuery.noConflict function

Upon review, I noticed that the scripts I inherited start like this: var $j = jQuery.noConflict(); The purpose behind this code is not clear to me. While I understand the intent is to avoid conflicts, I am uncertain about the specific conflict it aims to ...

Reposition the div element on mobile devices using media queries

Hello, I'm facing an issue on mobile with my website: dev site Today, I implemented a dropdown menu with flags to allow language switching. However, the dropdown in mobile is appearing under the hamburger nav bar. I was thinking of using media querie ...

What could be causing my Angular code to submit back unexpectedly?

My goal is to make an initial call to the database to populate some dropdowns, after which all actions are done through AJAX. However, whenever I click a button on the page, it seems to be posting back and calling the function that fetches dropdown values ...

Should you choose a pre-built CSS framework or create your own from scratch?

Have you come across a framework that meets your project needs with just a few tweaks, or have you forged your own path along the way? What advice do you have for someone facing this decision and focusing on priorities like: Implementing a CSS reset Refi ...

Why does this inner HTML table always adjust its width based on the content within it? Is there a way to make it match the width of its container instead

I'm not very familiar with HTML and CSS, and I've come across a problem. Here is the CSS structure in question: <!-- TECHNICAL REFERENCE: --> <div id="referenteTecnicoTab"> <table width="800px" class="standard-table-cls table-he ...