How to link to a alternative page in CSS

Two options.

The first would be as you said to determine the browser size using javascript. Then have your code do something where it changes the link if the browser us either above or below a certain size.

The second, and this may be your preferred method, would be to use css. If your theme has the body tag written like so <body <?php body_class(); ?>> then you will have the following class added to your page: page-id-164.

Set up your template so it has both options and wrap them each in a div with a unique class or id.

Set display:none; on one, and then the correct css on the other. Then in the code with @media only screen and (min-width: 1500px) { do the reverse. The issue is that you are loading a lot of unnecessary code as people will only see one or the other.

If you are referring to separate pages completely, including the headers, then I’d recommend doing the javascript option. Here’s the code using jQuery, which you will want to place within your ready function on a theme jquery scripts file, if there is one. You also may need to adjust the < to a > depending on when you want javascript to make the switch.

if ( $(document).width() < 1500 ) {
    $('.change-link > a').each( function(){
        newlink = 'Enter New URL';
        $(this).attr('href',newlink);
    });
}

Remember if you are putting this in your code, and it errors with $ isn’t defined, then you need to change the $ to jquery.

If you want to place this within your theme as inline js, then you would do the following:

<script type="text/javascript">
jQuery(document).ready(function($) {
    if ( $(document).width() < 1500 ) {
        $('.change-link > a').each( function(){
            newlink = 'Enter New URL';
            $(this).attr('href',newlink);
        });
    }
});
</script>

Or if you want it called in as a separate js file, then create the file as shown below, you would put the following in functions.php:

function my_enqueue_js(){
    wp_register_script('newlink', get_template_directory_uri().'FILE IN THEME DIRECTORY.js');
    wp_enqueue_script('newlink', array('jQuery'), '1.0', true);
}
add_action('wp_enqueue_scripts', 'sta_enqueue_js');

Then have the following code in your js file and place the file in your theme directory:

jQuery(document).ready(function($) {
    if ( $(document).width() < 1500 ) {
        $('.change-link > a').each( function(){
            newlink = 'Enter New URL';
            $(this).attr('href',newlink);
        });
    }
});

Leave a Comment