javascript - How to use .load to .prepend content without page refresh? -
i'm trying use jquery load content if viewport above specified width.
this works, not quite right. check out jsfiddle link @ bottom working demo.
here's have far;
- if viewport below 500px #wrapper hidden
media query
. - above 500px #wrapper set
visibility: visible;
- jquery looking
element.is(':visible')
. when happens jquery loads image. - resizing browser window activates
media query
, notjquery
. - the
jquery
fires on page refresh.
i've tried using $( window ).resize(function()
fires every time viewport changes size, duplicating content.
is there way activate jquery
without page refresh?
the ideal solution be;
- up 500px load nothing,
- when viewport resized above 500px load jquery.
- if viewport resized below 500px unload jquery content.
html
<p>css hides <strong>#wrapper</strong> if viewport below 500 pixels.</p> <div id="wrapper"> <p>jquery checks css see if <strong>#wrapper</strong> visible , loads image on page refresh.</p> <p>i'm looking way run function without needing refresh page. i've looked using (resize) function, duplicate content.</p>
css
#wrapper { visibility: none; display: none; } @media screen , (min-width: 500px){ #wrapper { visibility: visible; display: block; }}
jquery
$(function() { var element = $(this).find('#wrapper'); if (element.is(':visible')) { $('#wrapper').prepend('<img src="http://cache.desktopnexus.com/thumbseg/1134/1134934-bigthumbnail.jpg" alt="demo image">'); }
jsfiddle link:
you can use window.matchmedia()
instead of $(window).resize()
have javascript respond media query match in css.
https://developer.mozilla.org/en-us/docs/web/api/window/matchmedia
it's supported across browsers. http://caniuse.com/#search=matchmedia
if need support ie 9 or lower, might have fall using $(window).resize()
browsers.
Comments
Post a Comment