Media Query Failing to Perform as Expected

I have been working on implementing jQuery that can respond in sync with my CSS media queries on my website.

Currently, I am facing an issue where certain objects slide onto the webpage at specific scroll points. To ensure that these objects remain responsive, I need to adjust the scroll points using media queries.

Here is a snippet of the code I am currently using:

jQuery(window).scroll(function () {

            //media query scroll point @ min 768, max 995

            if (document.documentElement.clientWidth <= 995 && document.documentElement.clientWidth >= 768) {
                if (jQuery(this).scrollTop() > 400) {
                    if (jQuery('.rightSlideB').hasClass('visible') === false) {
                        jQuery('.rightSlideB').stop().animate({
                            right: '0px'
                        }, function () {
                            jQuery('.rightSlideB').addClass('visible');
                        });
                    }
                }
            } //end media query

            //default scroll point

            if (jQuery(this).scrollTop() > 250) {
                if (jQuery('.rightSlideB').hasClass('visible') === false) {
                    jQuery('.rightSlideB').stop().animate({
                        right: '0px'
                    }, function () {
                        jQuery('.rightSlideB').addClass('visible');
                    });
                }
            } //end default scroll point
        }); //end function

The CSS media query that dictates how my content responds looks like this:

@media only screen and (min-width: 768px) and (max-width: 995px) {}

Despite my efforts, the jQuery effects are not being achieved, and I acknowledge that my code is not optimized as there is a repetitive block of code:

if (jQuery('.rightSlideB').hasClass('visible') === false) {
                        jQuery('.rightSlideB').stop().animate({
                            right: '0px'
                        }, function () {
                            jQuery('.rightSlideB').addClass('visible');
                        });
                    }

This repetitive code segment is present in every media query. How can I streamline this section to avoid redundancy since it is used across multiple queries?

EDIT: Would it be recommended to place this repeating block into a function and then call it whenever needed?

I would appreciate any insights or guidance on what could be missing from my implementation. Thank you.

Answer №1

One solution could be to prioritize the default block by placing it at the top, especially if it applies to most situations. Additionally, consider adding an if condition to the default block that is the opposite of what is used in the media query. To bring it all together, connect them with an if-else conditional:

<div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>jQuery(window).scroll(function () {
if (document.documentElement.clientWidth > 995) {
if (jQuery(this).scrollTop() > 250) {
if (jQuery('.rightSlideB').hasClass('visible') === false) {
jQuery('.rightSlideB').stop().animate({
right: '0px'
}, function () {
jQuery('.rightSlideB').addClass('visible');
});
}
}
} else if (document.documentElement.clientWidth <= 995 && document.documentElement.clientWidth >= 768) {
if (jQuery(this).scrollTop() > 400) {
if (jQuery('.rightSlideB').hasClass('visible') === false) {
jQuery('.rightSlideB').stop().animate({
right: '0px'
}, function () {
jQuery('.rightSlideB').addClass('visible');
});
}
}
}
});

Answer №2

After much consideration, I have come up with my final solution.

To start, I simplified the repetitive block of code by creating a function:

$.fn.fromRight = function () {
            if (jQuery('.rightSlideB').hasClass('visible') === false) {
                jQuery('.rightSlideB').stop().animate({
                    right: '0px'
                }, function () {
                    jQuery('.rightSlideB').addClass('visible');
                });
            }
        };

Then, I defined new media queries based on popular mobile devices and called the function whenever the scroll height needed to be checked:

jQuery(window).scroll(function () {
... // Media queries and function calls here
});

Lastly, I decided to discard my old CSS media queries in favor of these new ones. And there you have it! Responsive web design is truly an enjoyable journey, don't you think? ;)

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

How can Jquery manage special characters received from the server-side?

One instance of storing ñ in my database results to it being saved as &#241. My goal is for the .ASPX page to show them correctly, such as ñ. Not displayed as Ni&#241o but instead as Niño. I'm thinking that I can achieve this in ASP.NET ...

Why is it that I am unable to utilize the post data stored in $var within my PHP document when making an Ajax call?

Hey there! I've got this function that makes an ajax call. But, for some reason, the $value I'm passing isn't defined in my showuser.php file. Can you help me figure out why? function showUser2(value) { var xhr = new XMLHttp ...

Sending data from Node.JS to an HTML document

Currently, I am working on parsing an array fetched from an API using Node.js. My goal is to pass this array as a parameter to an HTML file in order to plot some points on a map based on the API data. Despite searching through various answers, none of them ...

