简体   繁体   中英

Toggling text of “a href” based on screen width

Using jQuery/jQueryMobile, I have a link as follows:

<a href="index.html" id="HomeLink" data-role="button" data-mini="true" data-icon="home" data-iconpos="top" >Home</a>

I am trying to test various screen sizes, and if the screen width is less than 300px, I want to change:

data-iconpos="top"

to

data-iconpos="notext"

so I only get the icon. I have tried to do it with JavaScript:

var hl = document.querySelector('#HomeLink');
if ($(window).width() < 300) {
    hl.setAttribute("data-iconpos", "notext");
} else {
    hl.setAttribute("data-iconpos", "top");
}

But it won't work.

Question: can it be done in CSS instead.

If not: how can it be done in JavaScript?

You can't really set a data attribute with CSS as far as I know, but since you're already using jQuery, why not try it all the way :

$('#HomeLink').data('iconpos', ($(window).width() < 300 ? 'notext' : 'top') );

Remember to wrap that in document ready!

You can do this way altering your code:

    var hl = $('#HomeLink');
    if ($(window).width() < 300) {
        hl.data("iconpos", "notext");
    } else {
        hl.data("iconpos", "top");
    }

with .attr() :

    var hl = $('#HomeLink');
    if ($(window).width() < 300) {
        hl.attr("data-iconpos", "notext");
    } else {
        hl.data("data-iconpos", "top");
    }

Try to wrap the code in window resize event, eg:

$(window).resize(function () {
check();
})
$(function () {
check();
})

function check() {
if ($(window).width() < 300) {
    $('#HomeLink').attr('data-iconpos', 'notext');
} else {
    $('#HomeLink').attr('data-iconpos', 'top');
}
}

I would like to suggest using a different approach.

The data-iconpos="top" looks a bit out of place to me here. I have a feeling (perhaps I'm wrong) that you're attempting to inline your styling into the HTML.

Why not try media queries?

@media screen and (max-width: 300px) {
    #HomeLink {
        /* styling for HomeLink when screen width is less than 300px */
    }
}

This is a CSS-only solution. It works if the user decides to resize the screen after the page has loaded. Try resizing the "Result" frame in this jsfiddle and notice the color of the link changing.

Suggested reading:

And here are the docs on media queries: http://www.w3.org/TR/css3-mediaqueries/

Warning : mind ahem, IE below 9, ahem...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM