Is there a way to implement this media query within my JavaScript code?

I am attempting to make my website recognize when the screen width surpasses 1096px in order to apply some CSS styling. Below is the code I'm using:

var mq = window.matchMedia('@media all and (max-width: 1096px)');
if(mq.matches) {
    window.parent.document.getElementsByClassName("sticky-leaderboard-ad-container")[0].setAttribute("style","padding-top: 4rem !important; margin-left: 0 !important");
} 

Could someone please explain why this code is not functioning as intended? Your help is greatly appreciated.

Edit: It is important that the solution is implemented in JavaScript, as CSS cannot be used for this particular scenario.

Answer №1

You can achieve the desired outcome without relying on javascript.

Solely using css media queries, you can replicate the same functionality with the following code snippet:

@media all and (max-width: 1096px)
.sticky-leaderboard-ad-container {
     padding-top: 4rem !important; 
     margin-left: 0 !important;
}

However, if you prefer to incorporate javascript into your solution, you can retrieve the width of the window like this:

if(window.innerWidth < 1096) {
        let element = document.getElementsByClassName("sticky-leaderboard-ad-container")[0];
        element.setAttribute("style","padding-top: 4rem !important; margin-left: 0 !important");
} 

Answer №2

To ensure your media elements respond appropriately to screen sizes above 1096, it is recommended to use min-width: 1096px. The usage of max-width: 1096px specifies the behavior when the screen size is equal to or below the specified target.

if (window.matchMedia("(max-width: 1096px)").matches) {
  /* The viewport is less than, or equal to, 1096px pixels wide */
} else {
  /* The viewport is greater than 1096px pixels wide */
}

Alternatively:

if (window.matchMedia("(min-width: 1096px)").matches) {
  /* The viewport is greater than, or equal to, 1096px pixels wide */
} else {
  /* The viewport is less than 1096px pixels wide */
}

Furthermore, the use of

window.parent.document.getElementsByClassName()
is incorrect and should be replaced with
document.getElementsByClassName()
.

Answer №3

To gather the viewport dimensions, consider implementing an event listener and utilizing the window object.

window.innerWidth 
window.innerHeight
window.matchMedia("(min-width: 1096px)")

For more information on matchMedia, check out the matchMedia documentation.

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 one include a URL as a "URL parameter" when using Express?

In my Node.js application, I've set up a router to listen for requests at api/shorten/: router.get('api/shorten/:longUrl', function(req, res, next) { console.log(req.params.longUrl); } When I enter something like: http://l ...

Discover all related matching documents within a string array

I am using a mongoose schema model with a field called tags which is an array of strings to store tags for each document. I need functionality where if I search for a specific tag, such as "test," it will return all documents with tags like "testimonials" ...

The Ajax call failed to connect with the matching JSON file

