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, not jquery.
  • 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:

https://jsfiddle.net/tu60wbbu/13/

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

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -