jquery - Replacing Image Source Value With a PHP Variable Based on Device Width -


i'd able able swap img's src value variable created in php.

i using javascript determine device width. happening within .php file containing wordpress loop. upon recognizing device width, change img's src value accordingly.

i can retrieve php variables using js function when function written in loop, , know, duplicate function each post , resulting in error.

i need able calculate these given php variables outside loop , inject them img src value inside loop.

i recognize may have more errors in code looking resolve! have been working on time , particular issue has become quite troubling. in advance.

current code in use:

<?php query_posts( array ( 'home' => 'wordpress themes', 'orderby' => 'rand', 'posts_per_page' => -1 ) ); ?> <?php while ( have_posts() ) : the_post(); ?>   <script>     function getimagepath(){       if (window.matchmedia('(max-device-width: 1920px)').matches) {         var thesizedimage = <?php the_field('desktop_image'); ?>       }if (window.matchmedia('(max-device-width: 1280px)').matches) {         var thesizedimage = <?php the_field('tablet_image'); ?>       }if (window.matchmedia('(max-device-width: 600px)').matches) {         var thesizedimage = <?php the_field('mobile_image'); ?>       }       return thesizedimage;     }     </script>    <img src="pixel.gif" onload="this.onload=null; this.src=getimagepath();"  /> <?php endwhile; wp_reset_query(); ?> 

so after further tinkering, able come solution. in fact work, wonder if there far more elegant solution. note query has changed improved page , took care of errors. main problem above code variables image urls getting defined once. solution have provided below rerun each of posts in loop.

<?php query_posts( array ( 'category__not_in' => array( 1, 4, 5, 6, 7 ), 'orderby' => 'rand', 'posts_per_page' => -1 ) ); ?> <?php while ( have_posts() ) : the_post(); ?>     <script>        if (screen.width <= 1920) {document.write("<img src='<?php the_field('desktop_image');?>'   />");}        if (screen.width <= 1280) {document.write("<img src='<?php the_field('tablet_image');?>'  />");}        if (screen.width <= 600) {document.write("<img src='<?php the_field('mobile_image');?>'  />");}        if (screen.width > 1920){document.write("<img src='<?php the_field('full_resolution');?>'  />");}     </script> <?php endwhile; wp_reset_query(); ?> 

Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -