What is the best way to create JavaScript code specifically for devices with a maximum width of 520px?

Is there a way to apply this JavaScript code specifically to devices with a maximum width of 520px? I could use some guidance on how to achieve this.

// Apply code for max-width = 520px
const myBtn = document.getElementById("darktheme");
const body = document.body;
const welcome = document.getElementById("txtt");

let isDarkTheme = false;

myBtn.addEventListener("click", function() {
  isDarkTheme = !isDarkTheme; 

  if (isDarkTheme) {   
    body.style.backgroundColor = "rgb(17, 17, 17)";
    body.style.color = "white";
    welcome.style.color = "white";
  } else {    
    body.style.backgroundColor = "white";
    body.style.color = "black";
    welcome.style.color = "white";
  }
});

Answer №1

If you want to utilize the Window.matchMedia() method in JavaScript, it can be done. This method will provide a MediaQueryList object that allows you to determine the media query string.

After considering the above information, I have made some modifications to your code, as outlined in my comments below:

const myBtn = document.getElementById("darktheme");
const body = document.body;
const welcome = document.getElementById("txtt");

let isDarkTheme = false;

// Define MediaQueryList
let mql = window.matchMedia("(max-width: 520px)");

myBtn.addEventListener("click", function() {
  // Verify if the condition of MediaQueryList is met
  if (mql.matches) {
    isDarkTheme = !isDarkTheme; 

    if (isDarkTheme) {
      body.style.backgroundColor = "rgb(17, 17, 17)";
      body.style.color = "white";
      welcome.style.color = "white";
    } else {
      body.style.backgroundColor = "white";
      body.style.color = "black";
      welcome.style.color = "white";
    }
  }
});

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

Trouble with importing css in Angular webpack due to ui-bootstrap integration

Currently, I am developing an Angular application with Webpack and was looking to incorporate Bootstrap for styling purposes. To achieve this, I first installed 'ui-bootstrap' using npm install angular-ui-bootstrap --save-dev. After installation ...

Customize the keyboard on your iPod by replacing the default one with a

Looking to customize the iPOD keyboard to only display numbers, similar to a telephone keypad: https://i.stack.imgur.com/X0L3y.png The current iPOD default keyboard looks like this: https://i.stack.imgur.com/VykjU.png ...

The Art of Div Switching: Unveiling the Strategies

I have a question regarding my website. I have been working on it for some time now, but I have encountered a challenge that I am struggling to overcome. After much consideration, I am unsure of the best approach to take. The issue at hand is that I have ...

Retrieve a photo from a website address and determine its dimensions

When grabbing an image from a URL using this function: const fetch = require("node-fetch"); function getImageFromUrl(url) { return fetch(url).then((response) => response.blob()); } To determine the dimensions of the images, I am utilizing ...

Having trouble with the Angular router link suddenly "failing"?

app.routes.ts: import { environment } from './environment'; import { RouterModule } from "@angular/router"; import { ContactUsComponent } from './static/components/contact-us.component'; import { HomeComponent } ...

Preserving variable scope in JavaScript even after defining a function

I am facing an issue with my JavaScript code that involves invoking a function within a function: var obj = { // returns the function with prevent default prepended. run: function(functor, context){ return function(e){ e.preventDefault(); ...

Tips on preserving a dynamic web page within a Cordova application

I have developed a project and To Do list App that operates on a single HTML page with just an "add To Do list" button. Users can click on this button to create a To Do list and add tasks within it, all of which are dynamically generated as HTML elements. ...

Executing Javascript without invoking the default behavior

Recently, I've been delving into the world of JavaScript and experimenting with the prevent default command for ajax pagination. Here's the code I've come up with: http://jsfiddle.net/6pqfH/2/ $('.pagination').click(function(e){ ...

The deleteCell function will not properly function when directly targeting selected table rows (trs)

I'm currently facing an issue while trying to dynamically access a specific tr element. Although I believe that the tr is being selected, when attempting to use the deleteCell method, it gives an error stating that the object does not have such a meth ...

Discord.js: Merging strings while pushing to an array

I am currently updating an embed message to notify users who have "enlisted" in a list by reacting. However, I am encountering an issue where the strings from the entire array are getting combined when the length of the array reaches 2 before adding a new ...

"Woops! An error occurred with the message: "SassError: Could not locate the specified target selector" while working with SCSS Modules and incorporating

Currently, I am working with Next.js and utilizing SCSS Modules. To incorporate Bootstrap into my project, I opted to install it using the command npm install bootstrap. Following this installation, I went ahead and created a new file titled common.scss wi ...

What is the best way to create divs that can close and hide themselves when clicked from inside the div itself?

I have a situation in my code where clicking a link reveals a div, and then the same link must be clicked again to hide it. However, I want to modify this so that any link within the div can also hide it when clicked. I currently have eight divs set up lik ...

Animating the left and right positioning of a single element using CSS transitions

I am currently working with the following CSS code: #masthead { transition: left linear 0.25s; -moz-transition: left linear 0.25s; -o-transition: left linear 0.25s; -webkit-transition: left linear 0.25s; -ms-transition: left linear 0.2 ...

Guide on using webpack to import jQuery

When using webpack, is it necessary to install the jquery file from npm, or can I simply require the downloaded file from the jquery website? directory app/ ./assets/javascripts/article/create/base.js ./assets/javascripts/lib/jquery-1.11.1.min.js webpack ...

Skip ahead button for fast forwarding html5 video

One of the features in my video player is a skip button that allows users to jump to the end of the video. Below is the HTML code for the video player: <video id="video1" style="height: 100%" class="video-js vjs-default-skin" controls muted autoplay=" ...

Should front-end and back-end share Typescript data modeling through classes or interfaces?

I'm currently exploring the best approach to share the same data types between the client (React) and the server (Express + Socket.IO). Within my game, there are various rooms each storing the current status, such as: class GameRoom { players: P ...

Communicating JSON data through AJAX with a WCF web service

Hey everyone, I could really use some assistance with my current coding issue. My goal is to pass the value 2767994111 to my WCF web service using jQuery AJAX. var parameter = { value: "2767994111" }; $('#btSubmit').click(function () { $ ...

The navigation bar buttons in my IONIC 2 app are unresponsive on both the

In Ionic 2 for Android, I encountered an issue with the title placement. To resolve this, I applied some CSS to center the title and added left and right buttons to the nav bar. However, when I tried to implement onclick functionality for these buttons, no ...

Update your MySQL database with ease by leveraging the power of AJAX through a dropdown menu

Can you provide guidance on updating a MySQL database using a dropdown menu and Ajax without reloading the entire webpage? I am facing issues with implementing the code, even after referring to various tutorials. Below is a snippet of my PHP script within ...

Is it possible to conduct brain.js training sessions multiple times?

Is there a way to specifically train my neural network with new information without having to retrain the entire model, considering the potential performance costs associated with it? The neural network was created using brain.js. ...