1

I'm trying to load a Bootstrap carousel only if the screen size is larger than 768px (larger than a mobile device), but having a little trouble with the JavaScript.

I have the html element with the ID "hideIfScreenSmall" and an onload() event that fires the JS function loadCarousel(). The function is supposed to populate the <div> with HTML that two more nested <div> elements (the carousel and the photos in the carousel). When I load my page, the carousel isn't showing up and I'm wondering if I have a simple syntax error that I can't spot (maybe with the escape characters?) or if there's a larger issue here.

<div id="hideIfScreenSmall" onload="loadCarousel()">
</div>

<script>
    function loadCarousel(){
        if(screen.width >= 768){
            document.getElementById("hideIfScreenSmall").innerHTML = "<div class=\"sectional_home-slider hidden-xs\"><div class=\"container full-md\"><?php echo do_shortcode('[rev_slider alias=\"comic_slider\"]');?></div></div>";
        }
    }
</script>

Is there something I'm writing wrong, or maybe an easier way to prevent a <div> from loading if the user is on a smart phone? I'm not looking for a simple "display:none" fix because that still loads the element and just doesn't display it. I'm going for website optimization here. I'm still pretty new to JS and PHP, so hopefully it's just an easy fix. Thanks guys!

UPDATE Thanks to @DanieleAlessandra I was able to get an image to populate the innerHTML. However, it still won't populate with my PHP. I've tried different variations of escape characters to no avail. Below is a link to a screenshot of the DevTools window and the code that's coming up on the other side. Anyone know what I can do to make the PHP active?

Chrome DevTools Screenshot

  • 2
    Look at the source code when the page loads, and if there's anything in the browser's developer console. PHP runs before the page is loaded, and javascript after, so you'll be able to see what it's supposed to be doing. – aynber Jun 24 '19 at 16:59
  • 1
    Possible duplicate of [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – MonkeyZeus Jun 24 '19 at 16:59
  • 1
    php runs server-side, javascript runs client-side. So you're better off including the markup in your html so that php can render what's inside – inorganik Jun 24 '19 at 21:24
  • So what you're saying is that there's no way to change the PHP once the page is loaded? At least not using JS/jQuery? – Danny the Hopeless Jun 24 '19 at 21:55

2 Answers2

1

You cannot use onload event on div, it doesn't work.

You may use onload on body or you may want to attach a callback to document.ready event using jQuery:

$(document).ready(function(){
   loadCarousel();
});

Or maybe without jQuery*:

function ready(fn) {
  if (document.attachEvent ? document.readyState === "complete" : document.readyState !== "loading"){
    fn();
  } else {
    document.addEventListener('DOMContentLoaded', fn);
  }
}

ready(loadCarousel);

Source of snippet: http://youmightnotneedjquery.com/

DanieleAlessandra
  • 1,380
  • 1
  • 12
  • 21
  • Works great, thanks! I got it to load a single image on the page by populating the `
    ` with a simple ``, however I can't seem to get the PHP to work. Can you see any part of the `innerHTML` string that would cause a syntax error?
    – Danny the Hopeless Jun 24 '19 at 20:42
  • Check quotes around _comic_slider_ they shoud not be escaped: `` – DanieleAlessandra Jun 25 '19 at 08:02
  • This was very helpful. Turns out the PHP won't load at all because of the server-side/client-side difference, but I was able to rewrite the code I was trying to execute so it worked using the .ready function. Thanks! – Danny the Hopeless Jun 28 '19 at 15:41
0

Hello Danny the Hopeless,

My first tasks were related to the revision of the onload event in the div#loadThisWhenPageLoads element and as DanieleAlessandra pointed out this is not an effective approach.

Next, in reviewing your question thoroughly, I realized that your actual goal here seems to be merely able to achieve the functionality that shows and removes a Bootstrap carousel depending on the screen size. Now that is a different task altogether in my view. With that said, I think an approach that leverages the CSS3 display property and @media queries is the most practical and effective way to resolve the task at hand. Below you can find the code I created for this particular purpose.


JSFiddle Resolution Demo:

JSFiddle link demo


Full Code Snippet:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <!--
        Bootstrap CSS Loaded from CDN.
        Note: You can load the Bootstrap CSS from anywhere you want (CDN, locally, etc.). In my case, I am using a CDN as it is easy to implement so I can quickly move on and work on what matters -resolving the issue at hand.
    -->
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <title>Arty's StackOverflow Question 56740953</title>
</head>
<body>

<h1>StackOverflow Question 56740953 Resolution</h1>

<h2>Goal</h2>

<p>
    Load a Bootstrap carousel only if the screen size is larger than 768px (larger than a mobile device).
</p>

<h3>Basic Approach (CSS3 display/media-query):</h3>

<ol>
    <li>Load hidden carousel (display: none). </li>
    <li>Use CSS3 media query to show carousel when screen size is larger than desired with (768px).</li>
</ol>

<h2>Resize browser screen to see demo in action:</h2>

<style>
/*
** Micro-style choice to improve body visibility.
** Remove this style script when ready to use and resize body as needed.
*/
body {
    padding: 20px;
}
/*
** Micro-style choice to reduce slider size for this demo.
** Remove this style script when ready to use and resize carousel as needed.
*/
#carouselExampleIndicators {
    width: 80vh;
    margin: 0 auto;
}
</style>

