What is the best way to execute a function based on the width of the screen?

Two functions need to be called based on the screen width.

Here is one attempt:

var winWidth = $(window).width();

var sections = function() {
    $('.image').each(function(){
       var $this = $(this),
        x = $this.find('img').width()
        $this.width(x);
     });
};

var sectionsMobile = function() {
     $('.image').find('img').css({
           'height': 'auto',
            'width': '100%'
         });
};

function checkSize() {
  if (winWidth >= 800) {
      sections();
    }   else {
      sectionsMobile();
  }
}
jQuery(window).on('load resize', checkSize);

Although the CSS is applied when the page loads, it does not switch between functions when resizing within the 800px boundary.

To see the full demo visit: http://codepen.io/sol_b/pen/PzgdWy

Your assistance is greatly appreciated.

Answer №1

One line that remains in memory is:

let screenHeight = $(window).height();

Simply place it within the adjustHeight() function.

Answer №2

Consider this approach:

$(window).on("load resize",function(){

    if($(this).width() >= 800 )
        processSections();

    else
        displayMobileSections();

});

Answer №3

Include the following code snippet:

(window).resize(function() {
 if (winWidth >= 800) {
      sections();
    }   else {
      sectionsMobile();
  }
});

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

What is the best way to connect input values with ngFor and ngModel?

I am facing an issue with binding input values to a component in Angular. I have used ngFor on multiple inputs, but the input fields are not showing up, so I am unable to push the data to subQuestionsAnswertext. Here is the code snippet from app.component ...

What is the best way to correlate two arrays of strings with one another?

I am working with two sets of data: First Set: let training = [ "Z1,1545 John Doe,P1", "Z2,2415 Shane Yu,P2" ]; Second Set: let skill = [ "P1, Shooting", "P2, Passing", ]; I need to combine both arrays bas ...

What is the method for activating the on collapse event with a bootstrap navbar?

I am encountering a common issue with collapsing the navbar on smaller screens and triggering an event when the collapse button icon is clicked. Despite my efforts to find a solution, I have been unsuccessful in using the following JavaScript code: $(&apos ...

Consistently encountering incorrect values during onClick events

I am using a Table to display certain values const [selected, setSelected] = React.useState<readonly number[]>([]); const isSelected = (id: number) => selected.indexOf(id) !== -1; return ( <TableContainer> <Table sx={{ width ...

Disabling vertical scrollbar in textarea within Bootstrap modal using CSS, jQuery, and C# in .NET MVC framework

I am passing data to the Bootstrap modal using jQuery from my database. The form values can change from a single row to multiple rows. I do not want a scrollbar, but instead I want the textarea element to automatically adjust its height to fit the content. ...

Flipping the camera rotation matrix in three.js

I am struggling with a scenario involving objects and a camera being controlled by a trackball. Whenever I add a new object to the main object, I want it to maintain its original orientation regardless of how the camera has moved around. For instance, with ...

"Exploring the various configurations for session handling in NodeJs

I am trying to implement a login system using the express-session module. I'm unsure if I have set everything up correctly, especially when it comes to the secret option. Currently, my initialization code for express-session looks like this: app.use( ...

Reducing Time Series Data: Comparing Average vs Largest-Triangle-Three-Buckets Technique

Currently, I am utilizing Flot Charts to create line charts that display timeseries data. To streamline the visualization process and reduce the number of data points shown, I have implemented a downsampling technique by averaging data points within the s ...

Unusual outcome observed when inputting a random number into HTML using JavaScript

In my HTML file, I am trying to input a number within 50% of a target level into the "Attribute" field. Here is the code: <!DOCTYPE html> <html> <body> <input type = "number" name = "playerLevel" onchan ...

Include a triangle shape at the top of a div container that has a background image using CSS

Struggling to add a point or triangle shape to my div with a background image, finding it difficult to create enough open space. This is the desired outcome: https://i.sstatic.net/LZVaF.png This is what I have implemented so far: <div class="bg"> ...

Exploring the world of complex JSON manipulation in Node.js and jQuery using Socket.IO

I'm struggling a lot with this issue. What I'm attempting to achieve is having a square-div move in real-time when dragged, and then transmitting its position to another page via Socket.IO. The problem is, I have no idea how to make this work! Th ...

Running multiple controller functions in nodejs can be achieved by chaining them together in the desired

Currently, I am working on the boilerplate code of mean.io and adding a password reset email feature to it. Whenever a user requests a password reset with their email as a parameter, I generate a unique salt (resetid) and send them an email with a link con ...

Moving a Node project to a different computer

I am looking to transfer my Angular project from a Windows machine to a Mac. I attempted to copy the folder and run npm install, but encountered an issue. Here is the error message I received: sh: /Users/pawelmeller/Documents/hotel/angular4/node_modules/ ...

Choose the most recently created tab using this function in jQuery UI Tabs

Can anyone assist me in modifying this function used to generate JQuery UI Tabs? I would like the last tab that is generated to be automatically set as the opened tab. Any help is greatly appreciated, as I am feeling quite confused at the moment. Thank y ...

Utilize viewport activation to determine browser width

Is there a way to dynamically add the viewport-meta tag only for devices with screen widths larger than 680px? If the screen is smaller than 680px, then the responsive style file should be enabled instead. I attempted to achieve this by placing the follow ...

Implementing new updates to an object without affecting existing values in Vue.js 2

I am currently facing an issue with updating values for an object received in a payload before saving it to the database. Despite making changes, the new values are not being persisted correctly. I am utilizing Vue.js 2 for this task. How can I effectively ...

What is the best way to retrieve the value of a checked radio button in React.js?

I am in the process of creating a well-structured to-do list and I want to be able to add the input from any selected radio button into one of three options arrays (the array is not included in the code, but rather in a parent component). I am looking fo ...

Make sure all of the inner tags are properly contained within their respective containers

In my explanatory bubble, I aim to include text within the explain-header div as a container for my explanations: /*Explain Bubble*/ .explain-container { position: relative; overflow: hidden; max-width: 70vw; max-height: 50vh; background-c ...

Using Node.js for HTML redirections involves creating routes and setting

I am currently attempting to connect my Node.js API with my HTML pages. For the most part, everything is functioning correctly, but I have encountered some confusion along the way. Is there a more efficient method for redirecting an HTML page? Typically, ...

Adding key/value pairs to an array of objects in RxJS Observables can be easily

I currently have an Angular app with state management that retrieves data from a database in observables. Here is an example of the interfaces I am working with: interface Service { id: number, name: string, category_id: number, } interface Category ...