Home > Blockchain >  How to run this jquery function only on desktop
How to run this jquery function only on desktop

Time:05-07

I'm a begginer in Javascript and I kindly need your help with this Jquery script I'm working on..

I need to make it work only on desktop and prevent it to run in tablet/mobile.

If anyone can help me with this that will be wonderful. Thank you very much!

<script>
/*Project Collection Section*/
// Page Load
$('.grid-card').eq(0).addClass('current');
$('.grid2-item').eq(0).addClass('current');
$('.grid-image').eq(0).addClass('current');

function changeFocus(trigger) {
    $('.current').removeClass('current');
    trigger.addClass('current');
    let myIndex = trigger.closest('.grid1-item').index();
    $('.grid2-item').eq(myIndex).addClass('current');
    $('.grid-image').eq(myIndex).addClass('current');
}

$('.grid-card').on('mouseenter', function() {
  changeFocus( $(this) );
});

$('.scroll-trigger').on('inview', function(event, isInView) {
  if (isInView) {
    let myTrigger = $(this).closest('.grid-card');
    changeFocus( myTrigger );
  } else {
        // do something else
  }
});
</script>

CodePudding user response:

Well you can write a javascript function that returns whether the user is on a desktop device or not from the user agent.

you can do something like this

function isDesktop() {
  const ua = navigator.userAgent;
  return !/(tablet|ipad|playbook|silk)|(android(?!.*mobi))|(Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini))/.test(
    ua
  );
}

CodePudding user response:

you can use the following code:

 <script>
  var isDesktop = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(
    navigator.userAgent
  )
    ? false
    : true;
  if (isDesktop) {
    /*Project Collection Section*/
    // Page Load
    $(".grid-card").eq(0).addClass("current");
    $(".grid2-item").eq(0).addClass("current");
    $(".grid-image").eq(0).addClass("current");

    function changeFocus(trigger) {
      $(".current").removeClass("current");
      trigger.addClass("current");
      let myIndex = trigger.closest(".grid1-item").index();
      $(".grid2-item").eq(myIndex).addClass("current");
      $(".grid-image").eq(myIndex).addClass("current");
    }

    $(".grid-card").on("mouseenter", function () {
      changeFocus($(this));
    });

    $(".scroll-trigger").on("inview", function (event, isInView) {
      if (isInView) {
        let myTrigger = $(this).closest(".grid-card");
        changeFocus(myTrigger);
      } else {
        // do something else
      }
    });
  }
</script>
  • Related