1

Trying to change an href based on the screen size, This is what I've tried based on my research

My JS isn't great so I figure i'd ask

var productLink = document.getElementsByClassName('productlink');

function changeLink() {
  if (window.innerWidth < 1025) {
    productLink.setAttribute('href', "product-page-mobile.html");
  }
  else {
    productLink.setAttribute('href', "product-page-desktop.html");
  }
}

changeLink();
window.addEventListener('resize', changeLink);

edit:

Tried

var productLink = document.getElementsByClassName('productlink');
for(var i = 0; i < productLink.length; i++)


function changeLink() {
  if (window.innerWidth < 1025) {
    productLink.setAttribute('href', "product-page-mobile.html");
  }
  else {
    productLink.setAttribute('href', "product-page-desktop.html");
  }
}

changeLink();
window.addEventListener('resize', changeLink);

Still doesn't work :(

Edit: This works.

[].forEach.call(document.getElementsByClassName('productlink'), function(productLink) {
    if (window.innerWidth < 1025) {
        productLink.setAttribute('href', "product-page-mobile.html");
      }
      else {
        productLink.setAttribute('href', "product-page-desktop.html");
      }
});
Phil
  • 157,677
  • 23
  • 242
  • 245

0 Answers0