What is the best way to prevent a modal from being triggered specifically on mobile devices such as phones and

$(function() {
  $('.pop').on('click', function() {
    $('.imagepreview').attr('src', $(this).find('img').attr('src'));
    $('#imagemodal').modal('show');
  });
});
.modal-backdrop.in {
  opacity: 0.8;
}
#imagemodal .modal-dialog {
  width: 70%;
  position: center;
}
@media (max-width: 987px) {
  .pop:hover {
    opacity: 100;
    filter: alpha(opacity=100);
    /* For IE8 and earlier */
  }
}
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

<div class="row">
  <div class="col-md-4">
    <a href="#" class="pop">
      <img src="images/powwow/powwow_01.jpg" style="width: 100%">
    </a>
  </div>
</div>

<div class="modal fade" id="imagemodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body">
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
        </button>
        <img src="" class="imagepreview" style="width: 100%;">
      </div>
    </div>
  </div>
</div>

I want to deactivate a modal on smaller screens like phones and tablets, while keeping it active on larger screens. I've tried using CSS media queries with `visibility:hidden` and `display:none`, but the results are not what I expected. I believe the onClick function needs to be disabled for smaller screens, but I'm struggling to figure out how to do that. Any suggestions on how to achieve this?

Answer №1

When responding to Iceman's message, consider unbinding the click event from your button based on the device's width, such as on a tablet or mobile device:

if( isMobile() || (screen.width <= 800)) {
            $(#yourbutton).unbind('click');
        } 

Additionally, utilize CSS to alter the appearance of the button dynamically according to the width, which can help prevent users from unintentionally clicking on it.

Answer №2

To display the model using Javascript, make sure to verify if the device meets your requirements before revealing it. I've crafted a personalized function inspired by a Stack Overflow post to confirm if the device is a mobile one. Additionally, you can validate if the screen width is within the allowed range.

Update your Javascript with the following:

$(function() {
    $('.pop').on('click', function() {
      $('.imagepreview').attr('src', $(this).find('img').attr('src'));
      if ($(window).width() < 800 || isMobile()){
         // perform alternate action for mobile devices
      } else {
         $('#imagemodal').modal('show');
      }   
    });   
});
function isMobile() {
  var isMobile = false; //initialize as false
  // device detection
  if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|pluc...
  return isMobile;
}

FULL WORKING CODE:

The modal won't be displayed for mobile devices or screen sizes less than 800 pixels. Adjust as needed. Click run code snippet to see it in action!

$(function() {
  $('.pop').on('click', function() {
    $('.imagepreview').attr('src', $(this).find('img').attr('src'));
    if ($(window).width() < 800 || isMobile()) {
      //do substitute operation for mobile screens and delete below 3 lines
      console.log("model not showed!!");
      console.log("isMobile: " + isMobile());
      console.log("screen size: " + $(window).width() + "px  min is 800px");
    } else {
      $('#imagemodal').modal('show');
    }
  });
});

function isMobile() {
  var isMobile = false; //initiate as false
  // device detection
  if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|...
  return isMobile;
}
.modal-backdrop.in {
  opacity: 0.8;
}
#imagemodal .modal-dialog {
  width: 70%;
  position: center;
}
@media (max-width: 987px) {
  .pop:hover {
    opacity: 100;
    filter: alpha(opacity=100);
    /* For IE8 and earlier */
  }
}
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="row">
  <div class="col-md-4">
    <a href="#" class="pop">
      <img src="images/powwow/powwow_01.jpg" style="width: 100%">click
    </a>
  </div>
</div>

<div class="modal fade" id="imagemodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body">
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span>
        </button>
        <img src="" class="imagepreview" style="width: 100%;">
      </div>
    </div>
  </div>
</div>

Credits to L.Dia for suggesting the screen size check. It has been incorporated into the code.

Answer №3

Assuming you are utilizing Bootstrap, you have the option to utilize the built-in hide classes such as hidden-xs or visibility classes like visible-lg. Since Bootstrap follows a mobile-first approach, your modal will only be visible on large screen devices, which seems to be suitable for your situation.

<div class="modal fade visible-lg" id="imagemodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  ...
</div>

If you prefer a JavaScript solution and are still working within the Bootstrap framework with jQuery, you can use the following script to determine the window width and customize the event handling accordingly.

$(document).ready(function () {
            var $window = $(window);

            function checkWidth() {
                var windowsize = $window.width();
                if (windowsize < 1200) {
                    $(".pop").click(function (event) {
                        event.preventDefault();
                    });
                }

                else {
                    $(function () {
                        $('.pop').on('click', function () {
                            $('.imagepreview').attr('src', $(this).find('img').attr('src'));
                            $('#imagemodal').modal('show');
                        });
                    });
                }
            }

            checkWidth();
            $(window).resize(checkWidth);
        });

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

Adjust the width of the <td> elements that are nested under <th> elements with a specified