<!--
    Bootstrap Carousel Example With indicators.
    Source: https://getbootstrap.com/docs/4.0/components/carousel/
    Note: I am using "placeimg" to load dummy images easily for this demo.
    Source: https://placeimg.com/
-->
<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
    <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
</ol>
<div class="carousel-inner">
    <div class="carousel-item active">
    <img class="d-block w-100" src="https://placeimg.com/640/480/any" alt="First slide">
    </div>
    <div class="carousel-item">
    <img class="d-block w-100" src="https://placeimg.com/640/480/any" alt="Second slide">
    </div>
    <div class="carousel-item">
    <img class="d-block w-100" src="https://placeimg.com/640/480/any" alt="Third slide">
    </div>
</div>
<a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
</a>
</div>

<style>
#carouselExampleIndicators {
    display: none;
}
@media screen and (min-width: 768px) {
    #carouselExampleIndicators {
        display: block; /* "block" is the default display property value for this Bootstrap carousel div. */
    }
}
/*
    The following sources are recommended concerning the CSS3 display property and @media queries. Also,please note that the order matters when it comes to the @media queries so moving the @media... piece of code arbitrarily anywhere before the code that defines the styles for the elements referred within the @media styles can affect the functionality detrimentally.
**
** Source: https://www.w3schools.com/css/css_display_visibility.asp
** Source: https://www.w3schools.com/css/css3_mediaqueries.asp
*/
</style>

<!--
    Bootstrap JavaScript Bundle Loaded from CDN.
    Note: You can load the Bootstrap CSS from anywhere you want (CDN, locally, etc.). In my case, I am using a CDN as it is easy to implement so I can quickly move on and work on what matters -resolving the issue at hand.
    Source: https://www.bootstrapcdn.com/
-->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>

</body>
</html>

This as certainly an interesting challenge. If you have any issues implementing the approach I have recommended please feel free to let me know and I would be glad to assist you further. Also, if for whatever reason you are interesting in continuing to seek an approach that is related loading the carousel element via Javascript and/or inserting PHP code dynamically to accomplish this end, let me know as well and I would look into this matter further with you. There are certainly many paths to web development and the CSS3 approach seemed the most straightforward for the challenge you have at hand, which is why I have recommended it, but I am happy to help you look into other alternate solutions that might better suit your specific needs.

Regards,

Arty

  • Does this prevent the images from loading or does it just hide them? – Danny the Hopeless Jun 24 '19 at 20:43
  • Technically, the design works like this: 1) HTML doc is loaded (this includes the Bootstrap carousel, images, etc.) 2) The CSS3 display property comes in and immediately hides the Bootstrap carousel (including the images, etc). 3) The CSS3 media property comes in and checks the screen size. If it finds that the screen is greater than the specified number of pixels (786, per your request) it will change the value for the carousel element from "display:none" (hidden) to "display:block" (visually present in the html document for the users to interact with it). Otherwise it stays hidden. – Arty Stable Jun 24 '19 at 21:23
  • So, there is a small flaw in this architecture from the perspective that the carousel is ALWAYS being loaded, which might arguably be an undesired characteristic considering that this might cause a detrimental performance. For example, if the HTML doc is going to be primarily viewed from a small screen device, we know that the carousel will not be presented to the users most of the time so merely hiding the feature is detrimental as it might be better to not include this element altogether. – Arty Stable Jun 24 '19 at 21:37
  • Then perhaps utilize JavaScript to insert the element into the HTML doc if the user is using a larger screen size. I believe you were working from this perspective, which is definitely valuable. – Arty Stable Jun 24 '19 at 21:37
  • That being said, I thought that the impact in loading time/resource usage might be so insignificant that this approach still holds quite functional for most use cases. However, if you think that you are going to have a lot of traffic coming in to your website/html resource and that the web page/app will be affected significantly by this design choice, we can certainly look into a JavaScript version that simply checks the screen size and inserts/removes the element based on this value. – Arty Stable Jun 24 '19 at 21:37
  • This might be a slightly better approach from the architectural perspective albeit more costly in terms of spending a few extra cycles on the architecture for the sake of a very low-yield outcome. Think of it as spending one year to make a rocket that gets to the moon 3 minutes earlier than the previous model. Haha. Either way, this is definitely an interesting challenge so if you want to look into the other approach, I am happy to help you with that as well. Just let me know :) – Arty Stable Jun 24 '19 at 21:38