Using jQuery to verify a CSS property of an element upon window resizing

Is it possible to include a window resize function in this code?

jQuery(document).ready(function($){         
    var $MyDiv1 = $('#mydiv1');
        if ($MyDiv1.length && $MyDiv1.css('position') == 'fixed') { 
           console.log ( '#mydiv1 is fixed' );      
        } else {    
           console.log ( '#mydiv1 is not fixed' );      
        }       
 });

The current setup only works if the page is refreshed after resizing. I would like to continuously check whether MyDiv1's position is fixed or not while the window is being resized. Any help would be appreciated. Thank you.

Answer №1

$(document).ready(checkIfFixed);
$(window).on('resize', checkIfFixed);

function checkIfFixed() {
    var $myDiv = $('#myDiv');
    if ($myDiv.length && $myDiv.css('position') == 'fixed') { 
        console.log('#myDiv is fixed');      
    } else {    
        console.log('#myDiv is not fixed');      
    }   
}

Another method involves triggering one event within another:

$(window).on('resize', function() {
    var $myDiv = $('#myDiv');
    if ($myDiv.length && $myDiv.css('position') == 'fixed') { 
        console.log('#myDiv is fixed');      
    } else {    
        console.log('#myDiv is not fixed');      
    }  
});
$(document).ready(function() {
    $(window).trigger('resize');
});

If you place your code at the end of the page to avoid using $(document).ready, it becomes even simpler:

$(window).on('resize', function() {
    var $myDiv = $('#myDiv');
    if ($myDiv.length && $myDiv.css('position') == 'fixed') { 
        console.log('#myDiv is fixed');      
    } else {    
        console.log('#myDiv is not fixed');      
    }  
}).trigger('resize');

Source : jQuery combine .ready and .resize

Answer №2

Below are two ways to handle window resize events using javascript:

$(window).on('resize', function(){
 //code here
});

or alternatively:

window.onresize = function() {
 //code here
}

COMPLETE CODE:

function checkDivPosition(){ 
    var $MyDiv1 = $('#mydiv1');
    if ($MyDiv1.length && $MyDiv1.css('position') == 'fixed') { 
       console.log ( '#mydiv1 is fixed' );      
    } else {    
       console.log ( '#mydiv1 is not fixed' );      
    }
}
jQuery(document).ready(function($){         
  checkDivPosition();
});
window.onresize = function() {
  checkDivPosition();
}

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

Removing an individual HTML element within a form using JavaScript Fetch() in the presence of multiple components

The Situation Having a form that includes image components generated from a MySQL database with PHP, I've implemented javascript fetch() functionality on different pages of the website to enhance user experience. However, in cases where the functiona ...

Making a form select element responsive within a bootstrap 4 card component

Check out the code snippet I have here: This is how I envisioned it to look, and it works perfectly at large resolutions. However, when I scale it down to tablet size, the resizing of the select element doesn't seem to work properly. Here's a s ...

Utilizing base64_encode versus json_encode to pass encoded data through a hidden input

I am currently working on a project where users will be able to create live blocks using Ajax. I have encoded the block's elements map inside a hidden input's value and plan to decode it within the php file. My main question is this: I am utiliz ...

Transmitting HTML content to the browser from the client using Node.js

Quoted from: Book - "Getting MEAN with Mongo, Express.." When it comes to responding to requests in your application by sending HTML to the browser, Express simplifies this process compared to native Node.js. With support for various templating e ...

I am looking to customize the color of my Material UI switch

