When activated multiple times, Element pays no attention to jQuery

As I work on making my website responsive, I have encountered an issue with the jQuery script. When rapidly changing the window size, it seems to ignore the conditions set for elements to be displayed or hidden.

The CSS is straightforward:

body:after{display:none; content:"default";}
@media only all and (max-width: 800px){
    body:after{content:"tablet";}
}

And the jQuery code is as follows:

jQuery(document).ready(function($) {
    var currentSize = "default";
    var lazyLayout = _.debounce(function(e) {
    }, 300, true);
    $(window).resize(lazyLayout,function() {
            var size = window.getComputedStyle(document.body, ':after').getPropertyValue('content');
            
            size = size.replace(/"/g, "");
            size = size.replace(/'/g, "");
            if (size != currentSize) {
                if (size == 'tablet') {
                    var count = $('#mobileNav').length;
                    if (count < 1) {
                        var data = {
                        dataType: "HTML",
                        action: 'nav_media_query',
                        nonce: myAjax.nonce
                    };
                    $.post( myAjax.url, data, function( data ) {
                        $('#content-wrapper').removeClass('col-4-5');
                        $('#trending-Container').addClass('mobileNavStyle');
                        $('#trending-Container').append(data);
                        });
                    currentSize = 'tablet';
                    }

                }  
                if(size == 'default') {
                    $('#mobileNav').remove();
                    currentSize = 'default';
                }
            }
    }).resize();

});//end function 

This script checks for a media query by examining the content attribute, then triggers an ajax request to load WordPress PHP into an element.

While this setup works well with gradual window resizing, it tends to break when resizing quickly and repeatedly.

Is there a jQuery method that can prevent this issue from occurring?

Edit: I have updated my code to include _.js debounce method in order to reduce the number of ajax requests. However, the problem of elements not being removed after the conditions are no longer met remains unresolved.

Answer №1

You can experiment with incorporating a delay within the resize function by creating a nested function. To explore this concept, consider implementing the setTimeout method from jQuery in the following manner:

setTimeout(displayContent, 1000)

function displayContent() {     
  //Include the desired code here
}

Answer №2

Utilizing Underscore.js effectively resolved the issue I was facing, it was just a matter of correctly applying the function.

Behold, the outcome is displayed below.

When I used jQuery along with Underscore.js within the document.ready() function, I successfully managed to handle the resizing event depending upon the content value received from the body element's pseudo-selector in CSS. The slight challenge arose in ensuring consistency across different browsers due to variations in returning values. By replacing quotation marks and refining the logic based on the 'tablet' and 'default' sizes, I could dynamically adjust the navigation menu display accordingly for improved user experience. Witnessing this seamless transition between different browsing contexts further reinforced my appreciation for clever JavaScript libraries like Underscore.js.

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

Is there a way to show a progress bar that functions as the background for a table row

My table is structured as follows: th1 th2 th3 th4 th5 th6 td1 td2 td3 td4 td5 td6 td1 td2 td3 td4 td5 td6 I am looking to incorporate a feature where new rows are dynamically added using a form that triggers ...

Having trouble locating an element using Selenium?

I'm attempting to extract the price of a flight from Google Flights website using Selenium, but I am unable to locate the specific element on the page. Even after scraping the entire page, the element remains elusive. It has been suggested that it may ...

If the title is a match, append an attribute to a tag

Is there a way to automatically add the attribute "target=_blank" to an <a> tag if it has the title "extension" assigned to it? <ul id="mob-right-menu"> <li class="menu-item><a href="#">Work</a></li> <li class="menu- ...

Fluid percentage-based layout

I have four separate Divs that I would like to position on my page in a specific layout. Here is an image showing how I want them positioned: https://i.sstatic.net/KBZ1U.png In the future, I plan to add multiple svg files to Div 4 and I want it to be scro ...

Guide to locating a child element using CSS from a given web element

<div id='example' /><div> When looking at the provided example, the goal is to locate a div under the following conditions: WebElement divelement = driver.FindElement(By.css("#example")); My objective is to locate the div tag wit ...

What techniques can be used to maintain the alignment of an image while the surrounding text changes?

Having trouble aligning my image without affecting its position. When the wind text is hidden (JavaScript not functioning in CodePen), meaning it is not displayed below the temperature, the weather image shifts upwards. I attempted to use 'absolute&ap ...

Implementing audio effects in IE6 HTML

I've implemented the following code to play a sound effect on my website in Firefox, Chrome, and IE9: <body> <audio id="audio1"> <source src="audio.wav" type="audio/wav"> <source src="audio.mp3" type="audio/mpeg"> audio tag no ...

Customizing the Appearance of HtmlEditorExtender

Having an ajax HtmlEditorExtender featured on my webpage has been quite a challenge. I followed the instructions provided here: http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/HTMLEditorExtender/HTMLEditorExtender.aspx The issue arises from t ...

Struggling to attach a click event to a duplicated element with jquery

I was attempting to add a click event to a cloned object with the following sample code, but for some reason I couldn't get it to work. Despite multiple attempts, attaching the click event to the object proved challenging. Take a look at the code and ...

The presence of text is leading to CSS placement troubles

I operate a website dedicated to comic content and am looking to incorporate text (retrieved from the database field "description") beneath each comic thumbnail. Here are my two inquiries: 1) I'm facing an issue where adding text below a comic caus ...

What is the best way to retrieve the parameters from the current URL within an Express function on the backend? (details below)

Struggling to articulate my issue here. I'm in the process of creating a straightforward express app that utilizes the omdb API to search for movie titles and display the results. The challenge is that the omdb API returns the results in pages, with 1 ...

IE7 CSS3 Framework

Curious to hear your solutions for implementing CSS3 features in IE7. A fellow frontend developer suggested using "CSS Pie" specifically for rounded corners and shadows. Should I opt for a full CSS3 framework, or should I find individual fixes for each pro ...

Memory leaks observed in BinaryJS websockets

Currently, I am in the process of developing a simple client/server setup to facilitate the transfer of image data between a browser and a node.js server using BinaryJS websockets. Despite following the API examples closely, it seems that my implementatio ...

When clicking the next or previous button in VueJS, showcase a list

I am looking to create a case management system in a JavaScript view. The system will track employees arriving and leaving a department, returning 3 objects (entries and exits) for the current week, next week, and the week after that. By default, the syste ...

When I ran npm run build, I encountered numerous errors

I'm overwhelmed with numerous errors and not sure where to even begin. Error Log > webpack [webpack-cli] The configuration object for webpack is invalid. It seems that the configuration object does not match the API schema. - configuration.module ...

Tips for concealing an element with Clippy.js without relying on a timeout feature

Recently, I stumbled upon a fascinating JavaScript library called Clippy.js that allows you to incorporate Microsoft Word's classic virtual assistants into your web browser. While experimenting with it, I discovered that the text balloon vanishes afte ...

Challenges Encountered with AngularJS $http Service

How do I pass my data from the http request to the $scope in the MainCtrl? The code below should fetch data from a MySQL Database with an $http-service, but somehow the data provided by the service doesn't go to the controller or gets displayed incor ...

Sending information from a Bootstrap modal form

I'm experiencing an issue with my form that triggers a modal for confirmation before submission. The modal contains the submit button and is located outside of the <form> tag. Surprisingly, it works perfectly fine on all browsers except for Inte ...

Encountered an error while trying to initiate MongoDB using dpd-d

Trying to kick off a Deployd application, I encountered some hurdles. Upon entering dpd-d in the terminal, an error message popped up: deployd v0.6.11 startup failed... Failed to initiate MongoDB Seeking to debug the issue by typing 'DEBUG=* dpd&apo ...

Transfer the cropped image to the database through AJAX on the client side and PHP on the server side

I am attempting to upload an image to a Database using JavaScript on the client-side and PHP on the server-side. The first step is selecting an image from the gallery. After zooming and cropping the image, it should be passed to the database. The issue ...