0

How to always listen to window.width() and load different HTML codes based on the width values? I'm using window.width() and replaceWith().

It's only works when I open the page and not working when I resizing my browser window.

My code inside my html file:

    var width;
    $(window).resize(function() {
        width = $(window).width();
        if (width < 768) {
            $("#the_dropdown").replaceWith("<p>Less than 768</p>");
        } else {
            $("#the_dropdown").replaceWith("<p> More than 768</p>");
        }
    });
    $(window).trigger('resize');

Demo

Another question, does replaceWith() suitable for situation that involves long HTML codes (more than 1 line)?

I've already done some sets of HTML codes based on specific window's width and I want to put it accordingly inside my #the_dropdown div.

8
  • 1
    It's possible in CSS with @media queries : w3schools.com/cssref/css3_pr_mediaquery.asp Commented Jan 12, 2015 at 20:17
  • As ceadreak mentions, you should use media queries or perhaps something like modernizr to detect and react. Commented Jan 12, 2015 at 20:19
  • That one is to change CSS based on window's width. I already know about that. I'm not changing my CSS. I'm changing my HTML based on specific window's width. Commented Jan 12, 2015 at 20:19
  • Just to give you a term to search. What you are asking for is responsive design. Commented Jan 12, 2015 at 20:19
  • Don't check window width, use instead window.matchMedia and any polyfill to support older browsers if needed developer.mozilla.org/en-US/docs/Web/API/Window.matchMedia Commented Jan 12, 2015 at 20:20

1 Answer 1

4

Your code doesn't work because replaceWith() replaces the selected element. In your case, the element with id #the_dropdown. Therefore on the next trigger, this element isn't found and no text is written.

Replace replaceWith() with .html().

Demo

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

1 Comment

So the OP should just be calling ` $("#the_dropdown").html("<p>Less than 768</p>")`

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.