Activate javascript when the screen size is adjusted

I'm using a Bootstrap nav-tab to show and hide different tab-panes based on the screen size thanks to Bootstrap breakpoints.

The issue I'm encountering is when a user is on a small screen with the #hide-show tab-pane active, and then resizes the browser window to a large screen where #hide-show is hidden, the #hide-show pane remains active in the background.

Is there a way to switch the active pane based on the screen size or the display-type attribute of the #hide-show tab pane?

<ul class="nav nav-tabs" id="myTab" role="tablist">
  <li class="nav-item">
    <a class="nav-link active" id="home-tab" data-toggle="tab" href="#home" role="tab" aria-controls="home" aria-selected="true">Home</a>
  </li>
  <li class="nav-item d-lg-none">
    <a class="nav-link" id="hide-show-tab" data-toggle="tab" href="#hide-show" role="tab" aria-controls="contact" aria-selected="false">Contact</a>
  </li>
</ul>

<div class="tab-content" id="myTabContent">
  <div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">...</div>
  <div class="d-block d-lg-none tab-pane fade" id="hide-show" role="tabpanel" aria-labelledby="hide-show-tab">...</div>
</div>

Answer №1

Roberto highlighted that there is an inherent event in the window object for this purpose.

To utilize it, you would employ EventTarget#addEventListener.

window.addEventListener('resize', event => {
  console.log(event);
});

I'm not entirely clear on what you mean by switching the active panes, but you can selectively remove this class at certain breakpoints.

window.addEventListener('resize', () => {
  // Toggle on mobile
  if (window.innerWidth <= 696) {
    Array.from(document.querySelectorAll('.active')).forEach(element => {
      element.classList.remove('active');
    });
  }
});

If it only affects the style of elements in a predictable manner, I suggest utilizing CSS media queries.

@media (max-width: 696px) {
  .active {
    /* Mobile style changes here */
  }
}

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 could be the reason for the undefined value of my variable

I am facing an issue with a function that I have written function collectData() { var data = []; data[0] = {name: "Sophia", age: 25, gender: "female"}; data[1] = {name: "John", age:30, gender ...

Is it possible to implement addEventListener.delay() functionality?

Hello, I am working on a Qualtrics code that utilizes jQuery. I am looking to incorporate a delay function for event listening in my code, which currently allows key presses as inputs. Specifically, I need to disable the keys for the initial 2000ms before ...

Getting the right AngularJS $scope within a controller for beginners

I am struggling to understand how to toggle the visibility of an element on a webpage using a controller. Below is a code snippet with an example - you can test it by clicking the "close edit" button (nothing happens): var appModule = angular.module(&a ...

The server was surprised with an error when it encountered an unexpected token ":" while processing a valid JSON object from the server

I'm attempting to make a GET request to the solr search engine using $.ajax() from jQuery. This is the code snippet I'm using for the ajax call: $.ajax({ url : 'http://xxx.xxx.xxx.xxx:port#/solr/mycore/select?indent=on&q=mypa ...

Is there a way to automatically refresh the template whenever a scope variable is changed?

My goal is to have the showOrder.html template rendered when the value of orderHistory.type (a scope variable initialized as 'list') changes to 'show'. This change occurs when a link is clicked in the orderHistoryList.html. The model is ...

Finding the variable with the highest value using AngularJS

I have a variety of variables with different values assigned to them, such as: Weight_gain = 0.01 Weather_gain = 0.02 and many more like these. My goal is to determine the variable name with the highest assigned value. When I attempt this using code, it ...

Error: The Typescript module in Angular 2 does not have the constant 'FORM_DIRECTIVES' available for export

I need to integrate an existing component into my app, but I am facing some issues with the dependencies. Originally, the sample code provided me with these dependencies: import {CORE_DIRECTIVES, FORM_DIRECTIVES, NgClass} from 'angular2/common'; ...

Strange jQuery IE7 Modal Behavior

Recently, I encountered a frustrating issue with my modal windows. They seem to work perfectly in all browsers except for IE7 (I have not tested below this version). In the demo I provided, you will see that the first modal-dialog functions as expected. H ...

What is the best way to add a background to certain elements?

Is there a simple and elegant way to swap the background of the circle with the background of the div underneath? I would like the circles to have the background image of div "one", while keeping div "one" invisible (not using visibility:hidden). I am lo ...

Eliminating the bottom border of all buttons, except for the last three buttons in the list, solely using pure JavaScript, unless alternative methods are available

I have 3 sets of buttons, with each set containing 9 buttons stacked in 3 columns inside an ordered list (ol) within list items (li). I have removed the bottom border of the buttons to avoid double borders since they are stacked on top of each other withou ...

Tips for utilizing the selected option in the name attribute with Javascript or jQuery

I am looking to use the "selected" attribute in the option element based on the name attribute using JavaScript or jQuery. Essentially, I want the option with name="1" to be automatically selected when the page loads. I have attempted the following code, b ...

Navigating production mode in nuxtjs and uncovering errors

There seem to be numerous inquiries regarding this matter. Unfortunately, there doesn't appear to be a definitive solution. Is there any way to view detailed error logs in production mode? https://i.stack.imgur.com/prXUt.jpg ...

Manipulating variables in Jquery is not possible during an ajax success event

I implemented a code feature that uses ajax to load content when a user scrolls to a specific part of the page. To prevent the content from being loaded multiple times, I introduced a boolean variable that should toggle after each ajax call, preventing the ...

Adjust the arrangement of divs when resizing the window

I have utilized flexbox to rearrange the boxes. Here is a link to the demo code My issue arises when resizing for smaller screens; I need to place B between A and C. https://i.stack.imgur.com/M0dpZ.png Any suggestions on achieving this goal? Thank you i ...

How can I resize the border to match the size of the text inside it?

Check out the following image to see how it appears:https://i.sstatic.net/RkMqI.png Here is an example code snippet of a message: .allMsg { width: 100%; } .self { border-radius: 1rem; background-color: #28a745; text-align: right; padding-lef ...

Having trouble initiating the server using npm start

Just starting out with nodeJs: I have created a server.js file and installed nodejs. However, when I try to run "npm start", I encounter the following errors. C:\Users\server\server.js:43 if (!(req.headers &amp;& req.headers. ...

When the enter key is pressed in the input box, the page resets instead of triggering

After extensive research, I have found that none of the available resources have been able to resolve the specific issue I am facing. Objective: My goal is to trigger the function $("#search").click(); when text is entered into the box and th ...

Struggling to get the AngularJS filter to function properly when using a $scope

In my AngularJS application, I have a requirement to display courses and their equivalent courses in a table. The table should dynamically update based on the selection made from a drop-down menu. HTML <form name = "Select University" ng-show = "cours ...

When the button with an image is clicked, it will display a loading element

I have developed an application that heavily utilizes ajax, and I am looking to implement the following functionality: I would like to have a button with both text and an image. When this button is clicked, it should be disabled, and instead of the origina ...

Accessing CSV data stored externally using JavaScript

Hi there, I am struggling to load external CSV data into a script due to what I believe is the browser's same origin policy restriction. I came across some information about using cross-document messaging as a workaround, but I have no idea how to go ...