Grow your CSS skills. Land your dream job.

Last updated on:

Test if Mac or PC with JavaScript

User Agent testing sucks, but sometimes you need it for subtle things. In my case I was using it to adjust what I was showing for keyboard shortcut keys (Command or Control). Nothing super major.

if (navigator.userAgent.indexOf('Mac OS X') != -1) {
  $("body").addClass("mac");
} else {
  $("body").addClass("pc");
}

The statements in there use jQuery to add a body class, but that's not required, you could do whatever.

Comments

  1. This may be overkill for your intended use, however it really comes in handy if you need to nudge items or if things aren’t quite right on mobile devices.

    http://rafael.adm.br/css_browser_selector/

  2. Trying to solve the same problem of showing Cmd vs Ctrl, I found this snippet. But what if someone uses Linux on a Mac (with a Mac keyboard)? I have posted this question on stackoverflow as well.

  3. Aalekh

    would like to add that we can also add navigator object with platform property…….object.platform…it can specifically tell for ex: wether it is macintosh 68k or windows 64bit…..

  4. just what a needed to check if it’s a MAC for an .exe file download link (to put a different link for macs)

    • Will
      Permalink to comment#

      You can set a class in combination with a file type selector

      .mac a[href$=".dmg"] { STLYE }
      .pc a[href$=".exe"] { STLYE }

      Is this what you are shooting for?

  5. Permalink to comment#

    Thanks Mate, It really saved my couple of hours.

Leave a Comment

Posting Code

  • Use Markdown, and it will escape the code for you, like `<div class="cool">`.
  • Use triple-backticks for blocks of code.
    ``` 
    <div>
      <h1>multi-line block of code</h1>
      <span>be cool yo.</span>
    </div>
    ```
  • Otherwise, escape your code, like <code>&lt;div class="cool"&gt;</code>. Markdown is just easier though.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".