Different link in button for desktop/mobile only with css class

i have WordPress site with Elementor and i need set in button different link for mobile and desktop version. It´s custom component, so there is not possible edit html code, add ID or CLASS (for future updates).

html code is:

<a href="http://link.cz/" class="theme-btn btn-style-four"><span class="txt">Rezervovat</span></a>

is it possible to link this html code to javascript so that the links are different in the mobile and desktop version?

2 answers

  • answered 2021-06-18 18:21 Spectric

    You could try checking whether the window's innerWidth is smaller than a certain width, and if it is, change the href attribute:

    document.querySelector('a').href = window.innerWidth <= 480 ? "https://mobilelink.com" : "https://desktoplink.com";
    <a href="http://link.cz/" class="theme-btn btn-style-four"><span class="txt">Rezervovat</span></a>

  • answered 2021-06-18 18:30 s.kuznetsov

    Use method window.matchMedia(), which takes a media expression as an argument.

    The Window interface's matchMedia() method returns a new MediaQueryList object that can then be used to determine if the document matches the media query string, as well as to monitor the document to detect when it matches (or stops matching) that media query.

    let link = document.querySelector(".theme-btn.btn-style-four");
    
    if (window.matchMedia("(max-width: 767px)").matches) {
        link.setAttribute("href", "http://link_mobile.cz/");
    } else {
        link.setAttribute("href", "http://link.cz/");
    }
    <a href="http://link.cz/" class="theme-btn btn-style-four"><span class="txt">Rezervovat</span></a>