1

How can I insert a div dynamically based on the viewport parameter? As I need help with managing banner ads that are not responsive. For example the top divs for 728x90, 970x250, 160x600 would only load if the body client width is greater than 768 or else would load a 320x50 tag div instead.

Right now I am doing on web:

<div id="ezoic-pub-ad-placeholder-100">
<script type="text/javascript"><!--
               e9 = new Object();
    e9.size = "728x90";
//--></script>
<script type="text/javascript" src="http://tags.expo9.exponential.com/tags/ProWrestlingcom/ROS/tags.js"></script>
</div>

However, how it should work is when screen width is less than 768 it would show my 300 x 50 instead:

<script type="text/javascript"><!--

               e9 = new Object();

    e9.size = "320x50";

//--></script>

<script type="text/javascript" src="http://tags.expo9.exponential.com/tags/ProwrestlingcomMobile/320x50/tags.js"></script>

UPDATE:

I created this, which logically sounds like it should work but it doesn't display anything, unless there's something wrong with my browser. Can someone check?

<script>
window.onresize = function(){

var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');

if ( $(window).width() <= 767) {

e9 = new Object();
e9.size = "320x50";
script.src = "http://tags.expo9.exponential.com/tags/ProwrestlingcomMobile/320x50/tags.js";
head.appendChild(script);

}else {

e9 = new Object();
e9.size = "728x90";
script.src = "http://tags.expo9.exponential.com/tags/ProWrestlingcom/ROS/tags.js";
head.appendChild(script);

}
}
</script>
11
  • 2
    It shouldn't be necessary to have an HTML comment in the script block anymore. In fact I don't think it's really been necessary since 2000. Commented May 12, 2016 at 15:18
  • Can your share a link to your webpage ? I can't reproduce your ads showing up. Commented May 17, 2016 at 18:34
  • @PinkTurtle prowrestling.com. It doesn't have the code showing live since it was not showing the banners. So I reverted to original supplied code from ad network. The section I am changing is the banner ad below the navigation bar. Commented May 17, 2016 at 18:38
  • I think you can load both ads dimensions and show/hide them based on window resize. Does that make sense ? Are you able to display both ads size at the same time ? Commented May 17, 2016 at 18:43
  • @PinkTurtle That makes sense. I wouldn't want to display both ad sizes at the same time since the 300x250 is specifically for mobile only. I was thinking of perhaps scrapping the javascript since it doesn't work and switch to CSS, so I can just have the 728x90 resized to fit all screens. Will have to research that method more though. As the 728 pays out more than 300, so it would make sense to keep it if at all possible. Commented May 17, 2016 at 19:40

10 Answers 10

4
+50

Ad script creates several global variables: e9Manager, e9AdSlots, e9Loader and then checks if they are initialized: if (e9Loader === undefined). If they are, script does nothing.

so if You really need to reload ads on resize (but why?), You should destroy all e9 global objects and reinit them.

<script>
    window.onresize = function(){
        console.log('resize');
        var head = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
        script.setAttribute('id', 'ad_script');
        e9 = new Object();
        e9Loader = undefined;
        e9Manager = undefined;
        e9AdSlots = undefined;

        var element = document.getElementById("ad_script");
        if (element) {
            element.parentNode.removeChild(element);
        }   
        if ( window.innerWidth <= 767) {
            e9.size = "320x50";
            script.src = "http://tags.expo9.exponential.com/tags/ProwrestlingcomMobile/320x50/tags.js";
            head.appendChild(script);
         } else {
            e9.size = "728x90";
            script.src = "http://tags.expo9.exponential.com/tags/ProWrestlingcom/ROS/tags.js";
            head.appendChild(script);
        }
    }
    window.onload = function(){
        window.onresize();
    };
</script>

Something like this should work. However, I would sugest to do it only one, when page loads

Sign up to request clarification or add additional context in comments.

1 Comment

I was also thinking along the same line first you should load it in on load then on resize
0

I think Window.matchMedia() is your friend. This is it's API

You can create a rule like :

var mq = window.matchMedia( "(min-width: 500px)" );

And listen on window resize

