1

I created a responsive search button that will open a form once a user click on it but in mobile devices the form should appear without the need of the user to click on any button.

I was able do it by adding a class so on first click on the button the menu open and on second click it will submit the input.

The obstacle now is to add the active class just in mobile. What is the best way to do it? If it detected by userAgent that are mobile devices that has a larger screens (like tablets).

I know that there is option to do it by detecting the screen size of the device, the question what will be more efficient for my purpose or if there is any other way that I can achieve this thing.

Here is the relevant part of the code:

$(document).on('click', '.navbar-collapse form[role="search"]:not(.active) button[type="submit"]', function(event) {
  event.preventDefault();
  var $form = $(this).closest('form'),
  $input = $form.find('input');
  $form.addClass('active');
  $input.focus();
});
Yossi Aharon
  • 151
  • 1
  • 12

2 Answers2

2
if($(window).width()<768){
    $("body").addClass("mobileview");
} 
else {
    $("body").removeClass("mobileview");
}
// this is used whenever the window is resized
$(window).resize(function(){
  if($(window).width()<768){
        $("body").addClass("mobileview");
    } 
    else {
        $("body").removeClass("mobileview");
    }
});
Navneet Kumar
  • 623
  • 1
  • 6
  • 16
0

You can check if the user is using a mobile device like this:

if( navigator.userAgent.match(/Android/i)
 || navigator.userAgent.match(/webOS/i)
 || navigator.userAgent.match(/iPhone/i)
 || navigator.userAgent.match(/iPad/i)
 || navigator.userAgent.match(/iPod/i)
 || navigator.userAgent.match(/BlackBerry/i)
 ){
   $form.addClass('active');

 // some code..
}
David
  • 1,084
  • 12
  • 36
  • I edited my question. There are mobile devices with these userAgents that has a larger screens so I'm looking for a soultion that will based also on the screen size of the device. – Yossi Aharon Feb 27 '19 at 11:02