I want to define the width of the td elements in the tbody section under a thead element with colspan="2" using specific column widths in %. I need the table to maintain a fixed width without dynamically adjusting based on content. .sample { width: 10 ...

"An in-depth guide on parsing JSON and showcasing it in an HTML format

As part of my order processing, I am saving the order details into a JSON file named order_details.json. Here is an example of how the data is structured: [{ "uniqueID": "CHECKOUT_IE01", "orderID": "4001820182", "date": "06-02-2019 16:55:32.32 ...

The use of the `/deep/` combinator in CSS has been phased out and is set to be completely removed

After updating my angular to version 4.0.0 and chrome to 62.0.3202.94, I encountered the following error message: [Deprecation] /deep/ combinator in CSS is deprecated and will be removed in M63, around December 2017. Refer to for more information. The ...

Is it possible to adjust the height of input fields in MUI Reactjs?

Having trouble adjusting the height of input textfields using in-line css. <FormControl sx={{ "& .MuiOutlinedInput-notchedOutline": { borderColor: "blue", }, "&.Mui-focused .MuiOutlinedInpu ...

The Vue-cli webpack development server refuses to overlook certain selected files

I am attempting to exclude all *.html files so that the webpack devserver does not reload when those files change. Here is what my configuration looks like: const path = require('path'); module.exports = { pages: { index: ...

Performing function in Vue.js when a change occurs

I recently started developing a Vue.js component that includes an input field for users to request a specific credit amount. My current goal is to create a function that will log the input amount to the console in real-time as it's being typed. Ultima ...

"Utilizing react.js allows for the direct access of DOM elements by the main parent component

Is there a way to trigger click events on deeply nested DOM elements within my component hierarchy without passing down callback functions to each individual component? I'm looking to execute these events from the top parent App component using EventT ...

Decorate the elements that do not contain a specific child class

I'm currently working on an angular project with primeng for the UI components. My focus at the moment is on customizing the p-menu component, specifically the appearance of list items that are not active. The challenge I'm facing is that the act ...

Incorporating A Full-Fledged Office Word Editor Into My Web Application

In our web project, we are looking to integrate a feature that allows users to create, edit, and save their word documents for reporting purposes. While Microsoft Office offers an online option here, it seems limited to working within the Microsoft OneDriv ...

Can someone explain the significance of the statement "We strongly advise using custom validation styles because browsers' default styles are not announced to screen readers"?

The Bootstrap 4 website explains the importance of using custom validation styles for form validation, as native browser defaults may not be easily announced to screen readers. What does this mean? Should users opt for native browser form validation o ...

Steps to design a text div that extends beyond the bottom boundaries

Can anyone help me troubleshoot this design code using Bootstrap 3.x? Specifically, I am facing an issue with the following div. Any suggestions? Click here for more information. img{max-width:100%;} .mydiv{margin-bottom:20px;} .mytext{ positio ...

Radio boxes vanish in Safari when -webkit-perspective is applied

Check out this quick demonstration on Safari only: http://jsfiddle.net/2late2die/8AJnD/ If you remove the perspective style, all checkboxes will appear normal. When using -webkit-transform-style:preserve-3d, the checkboxes disappear. This issue seems to af ...

What is the process of disabling console log in a Vue template?

Origins of the $log variable: Vue.prototype.$log = console.log Restricted Areas: <template> <!-- Restricted Area 1 --> <div @click="$log"> <!-- Restricted Area 2 --> {{ $log }} <!-- Restricted Area 3 -- ...

Displaying JavaScript values one by one using a for loop and alert

Having an issue with looping through a JSON array in JavaScript. I am trying to extract only SG_J1001 and SG_LS01, but it's not working as expected. The result is coming out like this [{"regis ....... var item = JSON.stringify(data['code'] ...

Shuffling specific table cells to exchange positions

I am attempting to create a script that will allow certain td elements (but not all) in different tr elements to switch places with the ones directly above or below them. My goal is to only target the last 3 td elements in each row, rather than the entire ...

There was an AJAX post error that occurred due to the refusal to set an unsafe header with the name "Connection"

My custom ajax function sends data to a PHP file, but I'm encountering two errors each time the data is posted: Refused to set unsafe header "Content-length" Refused to set unsafe header "Connection" Here is my code: function passposturl(url1 ...

Capture screenshots of the web page URLs within the Chrome browser by utilizing PhantomJS

Looking for a way to capture screenshots of various URLs and display them in the Chrome browser using PhantomJS. How can I achieve this? Any assistance would be greatly appreciated, as nothing is currently showing up on the webpage. This is how my code a ...

Attempting to create a hexagon using 127 divisions results in a gap

I am faced with a challenge of arranging 127 divs to form a hexagon shape similar to the example below: for (i = 1; i <= 127; i++) { var div = document.createElement('div'); document.getElementsByTagName('body')[0].appendChild( ...

Creating a Responsive Design with Bootstrap 4 - Adjustable Height Structure

I am facing an issue with my website built on Bootstrap 4. I am trying to make a layout that utilizes the full height of the screen. I had expected the new "flex" grid system in Bootstrap 4 to facilitate this, but it seems like I might be implementing it i ...

What is the best way to create a line graph with D3.js in order to display data that is obtained from a server-side source?

I am trying to access data from a server side link, which is as follows: The data I want to retrieve is in JSON format and looks like this: {"Id":466,"Name":"korea", "Occurren ...