Deploying an AngularJS 1.x application bundled with Webpack to Tomcat server

I've scoured the depths of Google and combed through the official documentation for Webpack, but I’ve yet to stumble upon a tutorial, guide, or plugin that addresses this particular issue. Does anyone have any experience with this problem, or should ...

`Can I distribute configuration data to all components using a JavaScript file?`

My approach involves using config data to simultaneously affect the status of all components. I achieve this by importing the config object from the same JavaScript file and incorporating it into each component's data. It appears to work seamlessly, ...

Utilize the accurate information retrieved from the API and store it in MongoDB

I have a functioning script that automatically sends data to my MongoDB every second, but I am struggling with figuring out how to send the exact data from an API to MongoDB. FULL CODE var requestPromise = require('request-promise'); const ...

What is the best method for effectively organizing and storing DOM elements alongside their related objects?

In order to efficiently handle key input events for multiple textareas on the page, I have decided to create a TextareaState object to cache information related to each textarea. This includes data such as whether changes have been made and the previous co ...

intercepting a form prior to submission and modifying the JSON format

I am working on a form that needs to be reformatted before being sent to the backend in a readable way. One example is a survey with a structure like: { survey_id: (string), responses: [ { question: (String) ans ...

Designate the forward slash as the URL path

Can Express handle requests like this? app.get('/.test/abc', function(req, res) { res.send( 'abc test' ) }) So if I visit localhost:3000/.test/abc, it should display abc test. I tried it but it seems to not be working. Do I need t ...

Breaking a string into separate parts using various layers of delimiters

I am currently facing an issue with this specific string: {1 (Test)}{2 ({3 (A)}{4 (B)}{5 (C)})}{100 (AAA{101 (X){102 (Y)}{103 (Z)})} My goal is to divide it using { as the initial delimiter and } as the final delimiter. However, there are nested brackets ...

Is it acceptable to include text after the <li></li> tag?

I have a question: is it possible to add text after the Li tag and still maintain correct formatting? Here's an example: <ul> <li>Text</li> Text placed here after the tag <li>Text</li> Text placed here af ...

What could be the reason for attempting to insert metadata into a Google Drive document resulting in it being saved as plain text

I'm working on updating the metadata of a file that was previously uploaded to Google Drive. The metadata includes the title and description. However, I've noticed that when I submit the file, the name remains unchanged. The metadata seems to be ...

Using PHP to send date and time form fields to MySQL

I have been searching for a solution in the community forums, and the closest answer I found was in the thread titled "trying-to-post-date-via-php-with-mysql-need-help" My issue involves a form with 2 input fields - one for date selection using an HTML5 p ...

What is the best method for excluding past dates in the Ui calendar?

As a beginner with Ui calendar, I am seeking guidance on how to prevent users from selecting or interacting with previous dates in Ui-calendar using angularjs. While the Eventdrop, EventResize, and eventclick features are functioning properly for me, it ...

Link that is clickable within the tooltip of a Highcharts graph

My tooltips contain a list of data, and I want each data point to be a clickable link that redirects to the page for that specific data. The issue arises with Highcharts tooltip because it changes based on the x-axis, resulting in the tooltip content chang ...

Utilize JavaScript to submit the FORM and initiate the 'submit' Event

Hey there! Here's the code I've been working on: HTML : <html> <body> <form enctype="multipart/form-data" method="post" name="image"> <input onchange="test();" ...

What is the proper way to use Object.entries with my specific type?

On my form, I have three fields (sku, sku_variation, name) that I want to use for creating a new product. I thought of converting the parsedData to unknown first, but it seems like a bad practice. export type TProduct = { id: string, sku: number ...

What is the best way to delete and add elements in a looped array using Javascript

i have a form similar to this one. https://i.sstatic.net/V7ivb.png how can I replace this form each time the country changes, by removing it and then appending it again from a looping array. If there is only one set of data, display an "Add Form" Button; ...

Getting checkboxes from an HTML form in Django: A comprehensive guide

I am trying to create a form that displays checkboxes for each item in a list. Here is the structure of my form: <form action="/test"> <ul style="font-size:30px"> {% for d in Dlist %} <li type="none"><input typ ...

Struggling to extract the values from a KendoDropDown using Selenium

When using the selenium web driver, we are trying to retrieve a set of option values such as Last 30 days, Last 60 days, etc. Attempts have been made to locate these elements using a CSS selector. var timeperiodcss = "span.k-widget.k-dropdown.k-header se ...