Prevent inheriting styles with jQuery Else / If conditions

I'm seeking advice on how to prevent elements from retaining the same inline styles in different breakpoints.

My goal is to adjust styling based on window width, similar to CSS media queries, but with the additional need to increment a numeric value using jQuery due to the limitations of CSS.

However, I've encountered an issue when applying opacity to the first 5 articles in a specific breakpoint. If I resize my browser back down to less than 720px, those articles keep the opacity, which is not desired.

Any assistance would be welcomed and appreciated.

$(document).ready(function() {
    function checkWidth() {
        var windowSize = $(window).width();
        if (windowSize >= 1 && windowSize <= 479) {
            var posTop = 0;
            $('#main article').each(function() {
                $(this).css('top', posTop + 'px');
                posTop += 160;
            });
        } else if (windowSize >= 480 && windowSize <= 719) {
            var posTop = 0;
            $('#main article').each(function() {
                $(this).css('top', posTop + 'px');
                posTop += 240;
            });
        } else if (windowSize >= 720 && windowSize <= 959) {
            $('#main article').slice(0, 5).each(function() {
                $(this).css('opacity', 0.4);
            });
        }
    }
    // Execute on load
    checkWidth();
    // Bind event listener
    $(window).resize(checkWidth);
});​

Answer №1

Insert the code

$('#main article').css('opacity', 1);
at the start of the checkWidth function. Also, consider renaming the function to better reflect its purpose. You can remove the unnecessary posTop variable and the last each loop. Here is a refactored version:

$(document).ready(function() {
    function changeStylesDependsOnWidth() {
        $('#main article').css('opacity', 1);

        var windowSize = $(window).width();

        if (windowSize >= 1 && windowSize <= 479) {
            $('#main article').each(function(i) {
                $(this).css('top', i * 160 + 'px');
            });
        } else if (windowSize >= 480 && windowSize <= 719) {
            $('#main article').each(function(i) {
                $(this).css('top', i * 240 + 'px');
            });
        } else if (windowSize >= 720 && windowSize <= 959) {
            $('#main article').slice(0, 5).css('opacity', 0.4);
        }
    }

    changeStylesDependsOnWidth();
    $(window).resize(changeStylesDependsOnWidth);
});​

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

Ways to minimize renders while toggling a checkbox

I'm currently working on developing a high-performance checkbox tree component. To manage the checked checkboxes, I am utilizing a parent level state that contains an array of selected checkbox IDs => const [selected, setSelected] = useState([]); ...

Encountering a 400 Bad Request error while using the SharePoint 2013 Rest API

I am currently developing a web component that utilizes jQuery for making a REST API request to rename a SharePoint subsite. The functionality is working as expected when using a custom button on EditForm.aspx within a list, and it also functions correctly ...

I am facing an issue in my Nextjs project where the Array Object is not being properly displayed

Hi there! I am new to Nextjs and currently learning. I recently created a component called TeamCard which takes imgSrc, altText, title, designation, and socialProfile as parameters. However, when attempting to display the socialProfile object array using m ...

How can I make sure that the combobox in my Ionic app is aligned with the text fields in a row?

From the image provided, it's evident that my HTML code looks like this: <ion-row> <ion-col> <ion-item> <searchable-ion-select isModal="true" name="country" valueField="code" [(ngModel)]="country" title="Country" ...

Execute AJAX function when loading a form populated from a MySQL/PHP database

I am currently working on a drop-down menu that is being populated from a MySQL table using PHP. The goal is to have a second drop-down menu triggered based on the selection made in the first form. This functionality works perfectly when a selection is mad ...

How come my dynamic source path doesn't function correctly unless I add an empty string at the end of it?

Recently, I encountered an issue while using Vue.js to dynamically create a source attribute using an object's properties. Here is the code snippet where I faced the problem: <img :src='"../assets/" + project.image.name + "." + project.image. ...

Facing a Challenge with Textures in ThreeJS ShaderMaterial

I seem to be having trouble with my texture not being displayed properly in three.js r71. The plane is just showing up black and I can't figure out what's wrong with my ShaderMaterial. I could really use another set of eyes to help me identify th ...

What is the best way to delete a nested child object using a specific identification number?

Here is the current json structure: $scope.dataList = [{ CompanyName: null, Location: null, Client: [{ ClientId: 0, ClientName: null, Projects:{ Id: 0, Name: null, } }] }]; I'm attempting to remo ...

Error: The filter argument must be in object form

Currently I am in the process of developing a REST API with an endpoint for posting movies. The request body is expected to contain only the movie title, which needs to be validated for presence. Upon receiving the title, I need to fetch other movie detail ...

Is there a way to display menu items in a list when hovering over the parent element using CSS?

Is it possible to make the code below run when hovering over (#cssmenu ul > li > ul > li ) with the mouse? #cssmenu ul > li > ul > li > ul { right: 1170px; } ...

Refreshing Datatable without having to refresh the entire webpage

I apologize for my limited English proficiency. Could you please explain to me the process of reloading data without refreshing the page using jQuery's datatable? I have been encountering issues with my table not properly reloading. Here is my view: ...

Using the 'client-side rendering' and runtime environment variables in Next.js with the App Router

In the documentation for next.js, it's mentioned that runtime environment variables can be utilized on dynamically rendered pages. The test scenario being discussed involves a Next.js 14 project with an app router. On the page below, the environment ...

The Impact of Spaces in Inline Scripting within Asp.NET

As I was coding in JavaScript on an Asp.NET page today, I encountered a small issue. Here's what happened: <script type="type/javascript"> var elementID = document.getElementById("<%=txtMyServerControl.ClientID %>") </script> T ...

How to Arrange AppBar Elements in Material UI with React

I'm struggling to align the CloseIcon to be at the end of the container using flex-end but I can't seem to locate where to apply that style. import React from 'react'; import { makeStyles, useTheme } from '@material-ui/core/sty ...

Animate text and div elements with bounce or fade-in effects when they appear on the screen in a React application

Animating the elements of my website is a simple task for me, however I am looking to have them animate only when they are visible on the screen without relying on pixels or offsets. I want the animations to be responsive, even in phone mode, without hav ...

Addressing responsiveness problems with Bootstrap navigation bar

Seeking assistance with setting up the fundamental bootstrap grid system. Despite my efforts, I am unable to make it work. Could someone guide me in creating the basic structure for the Navbar above? Specifically, focusing on using columns and rows with p ...

Enhance Material UI BottomNavigationAction by adding a pseudo-element

Trying to enhance a selected item with an additional UI element using a pseudo-element. Specifically, looking to add a line above the menu item. https://i.stack.imgur.com/MZnmw.png The code I've implemented is not displaying the desired line: const ...

When an Ajax call is made, my .html page transforms into a .php page using jQuery

The Issue While using my PHP function to send emails, everything goes smoothly. However, I'm facing an issue where I don't want the page to refresh, so I've implemented AJAX in the code below: reservation.html <form class="form-horizon ...

Passing a value from the Trigger button to the Modal button in Angular-UI Bootstrap

Seeking some help. I am working with angular-ui-bootstrap alongside php and mysql. My goal is to pass a value from a list of links (dynamically generated from php mysql) to a modal button each time the modal is loaded. HTML // The link below is generated ...

If the text width of a label exceeds the total width of its container, intelligently display a sub-string based on pixel calculations

I am looking to shorten the text inside a label if its width exceeds the total width of its container. Instead of displaying the full text, I want to display a sub-string of it. if (SensorType.Text.Length >= 25) { SensorType.Text = SensorType.Text ...