I am having difficulty changing the color of my Material UI switch based on my preference. I have tried several ways, but have not achieved the desired outcome. const useStyles = makeStyles((theme) => ({ toggle: { '& .Mui-checked': ...

Assessing the usage of $parse in a directive within an ng-repeat loop in Angular version 1.4.5

I'm attempting to utilize $parse to analyze the expression of an attribute of a directive within an ng-repeat loop. Here is an example of the HTML: <body ng-app="hello" ng-controller="control"> <div ng-repeat="a in array" my-dir="a.one == 1" ...

Code behind implementing a new System.Drawing.Font

Recently, I have been attempting to generate an image using the Black Rose font in c# but unfortunately, the output does not reflect the desired font. Below is the code snippet I used for creating the image: protected void Page_Load(object sender, Eve ...

Issue with window.localStorage.setItem not functioning properly on mobile devices

Currently, I am developing an HTML5 mobile application with jQuery Mobile. Below is a snippet of my code: $(document).on("click","#send_mobile_number",function(){ var mobile = $('#mobile_number').val(); var user_id = sessionStorage.get ...

Using jqGrid with the jQuery.get() method

Struggling to populate a jqGrid from a jQuery.get() response and facing some challenges. The table is set up simply, and I have successfully called my servlet and returned the XML using this setup: $("#table_1").jqGrid({ datatype : 'xml', ...

Preventing direct URL access with Angular redirects after refreshing the page

My website allows users to manage a list of users, with editing capabilities that redirect them to the /edit-user page where form information is preloaded. However, when users refresh the page with F5, the form reloads without the preloaded information. I ...

Need Some Help Reversing the Direction of This CSS Mount Animation?

Exploring this fiddle, I encountered a small div showcasing an opacity animation. The animation smoothly executes when the state transitions to true upon mounting the component, causing the div to fade in beautifully. However, I faced a challenge as the an ...

Is there a way to use HTML and CSS to switch the style of a dynamic decimal number to either Roman numerals or Katakana characters within a specified HTML element, such as a tag, div

I've searched everywhere but only found guides on list styling and counter styling in CSS that didn't work out. So, for example, I have a number inside an HTML tag that is changed dynamically using Vue Watch. I want to display the number in upper ...

Bootstrap creates a small and calculated width for elements

Currently, I am integrating the react-datepicker plugin into my project alongside Bootstrap 3. Upon implementation, I have noticed that the size of the datepicker on my website appears to be smaller than the examples provided in the plugin demos. It seems ...

"Experiencing a problem with Next.js 13 where the User Context is not functioning properly outside of _app

When using Next.js 13 and the user context, I've noticed that it doesn't function properly outside of _app.tsx. Any idea why? src>context>UserPositionContext.tsx import { createContext, useContext, useState } from "react"; const ...

Creating pagination in Vue using an array of objects

I'm new to Vue and arrays and I need help paginating my json array so that only 10 items are displayed per page. Currently, all the items in the array are being shown in the <tr> body. I've tried different methods without success. Can someo ...

A guide on transferring documents between collections using Mongoose and MongoDB

I have a list of tasks that includes both completed and incomplete items. Additionally, I have two buttons - one for deleting an item (which is functional) and the other for marking an item as done or not. I am struggling with creating a function to move ...

Can you identify the issue with this jQuery code snippet?

$("#ckbCheckAll").click(function () { $('div .bulkop .ez-checkbox').toggleClass("ez-checked", this.checked); var id_checkboxes = $('div .bulkop .ez-checkbox input').map(function() { return this.id; }).get(); for ...

Issue encountered: ENOENT - There is no file or directory located at the specified path for ... .steampath

I am encountering an issue while attempting to launch the development server on a React project that has been dormant for quite some time. After executing npm install and npm start, I encountered the following error message. Despite my efforts to manua ...

Limiting the draggable element within a compact container using jquery UI

I've been attempting to drag an <img> within a fixed-width and fixed-height container. Despite researching on Stack Overflow and finding this solution, it doesn't seem to work for my specific case. If you check out this fiddle I created, y ...

Tips on utilizing the identical template in ngIf

I need to display different templates based on certain conditions. For example: <template [ngIf]="item.url.indexOf('http') == -1"> <a class="ripple-effect" [routerLink]="[item.url]" *ngIf="isUserLoggedIn == true" > ...