Do not execute the script if the window's width is below a certain threshold

I have a unique website layout that adjusts to different screen sizes, and I've incorporated some jQuery functionality. Here is a snippet of the code:

 <script>
    $(document).ready(function(){
        $("#D1000C36LPB3").click(function(){$("#D1000C36LPB3_details").show();});
        $("#D1200C36LPB3").click(function(){$("#D1200C36LPB3_details").show();});
        $("#D1-3CA36LPB3").click(function(){$("#D1-3CA36LPB3_details").show();});
        $("#D1-0CA36LPB3").click(function(){$("#D1-0CA36LPB3_details").show();});
        $("#D700S36LPB3").click(function(){$("#D700S36LPB3_details").show();});
        $("#D700S24LMB3").click(function(){$("#D700S24LMB3_details").show();});
    });
</script>

In the code above, all the div elements like #D1000C36LPB3_details have their initial CSS property set to display: none, making them invisible until clicked on by the corresponding div element like #D1000C36LPB3, which then displays the content.

Now, I want to modify the script to change the display property to fixed when the viewport/window width is less than 400px.

My solution

I've identified a solution to set the display property to fixed:

$("#corresponding_ID").css("display", "fixed");

However, I need to prevent the initial jQuery script from running (the one with .show()).

Answer №1

It is not advisable to set css styles directly in this manner. As mentioned before, it is better to use a class such as .visible and let css media queries determine the display. For example:

@media screen and (max-width: 399px) {
  .visible {
    display: fixed;
  }
}
@media screen and (min-width: 400px) {
  .visible {
    display: block;
  }
}

Then, in your click handler, you can do the following:

$("#D1000C36LPB3").click(function(){$("#D1000C36LPB3_details").addClass('visible');});

Furthermore, if all your details containers follow a similar naming convention by appending _details to the id, it might be more convenient to store all ids in an array and iterate over them like this:

$(document).ready(function(){
  var ids = [ "#D1000C36LPB3", "#D1200C36LPB3", "#D1-3CA36LPB3", "#D1-0CA36LPB3", "#D700S36LPB3", "#D700S24LMB3"];
  for (var i = 0; i < ids.length; i++) {
    $(ids[i]).on('click', function () { $(ids[i]+'_details').addClass('visible'); });
  }
});

Answer №2

Quick and efficient method for browser width detection using jQuery:

var screenWidth = $(window).width(); 
if (screenWidth >= 1024) { 
  -- Insert code to be executed here --
}else{
 -- Insert alternative code to be executed here --
}

You can easily adjust the width value and modify the comparison to suit your specific requirements.

Feel free to reach out if you need further clarification.

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

When employing the map function in React, the resulting array is always equal to the last element within

Recently delving into the world of React, I encountered an issue while trying to assign unique ids to an array of objects within a Component's state using the map function. Strangely, despite my efforts, all elements in the resulting array ended up be ...

How to maintain HTML list items in a single line while overlaying text

I'm seeking assistance with understanding how to solve a particular issue. I have multiple list elements with varying lengths of text content, each flanked by small images/icons on either side. Below is an example of the HTML structure: .truncate ...

Adjust a Specific CSV Value Using JavaScript and NodeJS

Hey there, I have a CSV file that I need to extract and modify a specific value from. Let's take this as an example: CSV 90,90,90,90,90 3,1,1000,2,931 I'm looking to access the number "2" in this CSV. How would I go about doing that? And once ...

Remove an item from the DOM instantly with React

Having trouble synchronously removing a child from the container? Here is a simplified code snippet demonstrating the current solution using the useState hook. type ChildProps = { index: number; id: string; remove: (index: number) => void; }; fun ...

Transfer the content from a text area to a div element while keeping the original line breaks

I have a textarea and a div (containing a paragraph tag) where the content of the paragraph tag is updated with the text entered into the textarea upon keyUp. Is there a way to maintain line breaks from the textarea and have them appear as line breaks in ...

