1

I am wanting to change the download link based on a device width (mobile, tablet, pc) What js would I need to accomplish this?

<a href="url" onclick="function"; class="btn btn-primary js-scroll-trigger download">Download</a>
Eddie
  • 26,593
  • 6
  • 36
  • 58
Turnt Ducky
  • 23
  • 1
  • 7

3 Answers3

4

In this answer you learn that there are many method of obtaining the device width in js. One of the best them is the one below:

const mq = window.matchMedia( "(min-width: 500px)" );

if (mq.matches) {
  // window width is at least 500px
} else {
  // window width is less than 500px
}

So you can do something like (resize window to test for small size):

var a_element;

function changeHref() {
    const mq = window.matchMedia( "(min-width: 500px)" );
    a_element = document.querySelector(".download");
        
    if (mq.matches)
        a_element.href = "http://www.google.com";
    else
        a_element.href = "http://www.duckgogo.com";

}
changeHref();
console.log(a_element.href);
<a href="url" onclick="function"; class="btn btn-primary js-scroll-trigger download">Download</a>
Nelson Teixeira
  • 6,297
  • 5
  • 36
  • 73
1

Dont use width in javascript. Have 3 anchor tags, show only 1 at once using media queries width

<a onclick="function1()"; class="showOnDesktopOnlyUsingMediaQuery">Download Desktop</a>
<a onclick="function2()"; class="showOnTabletOnlyUsingMediaQuery">Download Tablet</a>
<a onclick="function3()"; class="showOnMobileOnlyUsingMediaQuery">Download Mobile</a>
dota2pro
  • 7,220
  • 7
  • 44
  • 79
1

You can accomplish without even using JavaScript. CSS Media Queries are designed exactly for this type of thing. You make 3 separate <a> tags, and alternate between display:inline or display:none based on the media queries. For example, on a mobile screen, both the desktop and tablet links will be set to display:none while the mobile link will be set to display:inline.

But if you really need to use JS though, you can do something like the following.

HTML:

 <a href="#" id="link-change" class="btn btn-primary js-scroll-trigger download">Download</a>

JavaScript:

var link = document.getElementById("link-change");

var mobile = "url-mobile";
var tablet = "url-tablet";
var desktop = "url-desktop";

link.onclick = function(){
   if(screen.width < 768){
      link.href = mobile;
   } else if(screen.width < 1024){
      link.href = tablet;
   } else {
      link.href = desktop;
   }
}

You may need to change the breakpoints (1024px, 768px) I just used those off the top of my head for this example.

ryan.kom
  • 167
  • 1
  • 15