window.onresize = function(){
  if(mq.match){ //show or hide what you need }
}

1 Comment

I added updated code. However it doesn't load anything, just empty space now.
0

Check the width of the client:

window.onresize = function(){
  if(window.innerWidth <= 767){ 
    // Code to display a DOM element.

  }
}

Comments

0

Something like this might work

function insertDiv(){
    var screenSize = document.width;
    var bannerWrapper = document.getElementById('bannerWrapper');

    if(screenSize > 1200){
        bannerWrapper.innerHtml('<div class="bigBanner">Buy this!</div>');
    }else if(screenSize > 600 && screenSize < 1999){
        bannerWrapper.innerHtml('<div class="mediumBanner">Buy this!</div>');
    }else if(screenSize < 599){
        bannerWrapper.innerHtml('<div class="smallBanner">Buy this! </div>');
    }
}

Comments

0

Your function in the updated question looks good, but it requires a resize event to be triggered in order for it to work, that's why nothing happens when the page loads.

Also, you need to figure out if loading another script would overwrite the functionality of the previous one (which would happen when you change sizes), and you should also clean up the previous script when then new one is added. (note that your code adds a new script to the page head each time a resize event happens)

It would've been much easier if you could load both scripts and then just choose which one to call, but since this looks like a 3rd-party API, it's probably not possible.

To fix the first issue I've mentioned, you just need to run the function you used for the resize callback when the page loads. You can define that code as a function, and then attach that function body to the resize listener, and execute it once manually:

function handleResize(){

  var head = document.getElementsByTagName('head')[0];
  var script = document.createElement('script');
  var e9 = new Object();    

  if ( $(window).width() <= 767) {
    e9.size = "320x50";
    script.src = "http://tags.expo9.exponential.com/tags/ProwrestlingcomMobile/320x50/tags.js";    
  } else {
    e9.size = "728x90";
    script.src = "http://tags.expo9.exponential.com/tags/ProWrestlingcom/ROS/tags.js";    
  }
}

head.appendChild(script);

window.onresize = handleResize; // attach it
handleResize(); // run it once

Comments

0

You can use https://github.com/krux/postscribe to render an ad after page load. Full working example:

<html>
<head>
    <title>Test</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/postscribe/2.0.6/postscribe.min.js"></script>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
    <script type="text/javascript">
        window.onresize = function(){
            $('#ezoic-pub-ad-placeholder-100').children().remove();
            if ( $(window).width() <= 767) {
                e9 = new Object();
                e9.size = "320x50";
                $(function() {
                    postscribe('#ezoic-pub-ad-placeholder-100', '<script src="http://tags.expo9.exponential.com/tags/ProwrestlingcomMobile/320x50/tags.js"><\/script>');
                });
            }else {
                e9 = new Object();
                e9.size = "728x90";
                $(function() {
                    postscribe('#ezoic-pub-ad-placeholder-100', '<script src="http://tags.expo9.exponential.com/tags/ProWrestlingcom/ROS/tags.js"><\/script>');
                });
            }
        }
        window.onload = function(){
            window.onresize();
        };
</script>

</head>
<body>
    <div id="ezoic-pub-ad-placeholder-100"></div>
</body>
</html>

The problem that it isn't possible to write into a document from an asynchronously-loaded external script. So postscribe decides this problem.

Comments

0

Using onresize handlers without debounce kills performance. It's really bad practice. Try to avoid this. For more info - http://bencentra.com/code/2015/02/27/optimizing-window-resize.html

Comments

0
<script>
var createAds = function() {
  var head = document.getElementsByTagName('head')[0];
  var script = document.createElement('script');
  script.id = "ads";
  head.appendChild(script);

  return script;
};

var resizeAds = function(){

  var ads = document.getElementById('ads') || createAds();

  var width = window.innerWidth || window.screen.width;

  // It seems that your .js needs to get the e9 global object
  window.e9 = window.e9 || new Object();

// HTTP ommitted for use the current protocol: http/https

  if (width <= 767) {
    window.e9.size = "320x50";
    ads.src = "//tags.expo9.exponential.com/tags/ProwrestlingcomMobile/320x50/tags.js";
  } else {
    window.e9.size = "728x90";
    ads.src = "//tags.expo9.exponential.com/tags/ProWrestlingcom/ROS/tags.js";
  }

};

resizeAds();
window.onresize = resizeAds;
</script>

Comments

0

This may not be what you were originally looking for, but why not give a shot to pure css?

Your goal is to display different ads based on user viewport. Using css you can very easily display/hide elements based on actual user resolution. You don't even have to catch any event or include any library. You can even make your ads responsive (again, very easily) or hide them when printing your page.

Html

<a href="#target-page" class="banner">
  <span class="shadow"></span>
  <span class="text">Banner</span>
</a>
<a href="#target-page" class="banner only-small-viewport">
  <span class="shadow"></span>
  <span class="text">small screen</span>
</a>
<a href="#target-page" class="banner only-large-viewport">
  <span class="shadow"></span>
  <span class="text">large screen</span>
</a>

CSS

.banner { 
  display: block;
  position: relative;
}
.banner .text {
  position: absolute;
  left: 0;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  text-align: center;
  font-size: 10vmax;
}
.banner .shadow {
  position: absolute;
  left: 0; right: 0; top: 0; bottom: 0;
  background-color: rgba(255,255,255, 0.8);
  transition: 1s background-color;
  z-index: 100;
}
.banner:hover .shadow {
  background-color: rgba(255,255,255, 0);
}

@media (max-width: 768px) {
  .banner.only-large-viewport { display: none; }
}
@media (min-width: 768px) {
  .banner.only-small-viewport { display: none; }
}


.banner {
  background-image: url("http://speciale-life.com/wp-content/uploads/2016/03/zoom-1-400x225.jpg");
  width: 400px;
  height: 225px;
}
@media (min-width: 736px) {
  .banner {
    background-image: url("https://s-media-cache-ak0.pinimg.com/736x/35/ae/b8/35aeb834c602ba9394e3163fe66cca9d.jpg");
    width: 736px;
    height: 414px;
  }
}
@media (min-width: 736px) {
  .banner {
    background-image: url("https://s-media-cache-ak0.pinimg.com/736x/35/ae/b8/35aeb834c602ba9394e3163fe66cca9d.jpg");
    width: 736px;
    height: 414px;
  }
}
@media (min-width: 1280px) {
  .banner {
    background-image: url("http://cfile22.uf.tistory.com/image/2571CB3856D7FA8138BAA1");
    width: 1280px;
    height: 721px;
  }
}

Here is jsFiddle

Comments

0

Two main issues.

  1. window.onresize runs every single time the browser size changes, even if it's by just a little bit, so that needs managing - you don't want it keeping on loading scripts all the time.

To solve this you can run the check every time the browser resizes but only actually do something when it's changed to a new size. You also ought to run the check when the page first runs, or you will be waiting for a resize event to fire as mentioned above.

var banner_current = "a";
function banner_check() {
    var screen_size = document.width;
    var banner_suggested = ""; 
    if (screen_size > 1200) {
        banner_suggested = "a";
    } else if (screen_size > 600){
        banner_suggested = "b";
    } else {
        banner_suggested = "c";
    }
    if (banner_suggested !== banner_current) {
        banner_load(banner_suggested);
    }
}
window.onresize = banner_check;
banner_check();
  1. Once you've added a script asynchronously you'll likely have to initialise it for it to work.

This will involve deleting or resetting any variables it's using and that it might check on startup, and also calling the init function. I don't know about your script specifically, but something like the following should work.

function banner_load(new_banner) {

    // check for existing script here and delete if present

    // create new script
    var script_new = document.createElement('script');
    switch(new_banner) {
        case "a":
            script_new.src = "https://new-script.com/js_a.js";
            break;
        case "b":
            script_new.src = "https://new-script.com/js_b.js";
            break;
        default:
            script_new.src = "https://new-script.com/js_c.js";
    }
    script_new.type = 'text/javascript';
    script_new.async = 'true';
    script_new.onload = script_new.onreadystatechange = function() {


         // check if vars defined and if so clear them, e.g:
         if (typeof e9Loader !== 'undefined') { e9Loader = null; }
         if (typeof e9Manager !== 'undefined') { e9Manager = null; }
         if (typeof e9AdSlots !== 'undefined') { e9AdSlots = null; }

         // run init function in new script

    };

    // load script
    var head = document.getElementsByTagName('head')[0];
    head.appendChild(script_new);

}

If you don't delete one file when adding the other you'll likely get conflicting variables and function names and then you'll struggle to get the new script running properly. This link gives a good outline on how to delete a file properly:

http://www.javascriptkit.com/javatutors/loadjavascriptcss2.shtml

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.