0

I'm wanting to echo some code based on whether the user is on a mobile device (less than 768px) or larger.

I have done the following:

            <?php  
              if ( is_home() ) {
            ?>
              <script type="text/javascript">
              if ($(window).width() < 768) {
                  document.write("<?php echo my_shortcode("[mobile-slider]"); ?>");
              } else {
                  document.write("<?php echo my_shortcode("[desktop-slider]"); ?>");
              }
              </script>
            <?php                    
            } else {
              //do the stuff for the other pages

            } ?>

But now when the homepage renders it displays "); } else { document.write(" then the homepage slider and then "); }. Any idea why?

JS error

SyntaxError: unterminated string literal

document.write('

HTML Output - Seems to be adding a line break which I think is breaking the script?

<script type="text/javascript">
if ($(window).width() < 768) {
document.write("
<!--slider--> 
DT.DTDG
  • 765
  • 1
  • 13
  • 31

3 Answers3

0
"<?php echo my_shortcode("[mobile-slider]"); ?>"

CHANGE TO

"<?php echo my_shortcode('[mobile-slider]'); ?>"
                         ^               ^  // changed quotes here

or escape quotes

"<?php echo my_shortcode(\"[mobile-slider]\"); ?>"
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
  • I tried that and it still did the same thing :( That's why I tried using double quotes because the PHP executes regardless. Thanks @TusharGupta – DT.DTDG Sep 30 '13 at 01:47
0

try this:

document.write(<?php echo "\"[mobile-slider]\""; ?>);
Vincent
  • 555
  • 10
  • 22
0

Well your quotes are definately off, as others have mentioned, your inner quotes must be different from the outer ones, or escaped.

Is it possible for you to run your php function in the main document(outside of the javascript), then choose to show/hide/alter its contents with the javascript?

If that's not possible, try calling your function directly, instead of through the do_shortcode hook.

As a final alternative, you may need to use an ajax call here. I don't know that you're able to call shortcodes the way you're attempting to do here.

JammGamm
  • 151
  • 1
  • 5