<!DOCTYPE html> <html> <body> <p id="demo"></p> <script <script> function launch_program(){ var xml=new XMLHttpRequest(); var url="student.json"; xml.open("GET", url, true); xml.send(); xml.onreadystatechange=fun ...

Uncovering the Mystery: Extracting a Video Thumbnail from Brightcove Videos

Is there a way to extract the video thumbnail from Brightcove Video? <x:out select="$item/description" escapeXml="false" /> At the moment, the thumbnail is being retrieved within the description. ...

Bringing in the node-spotify or spotify-web modules to the browser for seamless integration

Has anyone successfully used Spotify's Playlist API in a browser? It seems that the web API only covers metadata, and to access the full API I need to use libspotify. Do I need to set up a Spotify API server myself or use node libraries like node-spot ...

Exploring the foundations of web development with html and stylus

If you have experience with the roots platform, you are familiar with its default stack including jade, stylus, and coffee script. The documentation provides some information on using HTML, CSS, and pure JavaScript instead of the compiled languages, but d ...

Is it possible for a font to exclude the space character?

I'm currently developing a font detection library that must be extremely compact in size, perfect for direct inclusion on every page of a website. I've managed to shrink it down quite a bit already (compressed to 417 bytes). Take a look at it on ...

The present user who is currently logged into the stackmob platform

I am currently working on retrieving a list of contacts for the logged-in user, but I am struggling to identify the current user. In Parse.com, you would use Parse.User.current(), but I am unsure if Stackmob offers a similar functionality. Below is the co ...

AngularJS promises are known for returning the object itself instead of just the resolved value

function getBusTimetable() { var waiting = $q.defer(); var busData = $http.get('https://bus.data.je/latest'); busData.success(function(response) { waiting.resolve(response); }); busData.error(function(error) { waiting.reject( ...

The transformation in the resulting array is evident when a nested array is altered after being concatenated using Array.concat

MDN explains concat as follows: The concat() function is utilized to combine two or more arrays without altering the original arrays. Instead, it produces a new array. Let's examine the code snippet below: Example 1 const array1 = [['a& ...

Issue with Laravel 5.4: AJAX behaving unexpectedly and not returning errors as it should

After going through several tutorials on handling AJAX requests in Laravel, I'm still facing some issues. Each tutorial has its own approach... Finally, one method is not giving me a 500 error, but it's not displaying validation errors as expect ...

How to retrieve the value of a SelectField component within a constant using Material-UI

I am currently facing an issue with my Drawer component that contains a SelectField with some fields. I am struggling to get the value and implement the onChange functionality of the Field. Below is the snippet of my code: const DrawerCargoAddItem = (p ...

Troubleshooting Problem with Creating a Button using HTML Checkbox "onclick" Event

My main goal with the checkbox click event is to achieve the following objectives: 1] Create a button with the id = 'id-of-checkbox'+'some-character-here' in a specific div. 2] Clicking on that button will remove both the button and ...

Utilizing ReactJS to fetch data from Material-UI's <TableRow/> component upon selection - a comprehensive guide

I've integrated Material-UI's <Table/> (http://www.material-ui.com/#/components/table) component with <TableRow/> containing checkboxes in a ReactJS project. While I can successfully select rows by checking the boxes, I am struggling ...

Error occurred while making a request in React using Axios: TypeError - Unable to retrieve the 'token' property as it is undefined

After successfully receiving a token from logging in with React Redux, I attempted to authorize it using the token. However, an error occurred stating Axios request failed: TypeError: Cannot read property 'token' of undefined. The token is stored ...

Guide on creating uniform heights and widths for images with varying dimensions utilizing CSS (and percentage values)

Is there a way to ensure that all images maintain the same height and width using CSS percentages, rather than set pixel values? I'm working on displaying images in circles, where most are uniform in size but a few outliers distort the shape. The wide ...

Leveraging *ngFor to extract HTML content from ion-label

I've encountered an issue while using *ngFor in my HTML like this: <ion-slides #slides [options]="slideOpts"> <ion-slide class="numbers-wrapper" *ngFor="let questionNumber of numbers" (click)="clickQue ...

Leverage the power of require() beyond the confines of Node

I'm currently exploring how to integrate an Angular.js application with Node.js. At the moment, I have the following code in the file MY-PROJECT/public/js/controllers.js function LoginController( $scope ) { // fetch waiters var Waiter = require( ...

Encountered a Server Error: Invalid hook call. Hooks are restricted to being called within the body of a function component specifically in _app.js

As someone new to React and Next JS, I am facing an issue with setting initial auth user data on the initial load from the __app.js file. Whenever I try to use dispatch, it throws an error saying "Invalid hook call". I understand that calling hooks in the ...

Saving a single ID at a time in a UseState array by clicking in ReactJS

When clicking on the "click here" button, I am trying to save favorite post IDs in an array. However, the issue is that it is currently only saving one ID at a time in the array. Every time you click on another "click here" button, it removes the previous ...