The application of Jquery media queries does not take effect until the page is refreshed

I've got this code on my page where the background color is working perfectly. However, I'm facing an issue with the li element - it doesn't update unless I refresh the page. For example, when the window size is smaller than 500px in width, the li elements are shown without needing to click anything.

function myFunction() {
  if ($(window).width() < 500) {
    $('body').css('background', 'black');
    $("nav").click(function() {
      $("li").toggle('slow');
    });
  } else {
    $('body').css('background', 'blue');
    $("li").show();
  }
}

Answer №1

Implement your code within a function and execute it on page load and when the window is resized as shown below:


$(window).load(function(){
   //insert your function here
});
$(window).resize(function(){
  //insert your function here
});

Answer №2

Make sure to also activate it on resize events, so when you resize the window, the queries will be triggered

$(window).on("load resize",function(){
  //your code should be placed here
  if ($(window).width() < 500) {
    $('body').css('background', 'black');
    $("nav").click(function() {
      $("li").toggle('slow');
    });
  } else {
    $('body').css('background', 'blue');
    $("li").show();
  }
}

Answer №3

$("nav").click(function() {
  $("li").toggle('slow');
});

function myFunction() {
  if ($(window).width() < 500) {
    $('body').css('background-color', 'black');
  } else {
    $('body').css('background-color', 'blue');
    $("li").show();
  }
}
  1. It is recommended to use background-color instead of just background
  2. Consider placing the click event outside the function for better organization.
  3. If myFunction is intended to be triggered on either a resize or load event, make sure it is properly implemented.

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

The ASP.NET MVC framework does not allow the passing of ajax data objects to controllers

I've been struggling for some time now trying to figure out this issue. I'm puzzled by the fact that when sending information to the controller through a data object from AJAX using JQuery, the parameter arrives null in this scenario. The JavaScr ...

Creating a diverse layout by dynamically adding divs without achieving uniformity in the grid

I'm working on dynamically generating a grid of divs with a specific size using the code below: function createGrid(gridSize) { var container = document.getElementById('container'); for (var i = 0; i < gridSize; i++) { va ...

Customize the color of router-link text in your Vue.js app

Within my coding project, I am utilizing vue.js in the App.vue file. I have set up route-links for goods, ratings, and seller components. Now, I am trying to customize the colors of these links using a style module. Below is the template section of the ...

Adjusting the width of a product slider based on window size changes using CSS media queries

Currently, I have a functional product slider that I am attempting to adjust the width for smaller viewports, but it is proving to be a challenge. Upon loading the document, the code tallies the width of each product item and initiates slides when buttons ...

What is the best way to add new content to the top of existing content within a DIV using jquery?

Is there a way to insert content at the top of existing content instead of the bottom using the .append() function? ...

Displaying a carousel of cards with a stacking effect using CSS and React

https://i.sstatic.net/254kG.jpgI am looking to design a layout similar to the image provided, where cards are stacked on top of each other with three dots for toggling. Can anyone guide me on how to achieve this visual effect? ...

I am endeavoring to send out multiple data requests using a function, ensuring that the code execution occurs only once all the results have been received

After reading through a post on Stack Overflow about handling multiple AJAX calls in a loop (How to take an action when all ajax calls in each loop success?), I was able to come up with a solution. I decided to track the number of requests I needed to make ...

What are the advantages of going the extra mile to ensure cross-browser compatibility?

It's fascinating how much effort is required to ensure web applications work seamlessly across all browsers. Despite global standards like those set by W3C, the development and testing process can be quite laborious. I'm curious why all browsers ...

Having trouble with my PHP/AJAX code - the Ajax request to PHP isn't functioning correctly, causing the rows not

I am currently working on a PHP chat application and running into some issues with utilizing AJAX to fetch data from a MySQL database and display it within a designated div. Below are the snippets of my code: HTML <div id="chatbox"> <div cla ...

Utilize the text input to occupy the remaining space within a row, flanked by two other elements

In my HTML, I am struggling with the alignment of a 'row' div that contains a label, text input, and hyperlink. The issue arises when I try to make the width of the input always fill the available space between the label and the hyperlink. Despit ...

Can minification of JS be achieved in a Jekyll environment?

Currently, I am in the process of developing a project with Jekyll and one of the requirements is to minify HTML, CSS, and JS. I was wondering if Jekyll has built-in features for JS minification. It may seem like a simple question, but since I am new to ...

"Creating a dynamic dropdown menu and sub-menu in PHP using MySQLi with unique slug values

I need to generate a dynamic menu from the database, including main menus and submenus. For instance: <li class="<?= ($pg == 'departments') ? 'active':''; ?>"> <a href="departments">Departments</a> ...

Use AJAX to send a form submission along with an anchor tag

I've been facing a challenge trying to make this work, but unfortunately, I haven't had any success. Typically, all my forms include a submit input, and I handle AJAX submission in the following manner: <script> $("input#submit").click(fun ...

Using jQuery to retrieve the text content of child elements

Struggling to extract the text of child elements using jQuery. I've been at this for a couple of days and can't seem to make it work. If anyone could spare a moment to review, I would greatly appreciate it! SCRIPT: function generateRemoveSect ...

Stacking elements in perfect alignment

Seeking assistance with React/MUI as a newcomer. I am utilizing a Stack of TextFields, which are resizing effectively based on screen width. <Stack direction="row" sx={{ margin: "16px" }} > ...

Timer Does Not Appear to be Counting Down

I recently added a countdown clock to my website, but I'm having an issue with it not updating in real-time unless the page is refreshed. I'm not very familiar with javascript, so I found some code online and made some modifications myself to sui ...

apply a border-radius to the top right corner only without affecting the other sides or background

https://i.sstatic.net/9YIiy.jpg I have been working on creating the top right triangle design shown in the image. However, I encountered an issue where applying border radius seems to affect all sides instead of just one as intended. Despite using border- ...

What is the best way to proceed with script execution once ajax has completed, without relying on synchronous calls or embedding content?

So, I am aware of two ways to handle waiting for an ajax request with jQuery: $.ajaxSetup({async: false}); Although this method will make ajax synchronous, it is not something I desire. The second technique I know is as follows: $.post("foo.html", func ...

Analyzing neglected CSS in intricate websites

While there are tools available to identify unused CSS on static web pages, real-world scenarios often involve CSS being used dynamically after interactions such as opening modals or popups. How can we effectively manage our ever-growing render-blocking CS ...

The grid feature in the Bones theme is malfunctioning and causing issues

I am currently using the Bones theme from Themble, which has a grid system in its design. I attempted to apply this grid system to the header of my website in order to transform menu items into icons on mobile devices and display the full menu on desktop s ...