JavaScript issue: Submitting form does not trigger the associated function

I am currently in the process of learning JavaScript as part of my university course, and I have encountered an issue where my function is not being called. I am seeking to gain a better understanding of why this problem is occurring. Summary The situati ...

Guide to fetching and displaying a complex array API using JavaScript's fetch method

Recently, I've been delving into the world of APIs and making sure I call them correctly. Using the fetch method has been my go-to so far, and here's a snippet of the code where I reference an API: fetch('https://datausa.io/api/data?d ...

Halt scrolling news feed when hovering over with the mouse

I'm currently working on a news ticker on this jsfiddle, but it's not functioning as I'd like. Here are the issues I'm facing: When I increase the width and height of all the divs, it doesn't work properly as the last divs over ...

Validation problem encountered on client side in a partial view

Currently, I am tackling client-side validation on a partial view. I have attempted to load the jQueryVal bundle on the master page but unfortunately, it is not functioning as expected. @Scripts.Render("~/bundles/jqueryval") Interestingly, the same bundl ...

TimePicker Component for ASP.Net MVC with Razor Syntax

I'm currently working on implementing a TimePicker using Razor and JQueryUI in my bootstrap website. While I have successfully created a DatePicker, I am facing difficulties in creating a separate TimePicker using two different TextBoxes instead of se ...

Unleashing the Power of Javascript in Selenium with Java (featuring PrimeFaces)

Recently, I discovered that JavaScript seems to be malfunctioning in my Selenium Tests written in Java. The reason behind this issue remains a mystery to me. Any ideas on how to tackle this roadblock? ((JavascriptExecutor) driver).executeScript("retur ...

Creating a seamless integration between a multi-step form in React and React Router

I've been learning how to use React + ReactRouter in order to create a multi-step form. After getting the example working from this link: , I encountered an issue. The problem with the example is that it doesn't utilize ReactRouter, causing the ...

What is the best way to set the date defaultValue to be empty?

I've developed a basic radio button to display an additional input field when the user chooses yes. I also created a function that will clear the fields if the user selects no. schema.ts: const formSchemaData = z.object({ doesHaveDryRun: z.enum( ...

Capturing and saving location data without internet connection, and then displaying markers once connectivity is restored

I am currently developing a web application that will monitor the user's location. I want to ensure its reliability, so even if the user loses internet connection, the application will continue tracking their location (since GPS does not rely on inter ...

The system is unable to locate the command "nvm"

Lately, I've been experimenting with using nvm to manage different versions of node. After successfully installing nvm on my Mac OS Catalina(10.15.6), I was able to easily switch between versions through the terminal. However, when attempting to do t ...

Trigger javascript function with a button click

Is there a way to trigger a JavaScript function from an HTML button that is not functioning properly? REVISED To see the issue in action, please visit this jsfiddle link: http://jsfiddle.net/winresh24/Sq7hg/341/ <button onclick="myFunction()">Try i ...

Utilizing the request module in Node.js with ExpressJS

Currently, I am in the process of creating a helper method within my code that will handle user authorization. This function, named "usePermissions", is being developed following the React approach but for backend functionality. Upon implementa ...

Lock GridView headers when only scrolling vertically

I am facing an issue with my gridview on an aspx page. The gridview is wider than the page itself, so I want the headers of the gridview to scroll horizontally along with the content, while remaining fixed vertically. Can anyone help me achieve this? I hav ...

Can an additional height be added to the equalizer to increase its height?

Is it feasible to append an additional 35px to the height determined by Foundation Equalizer? For instance, if Equalizer computes a height of 350px, I would like to increase it by 35px. This means that the resultant style should be height: 385px; instead ...

What is the best way to retrieve both the start and end date values from a React date range picker component

I have integrated a date range picker npm package called react-date-range into my code. On my screen, there is an "Apply Dates" button. When this button is clicked, I want to retrieve the selected date range value. How can I achieve this onclick event? ...