JavaScript takes the spotlight before CSS

Currently experiencing this issue in Chrome, although Firefox seems to be working fine so far.

Here is a greatly simplified version of the problem:

HTML:

<div class="thumbnail">
  <a href='#' id="clickMe">Click me!</a>
</div>

CSS:

div {
    width: 200px;
    height: 300px;
    background-color: purple;
}
a {
    position: absolute;
}
@media (max-width: 991px) {
    div {
        height: 200px;
    }
}

Javascript:

$(document).ready(function () {
    var $parent = $('#clickMe').parent();
    function resize() {
        $('#clickMe').offset({
            top: $parent.offset().top + $parent.height()-$('#clickMe').height()
        });
    }
    $(window).on('resize', resize);
    resize();
});

The issue at hand:

When resizing (without dragging), the JavaScript sets the position of the <a></a> element before the CSS applies any height changes if the window size is less than 992px.

As a result, the button ends up visually outside of the div rather than on the border where it was originally intended to be.

Temporary solution proposed in this post:

jQuery - how to wait for the 'end' of 'resize' event and only then perform an action?

var doit;
    $(window).on('resize', function(){ clearTimeout(doit); doit = setTimeout(resize, 500); });

Not satisfied with the temporary solution:

In my case, waiting for the end of the resizing event isn't necessary. I simply want my JavaScript to run after the CSS has finished loading or applying its changes. Using the provided function feels sluggish as it randomly triggers the JS when the CSS may not be fully applied yet.

The question remains:

Is there a way to ensure that JavaScript executes only after CSS has completed making modifications during a resize event? Any techniques in JS to achieve this?

Additional Information:

Please note that testing this on jsfiddle might yield different results due to my extensive CSS file and the utilization of Twitter Bootstrap, both of which can slow down the CSS application process. Your insights are welcome.

Miljan Puzović suggested a solution involving loading CSS files via JS, then triggering JS changes when the CSS event comes to a close.

Answer №1

I believe that following these straightforward three steps will help achieve the desired outcome (make sure to carefully read and understand each step):

  1. For any layout issues related to responsiveness and fluidity, it is best to address them using CSS rather than JavaScript.

    Therefore, eliminate all JavaScript code from your implementation.

  2. The inner element a#clickMe has been positioned absolutely in your script.

    This means it will be positioned relative to its closest element with a position: relative;. Since no other element has this style (by default, they have position: static), it will be positioned within the body element according to the provided style. If you want it to be positioned relative to its parent container, add position: relative; to the div.thumbnail element.

  3. Based on the script you provided, it seems like you want to place a#clickMe at the bottom of div.thumbnail.

    Now that we've established the positioning context for a#clickMe within div.thumbnail, simply add bottom: 0px; to the a#clickMe element to position it accordingly, regardless of its parent's height. This adjustment will automatically adapt when the window is resized without requiring additional scripting.

The revised code snippet looks like this (view fiddle here):

JS:

 /* No script needed. */

CSS:

div {
    width: 200px;
    height: 300px;
    background-color: purple;
    position: relative; //added
}
a {
    position: absolute;
    bottom: 0px; //added
}
@media (max-width: 991px) {
    div {
        height: 200px;
    }
}

If you're still interested in media query change detection, check out these resources:

Link 1

Link 2

Link 3

Link 4

Twitter Bootstrap - how to detect when media queries starts

Bootstrap: Responsitive design - execute JS when window is resized from 980px to 979px

Answer №2

That temporary fix you implemented is quite clever (I've used a similar one in the past for a different issue, personally I don't think half a second is too long of a wait time for users but it might not suit your specific requirements...).

