Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make an HTML element clickable only at certain screen sizes

I'm trying to convert an old, custom-built web site to be responsive. I've got the main bulk of the CSS work done and can get the sizings and positioning that I want for the most part. There's one last piece that's giving me grief.

I have a series of news articles displayed on the page. When I go to mobile phone-size displays, I really want those headings to become "clickable" so that I can use them to show/hide the detail of the article. But I don't want those headings to be clickable at larger screen sizes.

The basic layout of each article is...

<article id="article-001">
    <div class="newsArticleTitle">Title goes here</div>
    <div class="newsArticleTeaser">
        <p>
            Teaser paragraph</p>
    </div>
    <div class="newsArticleContent">
        <p>
            Paragraph 1</p>
        <p>
            Paragraph 2</p>
    </div>
</article>

The relevant CSS that controls the display of those articles as the screen size reduces are...

@media only screen and (max-width: 479px) {
    .newsArticleTeaser {
        display: none;
    }
}


@media only screen and (max-width: 319px) {
    .newsArticleContent {
        display: none;
    }
}

...so that at the narrowest screen sizes, only the article title is visible. I then need/want that article title (the div with class="newsArticleTitle") to then become a clickable item such that the visibility of the teaser and content will be toggled.

Is there a sane way to make that happen? My fallback method will probably be to duplicate the heading element - once with an <a> tag wrapping it, once without - and toggle the visibility of those two with CSS. That feels wrong though.

Has anyone solved this more elegantly or got any suggestions for a better way of designing this?

like image 456
Bignose Avatar asked Dec 14 '22 15:12

Bignose


1 Answers

You can use the css property pointer-events: none in combination with media queries:

.elementToClickInMobile {
    pointer-events: none;
    @media all and (max-width: 460px) {
        pointer-events: all
    }
}

this would prevent any click event in larger screens than 460px

EDIT// as correctly suggested this works >IE10

fallback for older (outdated) browser you could use

$("elementToClick").click(function(e){
    var outerWidth = window.outerWidth
    if (outerWidth > 480) {
        e.preventDefault(); //for browsers
        e.returnValue = false; //for IE
        return false
    }
});

JS not tested, so feel free to comment further suggestions!

EDIT2// found a neat fallback for IE7+ pointer events including a preventClick() method! https://github.com/vistaprint/PointyJS

like image 131
Doml The-Bread Avatar answered May 19 '23 19:05

Doml The-Bread