2

I'm having a funny issue, I'd like to remove the <br> under 760px width resolution. I've been using this which always worked, however it doesn't work on a new website I'm working on.

$(function() {
    if ($(window).width() < 760) {
        $('p.nobreak br').replaceWith(' ');
        $('span.vert-align.centerone br').replaceWith(' ');
    }
});

The funny part is if instead of < 760 I change by > 760 (for higher resolution) and it does work! But I need this for < 760. Any advice guys?

2 Answers 2

1

Your current code works, but only for the resolution the window is loaded at. You need to apply your logic in the resize event handler so that it reacts as the window size is changed. Try this:

$(function() {
    var timer
    $(window).resize(function() {
        clearTimeout(timer);
        timer = setTimeout(function() {
           if ($(window).width() < 760){
               $('p.nobreak br, span.vert-align.centerone br').replaceWith(' ');
           }
        }, 100);
    });
});

Note however that a much better solution is to use CSS media queries to do this. It's faster, and also allows the effect of the <br /> tags to be applied again if the window is made larger. Try this:

<p>
    Lorem ipsum
    <br />dolor sit amet
</p>
@media (max-width: 760px) {
    p.nobreak br, 
    span.vert-align.centerone br {
        content: ' '
    }
    p.nobreak br:after, 
    span.vert-align.centerone br:after {
        content: ' '
    }
}

Working example (drag the result panel size handles to see the effect in action)

Sign up to request clarification or add additional context in comments.

Comments

0

Why wouldn't you use media queries to hide these elements instead of javascript?

Something like this for example:

@media screen and (max-width:760px) {
    p.nobreak br, span.vert-align.centerone br { display: none; }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.