What is the best way to disable a JavaScript code based on a specific screen width?

When I click on a specific link, it triggers an alert using jQuery.

Here is the HTML code for the link:

<a class="link" href="www.example.com">link</a>

The JavaScript code attached to the link is as follows:

$(".link").click(function() {
    alert('clicked');
    return false;
});

In the CSS code snippet below, a condition is set for when the user's screen width is at least 980px:

@media (min-width: 980px)
{
  // When the link is clicked within this width range,
  // I want it to open www.example.com
}

How can I determine whether the client's device width is less than or greater than 980 pixels?

Answer №1

Utilize the following code snippet: $(window).width()

$(".link").click(function() {
    if($(window).width() >= 980){  
       alert('clicked');
       return false;
     }
});

Answer №2

I'm not exactly sure what you're looking to achieve, but if I understand correctly, you want a piece of JavaScript code to execute based on the client's screen width crossing a specific pixel threshold.

If this is indeed what you're aiming for, you'll need to include a check in the click event callback function to determine whether the client's screen size exceeds or falls below 980 pixels.

$(".link").click(function () {
  if (window.innerWidth > 980) {
    alert('Clicked');
    return false;
  }
});

Answer №3

Disabling JavaScript through CSS is not possible; instead, you would need to utilize JavaScript to determine the width by using $(window).width()

$(".link").click(function() {
    if ($(window).width() >= 980) {
        alert('clicked');
        return false;
    }
});

Answer №4

Personally, I find match media to be quite useful:

var mq = window.matchMedia('@media (min-width: 980px)');
var link = document.querySelector('.link');
link.href = mq.matches ? "http://www.example.com" : "";

UPDATE:

Just a heads up, as pointed out by @Oscar: If you're concerned about the combined ~16% market share of IE8/IE9 as of October 2015, it may be best to go with the jquery method outlined in the selected answer.

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

Avoiding the display of file picker dialog - Selenium GeckoDriver

Currently, I am attempting to use Selenium to upload a file by sending keys (the file path). While this method is successful in uploading the file, it also triggers the file picker dialog which remains open indefinitely. Although no actual issues occur, wh ...

Instead of returning an object, the underscore groupBy function now returns an array

Currently, I am attempting to utilize underscore to create an array of entities that are grouped by their respective locations. The current format of the array consists of pairs in this structure { location: Location, data: T}[]. However, I aim to rearran ...

html transparent div element

I'm encountering an issue with this specific code snippet: <li class="nav-item dropdown" id="noti_Container" > <div id="noti_Counter" style="opacity: 1; top: -2px;"></div> <a style=" ...

The content of xmlhttp.responseText is not being displayed in the innerHTML

As part of my ongoing effort to enhance my understanding of Ajax for work purposes, I have been following the W3Schools tutorial and experimenting with my Apache2 server. In this process, I have placed a file named ajax_info.txt on the server (in /var/www ...

Why is the code able to execute following the setState hook without any listener declared in the useEffect hook?

Recently, I came across an expo barcode scanner example where a function is executed after a setState hook. This puzzled me as I thought that calling the setState hook would trigger a re-render of the component. Can anyone explain why the function runs aft ...

Creating a custom JavaScript function to manipulate arrays

I am working on a project involving an array of strings that represent class names. My goal is to instantiate these classes using their string names, but so far my attempts with the window object have been unsuccessful. The array structure looks like this ...

flex child moves outside parent when available space shifts

My dilemma involves a flex container (A) containing two or more flex items stacked in a column. The top flex item (B) is a Bootstrap Collapse panel, while the bottom item (C) consists of two horizontal divs (D and E). The problem arises when the collapse p ...

Establishing MQTT Connection in Ionic 3

I am facing a challenge with implementing Publish-Subscribe methods in my Ionic 3 application. After consulting the information on this page, I attempted to link MQTT with my Ionic 3 application. Can anyone guide me on how to successfully connect MQTT wi ...

Getting an image from a NodeJS backend to a React frontend

I successfully uploaded an image using the multer library in Express, storing it in the path Backend->Uploads/ and saving the image path in MongoDB. My project is structured as DirectoryName Backend Uploads Frontend While I can access the ima ...

What is the limitation of including a string constant with "</script>" inside a <script> block?

I am genuinely curious about this: I thought that the following code would be valid within an HTML document: <script> var test = "<script>why? </script>"; </script> However, it turns out that this leads to an "unterminated str ...

Webpack has issues with loading HTML files

I encountered a 404 not found error while attempting to load the HTML page using webpack. Here are my configurations: Webpack.config.js: const path = require('path'); module.exports= { devServer: { // contentBase static : { ...

Implementing GRIDFS for mp3 storage in a meteor application

Being a novice in the world of meteor, I am currently working on defining an mp3 collection and then uploading music to it from the admin page. The packages that are installed include: cfs:standard-packages cfs:gridfs cfs:filesystem 1) I have successful ...

Receiving "Illegal Invocation" error when attempting to submit form using ajax

I am attempting to submit a form using ajax, and here is the form code: <form class="form-vertical" method="POST" id="request-form" action="/post_handler?request=add_data" enctype="multipart/form-data"> <div class="form-group"> <label ...

Validation of check boxes in AngularJS group

Struggling to enforce the selection of at least one checkbox from a list using AngularJS validation. Here's the code I've been working with: // JavaScript code snippet var app = angular.module('App', []); function Ctrl($scope) { $ ...

Obtain data attributes using JQuery's click event handler

I'm facing an issue with a div structure setup as follows: <div class='bar'> <div class='contents'> <div class='element' data-big='join'>JOIN ME</div> <div class=& ...

Linking URLs in an Android TextView with the <a href> tag

When creating a TextView dynamically, I encountered an issue with setting the text as linkable. The desired text value was "Google". After referring to various resources on the internet and blogs, such as this one, I attempted different methods but did not ...

Naming variables in JavaScript with parentheses()

I'm currently facing some issues with my code, as it's not working properly. I have three variables that set the state of another set of three variables. Instead of writing out the code three times, I wanted to use another variable (like 'i& ...

Automate your workflow with Apps Script: Save time by appending a row and seamlessly including additional details to the

I currently have 2 server-side scripts that handle data from an html form. The first script saves user input to the last row available in my Google sheet, while the second script adds additional details to the newly created row. Although both scripts work ...

What are some ways to access Angular's form array within HTML code?

.ts import { Component, OnInit } from '@angular/core'; import { HelloServiceService } from 'src/app/hello-service.service'; import { FormBuilder, FormGroup, FormControl, FormArray, Validators } from '@angular/forms'; @Compone ...

Incorrect input

Let's consider this scenario: We have a workspace website similar to Google Drive. (Remember that) There is a Delete .icon on my files list to delete a file. When I request the delete file WebMethod using Ajax, I also want to retrieve the updated ...