Have you considered another approach that involves handling everything through javascript and removing the @media (max-width.... from your css? It's a possibility worth exploring if you haven't already.

function adjustSize() {
    var windowWidth = (window.innerWidth > 0) ? window.innerWidth : screen.width;
    if(windowWidth<992){
        $("section").each(function(index,obj){$(obj).height(200);});
    }
    $('#clickMe').offset({
        top: $parent.offset().top + $parent.height()-$('#clickMe').height()
    });

}

Answer №3

To enhance the styling of your HTML page, remember to place the link to the CSS file in the head section. Then, make sure to include the link to the JavaScript file right before the closing /body tag. By following this order, the CSS will consistently load before the JS scripts are executed. I trust this tip proves beneficial for you.

Answer №4

Have you attempted binding the resize handler not to the window but to the specific object you want to monitor for resize events?

Instead of

$(window).on('resize', resize);

You could try

$("#hoverHere").on('resize', resize);

Alternatively, you may consider

$("#hoverHere").parent().on('resize', resize);

Answer №5

let isResized = false;
$(window).resize(function() {
    isResized = true;
});
setInterval(function() {
    if (isResized) {
        isResized = false;
        console.log('Window has been resized');
    }
}, 250);

Answer №6

I concur with falsarella's suggestion to utilize CSS for achieving your desired outcome.

However, if you wish to incorporate JavaScript functionality after applying the CSS, you might consider utilizing requestAnimationFrame. Unfortunately, I did not have the opportunity to test this personally as I could not replicate the issue you described.

According to the MDN documentation:

The window.requestAnimationFrame() method informs the browser that you want to execute an animation and requests the browser to call a specified function to update an animation prior to the next repaint. The method requires a callback function argument to be executed before the repaint occurs.

You may want to attempt something along these lines:

var $parent = $('#clickMe').parent();

function resize(){

    $('#clickMe').offset({
        top: $parent.offset().top + $parent.height()-$('#clickMe').height()
    });
}


window.onresize = function(e){
    window.requestAnimationFrame(resize);
}

window.requestAnimationFrame(resize);

Answer №7

Does anyone have a solution for delaying the execution of JavaScript until after CSS has finished loading?

Have you considered using

$(window).load(function() { /* ... */ }
? This method ensures that the function is only executed once the entire page, including CSS, has been fully loaded.

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 to Automatically Close an Ajax Modal Popup After Executing Code in ItemCommand in ASP.Net

I am currently facing an issue with closing a ModalPopup after a code sequence is executed. The situation at hand involves coding a filebrowser for the company and everything seems to be working fine except for the downloading of files. I have implemented ...

The jQuery click function triggers immediately upon the loading of the page

Despite my best efforts to resolve this issue independently and conduct extensive research on Google, I am still unable to identify the root of the problem. It seems that the click function continues to activate upon page load. Kindly elucidate the under ...

What is the procedure for matching paths containing /lang using the express middleware?

I need to target paths that contain /lang? in the URL, but I am unsure how to specifically target paths that begin with /lang? I have two routes: app.get('/lang?..... app.get('/bottle/lang?....... I want to target these routes using app.use(&a ...

I am unable to return JSON data from an AJAX request

I've been working on a price calculator within Joomla and have created a plugin for my ajax function. It appears to be functioning correctly, but I'm unable to display the data once it's retrieved. Below is the jQuery code I'm using f ...

What is the best way to align the middle item of a flexbox using CSS?

I am attempting to present text divided into 3 divs - the middle div contains the highlighted portion of the text, while the first and last divs contain the text before and after the highlighted section. Both the first and last flex items have classes tha ...

What is the process for assigning a random string value to each document within a mongodb collection using the mongo shell?

Looking to assign a randomly generated string property to every item in a MongoDB collection. Planning to leverage the mongo shell and the updateMany function for a swift and efficient solution. ...

What makes Angular date pickers sluggish?

Have you ever noticed that Angular JS date pickers consume a lot of CPU? When multiple date pickers are present on a page, they can noticeably reduce the site's speed. Is there a way to minimize this issue? Take for example the official Angular for ...

The `<Outlet/>` from react-router is being rendered in a location outside of its intended wrapper div

Utilizing MUI for crafting a straightforward dashboard featuring an <AppBar>, a side <Drawer>, my component appears as follows: <> <AppBar> // code omitted <AppBar/> <Drawer> // code omitted <Drawer/> / ...

Can you provide step-by-step instructions for creating a customized CSS dropdown menu?

Need some help with my code. I have a header that I don't want to change much, but I'd like to add a dropdown menu without using a list. Here's my code: <!-- Navigation Bar --> <div class="navbar"> <div class="button_l"& ...

Unable to reset input in a functional component using React JS

I have a component named TextInput that is responsible for rendering an input element: function TextInput({ type = "text", label, name, required = false }) { const [value, setValue] = useState(""); function handleChange(e) { se ...

Incorporating timed hover effects in React applications

Take a look at the codesandbox example I'm currently working on implementing a modal that appears after a delay when hovering over a specific div. However, I've encountered some challenges. For instance, if the timeout is set to 1000ms and you h ...

What is the best way to include the ID in a Vue.js Ajax request for posts?

Is there a way to pass an "id" obtained as data in vue js? The id is coming as "agnt.basic.actor". Considering the presence of multiple ids, how can I achieve this? <tr v-for="agnt in agentlist"> <td v-if="agnt.basic">{{agnt.basic.actor}}< ...

Can a key event be activated on the DOM Window using Javascript or JQuery?

Can a key event be triggered on the DOMWindow or DOMDocument using JavaScript? I am developing a browser extension to interact with a website that has shortcut key events, similar to those in GMail. While I have come across other methods for triggering key ...

Is there a way to retrieve the current object as a JSON string from inside the object using either jquery or javascript?

Looking for a way to return the current instance as a JSON text so that the values can be sent via an ajax request to a server-side script. Uncertain about where to apply the "this" keyword in a jQuery selector function Actor(){ this.input=function(pnam ...

Can a Textmate snippet be activated using a Regex pattern instead of just a specific character?

Hey there, I've been spending a lot of time working with CSS recently, and I have to admit that constantly typing "px" after every width, height, margin, etc., is starting to get on my nerves. I find myself refining pixel values in Firebug quite ofte ...

Utilizing Salesforce and DocuSign: A guide to automatically filling in the recipient of my envelope through DocuSign with the contacts from my records

In my Salesforce work, I'm currently customizing the Quote object. The default button labeled "Send with DocuSign" is already included on the Quote layout. My goal is to automatically populate the recipient of the DocuSign envelope with the contact(s) ...

"Enhancing HTML table rows using jQuery for a dynamic user experience

I'm currently using a jQuery script to determine the number of rows in a table and then display that count within a <td> tag. <tr> <td id = "jquery"> </td> <td> <%= f.text_field :data1 %> </td> <td ...

Implementing three identical dropdown menus using jQuery and HTML on a single webpage

It seems like I've tangled myself up in a web of confusion. I'm trying to have three identical dropdowns on a single page, each displaying clocks from different cities (so users can view multiple clocks simultaneously). However, whenever I update ...

Issues surrounding the break function in PHP and Jquery

Here is a simplified version of PHP and jQuery code for a page that I am working on. The example includes PHP break functions and the file is named test.php. The issue I am encountering is that when trying to load the first part of the page (case 1), the ...

Transforming the mui stepper connection into a progress bar is simple. Each step contains individualized content to guide you through the process

Is there a way to make the MUI stepper connector act as a progress indicator? I have step content and connectors as separate divs, but I'm having trouble styling them. Any assistance would be greatly appreciated! ...